def test_08_less(self): x1 = 0.8888 x2 = 0.9999 eps = 1e-6 value1 = function(x1, eps) value2 = function(x2, eps) self.assertLess(value1, value2)
def d_net(x, reuse=True): act = lambda x: tf.nn.relu(tcl.batch_norm(x)) d0 = function(x, size=( 100, 50, ), name="d_net", act=act, reuse=reuse) return function(d0, size=1, name="d_net/out", reuse=reuse, use_bias=False)
def test_09_equal_100_random_values(self): for _ in range(100): x = random.random() * 2 - 1 x *= random.choice((-1, 1)) eps = 1e-15 expected_value = log(1 + x) value = function(x, eps) self.assertAlmostEqual(expected_value, value)
def __call__(self, x, h, scope=None): new_x, new_h = self._base_cell(x, h) proj_x = function(new_x, name="projection", size=self._projection_size, scope=scope, act=self._activation) return proj_x, new_h
def juliajudge(x=complex(0.5,1),c=0,t = 50): y=[] dx_temp = [] flag = 1 # iteration flag index = 0 temp, dx = function(x,c) radius, radian = cm.polar(temp) # print('index',index,'the function input:',x,c,'result',temp,'the dx:',dx,ma.fabs(dx)) while (index < t) & (radius < 2): y.append(temp) dx_temp.append(dx) temp,dx = function(y[index],c) # print('index',index,'the function input:',y[index],c,'result',temp,'dx',dx) radius, radian = cm.polar(temp) index = index + 1 pass if radius > 2: result = 0 # print('it is not in the julia set:',x,'iteration times:',index) pass else: result = 1; # print('find a julia set value:',x,'iteration times:',index) pass # plt.figure(1) # plt.subplot(121) # plt.plot(dx_temp,'r*-') # # plt.hold() # plt.xlabel('times') # plt.ylabel('dx') # plt.title('the dx trend') # plt.subplot(122) # plt.plot(y,'y*--') # plt.xlabel('times') # plt.ylabel('y') # plt.title('the y trend') # # plt.gridon() # plt.show() return result, index pass
def test_10_raise(self): with self.assertRaises(AssertionError): function(-1, 1) with self.assertRaises(AssertionError): function(0, 0) with self.assertRaises(AssertionError): function(10, 10)
def test_10_raise(self): with self.assertRaises(AssertionError): function(-1, 0.1) with self.assertRaises(AssertionError): function(0, 0) with self.assertRaises(AssertionError): function(20, -20)
def newFunction(self): if(len(self.tabButtons) <= 10 and self.whichScreen == "program"): self.function.append(function(name="func"+str(self.count), do=[])) self.count += 1 if len(self.tabButtons) != 0: x, y = (self.tabButtons[-1].x + 70, self.tabButtons[-1].y) else: x, y = (40, 60) self.tabButtons.append(Tab(x, y, self.function[-1].funcName)) self.switchFunctions(len(self.function) - 1) self.undoList.append(["function(name='func',param=[],do=[])"]) self.undoPosList.append(0) self.redrawAll()
def modelling_4( default="""В тот момент, когда Вы нажимаете кнопку, программа выбирает случаный банк с сайта banki.ru, после чего показывает все отзывы от пользоватлей о найденном учреждении, затем оценивает их эмоциональную окраску и выводит к нам на сайт.""", users="Введите ваш отзыв", rate="Ничего"): try: if request.method == "POST" and request.form[ "generate4"] == u"Сгенерировать": recall = rand_recall() default = recall[0] rate = function(default) except: pass try: if request.method == "POST" and request.form["rating4"] == u"Оценить": text = request.form["text"] users = text rate = function(text) except: pass return render_template('fourth_model.html', random_comment=default, user_recall=users, rate=rate)
def translate_function(ftree, glob, funcs): if ftree[2][0][0] == '*': ptr = True fname = ftree[2][1][0][0] fargs = list(map(cvmtypes.declarator, ftree[2][1][1])) else: ptr = False fname = ftree[2][0][0] fargs = list(map(cvmtypes.declarator, ftree[2][1])) fcode, flocals = translate_compound(ftree[3], glob, funcs) if 'void' in ftree[1]: fret = None else: fret = cvmtypes.typefor(ftree[1]) if ptr: fret = cvmtypes.cvmptr(fret) func = function(fname, [], fargs, fret, flocals) # Calculate storage required for stack frame func.frame_size = 0 local_addr_offsets = {} for cvmtype, name in fargs: local_addr_offsets[name] = func.frame_size func.frame_size += cvmtype.bytecount for name, cvmtype in map(lambda x: (x[0], x[1][0]), flocals.items()): local_addr_offsets[name] = func.frame_size func.frame_size += cvmtype.bytecount prepend = [] for cvmtype, name in reversed(fargs): prepend.append(('lstore', local_addr_offsets[name])) fcode = prepend + fcode for line in fcode: if len(line) > 1 and is_var(line[1]) and line[1][0] in local_addr_offsets: if line[0] in ['load', 'store']: func.code.append(('l%s' % line[0], local_addr_offsets[line[1][0]])) else: raise Exception('Accessed non-register memory in an instruction other' ' than load and store') else: func.code.append(line) return func
def main(): #plotSurf([], []) [Nx, Ny, ne, E, h, a, b] = funVar() w, sigma_max = function([a / 2, b / 2]) # DataFrame x = 1000 * h y = E / 1e6 z = ne f = 1000 * w narea = sigma_max / 1e6 columns = [ 'Thickness [mm]', 'Young Modulus [MPa]', 'Poisson Ratio', 'Bending [mm]', 'Max Tension [MPa]' ] assemble = pd.DataFrame(data=np.transpose([x, y, z, f, narea]), columns=columns) assemble_ = assemble.loc[(assemble['Bending [mm]'] < 30) & (assemble['Max Tension [MPa]'] < 1000)] print( f"{bcolors.HEADER}\nmaximum bend ={assemble_['Bending [mm]'].max():.2f}mm " + f"minimum bend ={assemble_['Bending [mm]'].min():.2f}mm{bcolors.ENDC}") print( f"{bcolors.HEADER}\nmaximum Tension ={assemble_['Max Tension [MPa]'].max():.2f}MPa " + f"minimum tension ={assemble_['Max Tension [MPa]'].min():.2f}MPa{bcolors.ENDC}" ) bubbles(assemble_.iloc[:, 0], assemble_.iloc[:, 1], assemble_.iloc[:, 2], assemble_.iloc[:, 3], assemble_.iloc[:, 4]) visualize_corr(assemble_) plt.show() input('\nEnd')
def initAnimation(self): self.x = -1 self.y = -1 self.size = 50 self.root.title("Visual Programming Language") self.error = "" self.count = 1 self.cx, self.cy = self.width/2, self.height/2 self.funcLine = self.cx + 100 self.functionNum = 0 self.function = [function(do=[])] self.undoList = [["function(name='func',param=[],do=[])"]] self.undoPosList = [0] self.Draggable = False self.tmpDrag = None self.initDashBoard() self.highLighted = None self.whichScreen = "start" self.convertButton = Button(self.canvas, text="Convert to Python", command=self.convertToPython) self.convertAllButton = Button(self.canvas, text="Convert All to Python", command=self.convertAllToPython) self.runFunction = Button(self.canvas, text="Run Python Code", command=self.runPython, state=DISABLED) self.tabButtons = [Tab(40,40, self.function[0].funcName)] self.tabButtons[0].selected = True self.initStartandSplash() self.helpScreenPos = 0 self.root.bind('<Control-n>', (lambda x:self.newFunction())) self.root.bind('<Control-o>', (lambda x:self.openFunction())) self.root.bind('<Control-s>', (lambda x:self.saveFunction())) self.root.bind('<Control-z>', (lambda x:self.undo())) self.root.bind('<Control-y>', (lambda x:self.redo()))
def test_04_equal(self): x = -0.5 eps = 1e-15 expected_value = log(1 + x) value = function(x, eps) self.assertAlmostEqual(expected_value, value)
def test_02_equal(self): x = 0.5 eps = 1e-3 value = function(x, eps) expected_value = log(1 + x) self.assertAlmostEqual(expected_value, value, delta=0.001)
def test_01_equal(self): x = 0 eps = 0.1 expected_value = 0 value = function(x, eps) self.assertAlmostEqual(expected_value, value)
best_valuesDict = {} train = None test = None valuesDict = {} for no_hidden1 in no_hidden1_values: print('For hidden layer neurons = %d' % no_hidden1) for fold in range(folds): start, end = fold * interval, (fold + 1) * interval if (end + interval) > len_trainX: end = len_trainX validateX_kfold, validateY_kfold = trainX[start:end], trainY[start:end] trainX_kfold, trainY_kfold = np.append(trainX[:start], trainX[end:], axis=0), np.append(trainY[:start], trainY[end:], axis=0) train, test, valuesDict = f.function(trainX_kfold, trainY_kfold, validateX_kfold, validateY_kfold, no_hidden1, alpha, epochs, batch_size) fold_cost = np.append(fold_cost, np.mean(valuesDict['test_cost'])) average_fold_cost = np.mean(fold_cost) if average_fold_cost < best_average: best_average = average_fold_cost best_no_hidden1 = no_hidden1 best_train = train best_test = test best_valuesDict = valuesDict plt.figure(0) plt.plot(range(epochs), valuesDict['train_cost'], label='Hidden layer neurons = %d' % no_hidden1) plt.figure(1) plt.plot(range(epochs), valuesDict['test_cost'], label='Hidden layer neurons = %d' % no_hidden1)
from scipy import * from function import function, domain # We do a monte-carlo integration with 1,000,000 points numpoints = 1000000 # Create 'numpoints' number of random points in [0, 1)x[0, 1) x = random.random(numpoints) y = random.random(numpoints) # Scale x to fit the domain x = x * (domain[1] - domain[0]) + domain[0] # Evaluate f at all x for future comparison with y fx = function(x) # Now to find the range over which the function spans, in the given domain maxy = max(fx) miny = min(fx) # Now scale y to fit the range y = y * (maxy - miny) + miny # Now find how many of the points are actually 'under' the curve. This depends # upon sign. If fx is positive, y is under the curve if 0 < y < fx and # contributes positive area. If fx is negative, y is under the curve if # 0 > y > fx and contributes negative area countplus = len(where((y > 0) * (fx > y))[0]) countminus = len(where((y < 0) * (fx < y))[0])
def test_03_equal(self): x = -0.3 eps = 1e-10 expected_value = 1 / (1 + x) value = function(x, eps) self.assertAlmostEqual(expected_value, value)
import function import time num = 10000000 my = function.function("lw", 24, 3640) my.printinfo() # print(my.name) my.name = "23112" print(my.name) my.printinfo() time1 = time.time() my.round(num) time2 = time.time() for i in range(num): pass time3 = time.time() print(time2 - time1) print(time3 - time2) stru = function.functionstruct() stru.a = 1 stru.b = 3 print(stru.add()) my.time1 = 1 my.time2 = 5 print(my.addtime())
import requests import json import paho.mqtt.client as mqtt import time import function # import pygame # screen = pygame.display.set_mode((200,200)) i = 0 rak = [] func_object2 = function.function() start = 0 # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code " + str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("biosense/Sensor_test_R/data") client.subscribe("biosense/Sensor_test_L/data") client.subscribe("biosense/Sensor_test_H/data") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, message): global start #print("Time between messages: ", time.time() - start) #start = time.time()
loopmaster = True while loopmaster: print("MENU") print("1. Melihat Data Siswa 2. Menghitung Volume Prisma dan Limas") pilihan = int(input("Masukkan pilihan: ")) if pilihan == 1: if __name__ == "__main__": listNama = ("Ainun", "Linda", "Karin", "Santi", "Dian") listKELAS = [8, 8, 8, 8, 8] listfunction = [] for i in range(len(listKELAS)): listfunction.append(function.function(listNama[i], listKELAS[i])) for j in range(len(listfunction)): print(" NAMA: {} ".format(listfunction[j].show_NAMA())) print(" KELAS: {} ".format(listfunction[j].show_KELAS())) elif pilihan == 2: print("Menghitung Volume Prisma Segitiga dan Limas Segitiga") t = int(input("Masukkan tinggi Prisma: ")) ts = int(input("Masukkan tinggi segitiga (alas): ")) ss = int(input("Masukkan alas segitiga (alas): ")) print("Volume Prisma Segitiga = {}".format(function.prisma().add( t, ts, ss))) t = int(input("Masukkan tinggi Prisma: ")) ts = int(input("Masukkan tinggi segitiga (alas): "))
def g_net(z): x0 = function(z, size=( 100, 50, ), name="g_net", act=tf.nn.relu) return function(x0, name="g_net/out", size=x_dim)
import sys from PyQt5.QtWidgets import QApplication from function import function app = QApplication (sys.argv) function = function() sys.exit(app.exec())
===============================================================""" ### import some libraries ### import numpy from matplotlib import pyplot ### import .py files ### import constant import function ### input rho, T -> output ft & x=NII/Ntot ### rho=1.0e-9 T=numpy.arange(5000, 25000) ft=function.function(rho, T) x=(-ft+numpy.sqrt(ft**2+4*ft))*0.5 ### show result ### pyplot.plot(T, x) pyplot.show()
def test_06_true(self): x = 0.00023 eps = 1e-15 expected_value = log(1 + x) value = function(x, eps) self.assertTrue(abs(expected_value - value) < 1e-15)
def test_07_false(self): x = 0.00023 eps = 1e-15 expected_value = log(1 + x) value = function(x, eps) self.assertFalse(abs(expected_value - value) > 1e-15)
def __init__(self): self.cam = cv2.VideoCapture(0) self.detector = cv2.CascadeClassifier( "haarcascade_frontalface_default.xml") server = function() self.id = server.get_last_id()
def test_05_true(self): x = 0.58 eps = 1e-15 expected_value = 1 / (1 + x) value = function(x, eps) self.assertTrue(abs(expected_value - value) < 1e-15)
# Hc1 = tf.get_variable("Hc1", [h0_size, h1_size], initializer = small_init, dtype=tf.float32) # Hc2 = tf.get_variable("Hc2", [h1_size, output_size], initializer = small_init, dtype=tf.float32) cross_entropy_list, accuracy_list = [], [] for episode_num in xrange(episodes_num): h0 = tf.nn.relu(tf.matmul(x, W0)) ###### hebb0 = 0.1 * tf.matmul( tf.transpose(x), function(h0, name="h0", size=h0_size, scope="h0", reuse=(True if episode_num > 0 else False), layers_num=1, act=tf.nn.relu, weight_factor=0.0001)) W0 += hebb0 ###### h1 = tf.nn.relu(tf.matmul(h0, W1)) hebb1 = 0.1 * tf.matmul( tf.transpose(h0), function(h1, name="h1", size=h1_size,
import function import os import sys n= sys.argv[1] if n.find(".zip")>0:print str(function.function(n)) +" number of items have been stored into the database" else: count =0 for i in os.listdir(n): count =count+ function.function(n+"/"+i) print str(count)+" number of items have been stored into the database"
def test(): assert function.function(a, b) == c
decode_cell = tf.nn.rnn_cell.MultiRNNCell(rnn_layers*[ ProjectionCell(tf.nn.rnn_cell.LSTMCell(config.decode.net_size), n_mix, activation=tf.nn.tanh) ]) input = tf.placeholder(tf.float32, shape=(seq_size, batch_size, dim_size), name="Input") # state = tf.placeholder(tf.float32, [batch_size, net_size], name="state") state = tuple( tf.nn.rnn_cell.LSTMStateTuple(*[tf.zeros((batch_size, sz)) for sz in sz_outer]) for sz_outer in encode_cell.state_size ) with tf.variable_scope("rnn_encode") as scope: encode_out, encode_h_end = rnn.dynamic_rnn(encode_cell, input, initial_state=state, time_major=True, scope = scope) z_enc = function(*encode_h_end[-1], name="z_enc", size=config.z_interm, act=tf.nn.elu, layers_num=layers_num) z_mu = function(z_enc, name="z_mu", size=config.z_dim) z_sigma = function(z_enc, name="z_sigma", size=config.z_dim) # sampling epsilon = tf.random_normal((batch_size, config.z_dim), name='epsilon') z = z_mu + tf.exp(0.5 * z_sigma) * epsilon # h0 = h0 = tuple( tf.nn.rnn_cell.LSTMStateTuple(*[ function(z, name="decode_init_state_{}".format(i), size=sz, layers_num=layers_num) for i, sz in enumerate(sz_outer) ])
# read and divide data into test and train sets cal_housing = np.loadtxt('cal_housing.data', delimiter=',') X_data, Y_data = cal_housing[:, :8], cal_housing[:, -1] Y_data = (np.asmatrix(Y_data)).transpose() Y_data = Y_data / 1e3 # Scale X_data then shuffle data X_data = f.scale(X_data) X_data, Y_data = f.shuffle_data(X_data, Y_data) # separate train and test data m = 3 * X_data.shape[0] // 10 testX, testY = X_data[:m], Y_data[:m] trainX, trainY = X_data[m:], Y_data[m:] train, test, valuesDict = f.function(trainX, trainY, testX, testY, no_hidden1, learning_rate, epochs, batch_size) train_cost = valuesDict['train_cost'] test_cost = valuesDict['test_cost'] # Plots # a) Plot the training error against number of epochs for the 3-layer network. plt.figure() plt.plot(range(epochs), train_cost, label='train error') plt.xlabel('Time (s)') plt.ylabel('Mean Squared Error') plt.title('Training Errors at Alpha = %.5f' % learning_rate) plt.legend() plt.savefig('partb_1a.png') # b) Plot the final test errors of prediction by the network.
import output import function import platform import re import time luna_output = output.output() func = function.function() class parasehttp(object): def __init__(self): self.text = '' self.http_method = '' self.get_key_list = [] self.get_value_list = [] self.get_text = '' self.post_key_list = [] self.post_value_list = [] self.post_text = '' self.cookie_key_list = [] self.cookie_value_list = [] self.cookie_text = '' self.cgi = '' self.content_length = ''
call(["espeak", "-s", "160", "Do you want to import your contact?"]) speech = get_speech() if "yes" in speech.lower(): conn.import_contact() rec = face_rec() if rec.rec() != "0": computername = rec.rec() else: call(["espeak", "-s", "160", "This is Your First Time using me"]) call(["espeak", "-s", "160", "Do you want to create a new account?"]) speech = get_speech() if "yes" in speech.lower() or "yeah" in speech.lower(): det = face_detect() det.new() server_ad = function() server_ad.add_user() train = face_train() train.train() rec = face_rec() computername = rec.rec() else: break call(["espeak", "-s", "160", "Hello " + computername + " can i help you?"]) speech = get_speech() if "email" in speech.lower(): try: server = function() if server.get_last_id() == "0":