def get_response(self, t, x): ''' получить выход''' equa = EquationClass.Equation.get_instance() # Определяем было ли уже это время if t > self.last_t or t == self.last_t: # Определяем направление if self.last_x < x: self.bound = self.line_up else: self.bound = self.line_down y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) self.last_x = x self.last_t = t else: print('!!!!!') y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) return y
def get_response_operezenie(self,t,x): ''' получить выход''' equa = EquationClass.Equation.get_instance() # Определяем было ли уже это время if self.in_hyst == False: if t > self.last_t or t == self.last_t: # Определяем направление if self.last_x < x: self.bound = self.line_down else: self.bound = self.line_up y = functions.sign(t, x, input_bound = self.bound, out_upper= self.up, out_down= self.down) self.last_x = x self.last_t = t if x > self.line_up or x <self.line_down: self.in_hyst= True else: print('!!!!!') y = functions.sign(t, x, input_bound =self.bound, out_upper= self.up, out_down= self.down) else: y = functions.sign(t, x, input_bound = self.bound, out_upper= self.up, out_down= self.down) self.last_x = x self.last_t = t if x< self.line_up or x>self.line_down: self.in_hyst = False return y
def get_response_zapazdivanie(self, t, x): ''' получить выход''' equa = EquationClass.Equation.get_instance() #print(f'state is {self.state}, x is {x}, hyst is {self.in_hyst}') # Определяем было ли уже это время if self.state == True: self.bound = self.line_down else: self.bound = self.line_up #print(self.bound) if x < self.line_up and x > self.line_down: self.in_hyst = True if self.in_hyst == False: if t > self.last_t or t == self.last_t: # Определяем направление if self.last_x < x: self.state = False elif self.last_x > x: self.state = True if self.state == True: self.bound = self.line_down else: self.bound = self.line_up y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) self.last_x = x self.last_t = t else: print('!!!!!') y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) else: y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) self.last_x = x self.last_t = t if x > self.line_up or x < self.line_down: self.in_hyst = False self.state = not self.state return y
def get_response(self, t, x): ''' получить выход''' equa = EquationClass.Equation.get_instance() # Определение линии переключения if self.state == True: self.bound = self.line_down else: self.bound = self.line_up # Проверка на нахождение в зоне гистерезиса if x < self.line_up and x > self.line_down: self.in_hyst = True # В случае нахождения вне гистерезиса if self.in_hyst == False: # Проверка на последовательность по времени if t > self.last_t or t == self.last_t: y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) self.last_x = x self.last_t = t else: y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) else: # В случае нахождения в зоне гистерезиса y = functions.sign(t, x, input_bound=self.bound, out_upper=self.up, out_down=self.down) xlast = self.last_x self.last_x = x self.last_t = t # Определяем реле на опережение или запаздывание # Далее идет проверка на выход из зоны гистерезиса if self.zapazdivanie == True: if self.state == False and x > self.line_up or self.state == True and x < self.line_down: self.in_hyst = False self.state = not self.state else: if self.state == False and x < self.line_up or self.state == True and x > self.line_down: self.in_hyst = False self.state = not self.state return y
def __update_net_weights_biases (self, mini_batch, step_size, lmbda, training_set_size, regularization_type=None): grad_b = [np.zeros(l) for l in self.__layer_sizes[1:]] grad_w = [np.zeros((cl, pl)) for pl, cl in zip(self.__layer_sizes[:self.__n_layers-1], self.__layer_sizes[1:])] for i, o in mini_batch: d_grad_b, d_grad_w = self.__back_prop(i, o) grad_b = [gb + dgb for gb, dgb in zip(grad_b, d_grad_b)] grad_w = [gw + dgw for gw, dgw in zip(grad_w, d_grad_w)] avg_step = step_size/(len(mini_batch)+0.0) self.__biases = [b - avg_step*gb for b, gb in zip(self.__biases, grad_b)] if regularization_type == 'L1': #L1 Regularization self.__weights = [w - avg_step*gw for w, gw in zip(self.__weights, grad_w)] reg = lmbda/(training_set_size+0.0) for x in range(len(self.__weights)): for y in range(len(self.__weights[x])): for z in range(len(self.__weights[x][y])): self.__weights[x][y][z] -= fn.sign(self.__weights[x][y][z])*reg elif regularization_type == 'L2': #L2 Regularization reg = lmbda/(training_set_size+0.0) self.__weights = [(1-step_size*reg)*w-avg_step*gw for w, gw in zip (self.__weights, grad_w)] else: # Unregularized self.__weights = [w-avg_step*gw for w, gw in zip(self.__weights, grad_w)]
def testWeight(self, testDataSet, t): # reset mistakes count so each iteration starts at 0 xit = [ ] # x-sub-i-sub-t, the training vector for the current iterations yit = 0 # y-sub-i-sub-t, the label for the current training vector (yStar) yHat = 0 ### evaluate all test samples: for i in range(len(testDataSet)): self.testTotal += 1 xit = testDataSet[i][0] yit = testDataSet[i][1] ### make the prediction: #yHat = yit * self.dotProd(xit) # Method A #yHat = yit * (self.dotProd(xit) + self.b) # Method B #yHat = sign(yit * (self.dotProd(xit) + self.b)) # Method C yHat = sign(yit * self.dotProd(xit)) # Method D ### if the value is actually good, ### and we predicted good, increment npr ### which is the # lines predicted as good that are actually good if yit == 1: self.testGood += 1 if yHat > 0: self.testnpr += 1 self.testdp += 1 else: self.testMistakes += 1 if yit == -1: if yHat > 0: self.testMistakes += 1
def get_response(self, t, x, dx): ''' получить выход''' equa = EquationClass.Equation.get_instance() # Определяем производную if equa.dy < 0: bound = self.line_down else: bound = self.line_up if self.switch == True: dy = -2 * np.sign(equa.dy) * 200 if abs(equa.dy - self.ddy) > abs(2 * equa.b0): self.switch = False dy = 0 elif (abs(self.line_up - x) < equa.step) and equa.dy > 0: #print(f'line up x is {x}, dy is {equa.dy}, t is {t} abs is {abs(self.line_up - x)}') dy = -2 * np.sign(equa.dy) * 100 self.switch = True self.ddy = equa.dy elif abs(self.line_down - x) < equa.step and equa.dy < 0: #print(f'line down x is {x}, dy is {equa.dy}') dy = -2 * np.sign(equa.dy) * 100 self.switch = True self.ddy = equa.dy else: dy = 0 y = functions.sign(t, x, input_bound=bound, out_upper=self.up, out_down=self.down) return y, dy
def __iter__(self): f = self.f x1 = self.x1 fx1 = f(x1) x2 = self.x2 fx2 = f(x2) while True: x3 = 0.5*(x1 + x2) fx3 = f(x3) x4 = x3 + (x3 - x1) * sign(fx1 - fx2) * fx3 / sqrt(fx3**2 - fx1*fx2) fx4 = f(x4) if abs(fx4) < self.tol: # TODO: better condition (when f is very flat) if self.verbose: print 'canceled with f(x4) =', fx4 yield x4, abs(x1 - x2) break if fx4 * fx2 < 0: # root in [x4, x2] x1 = x4 fx1 = fx4 else: # root in [x1, x4] x2 = x4 fx2 = fx4 error = abs(x1 - x2) yield (x1 + x2)/2, error
def __update_net_weights_biases(self, mini_batch, step_size, lmbda, training_set_size, regularization_type=None): grad_b = [[0 for n in range(self.__layer_sizes[l])] for l in range(1, self.__n_layers)] grad_w = [[[0 for p in range(self.__layer_sizes[l - 1])] for n in range(self.__layer_sizes[l])] for l in range(1, self.__n_layers)] for i, o in mini_batch: d_grad_b, d_grad_w = self.__back_prop(i, o) grad_b = [ functions.add_vec(1, 1, grad_b[a], d_grad_b[a]) for a in range(self.__n_layers - 1) ] grad_w = [[ functions.add_vec(1, 1, grad_w[a - 1][b], d_grad_w[a - 1][b]) for b in range(self.__layer_sizes[a]) ] for a in range(1, self.__n_layers)] avg_step = (step_size + 0.0) / len(mini_batch) self.__biases = [ functions.add_vec(1, -avg_step, self.__biases[a], grad_b[a]) for a in range(self.__n_layers - 1) ] if regularization_type == 'L1': #L1 Regularization self.__weights = [[ functions.add_vec(1, -avg_step, self.__weights[a][b], grad_w[a][b]) for b in range(self.__layer_sizes[a + 1]) ] for a in range(self.__n_layers - 1)] reg = lmbda / training_set_size for x in range(len(self.__weights)): for y in range(len(self.__weights[x])): for z in range(len(self.__weights[x][y])): self.__weights[x][y][z] -= functions.sign( self.__weights[x][y][z]) * reg elif regularization_type == 'L2': #L2 Regularization reg = lmbda / training_set_size self.__weights = [[ functions.add_vec((1 - (step_size * reg)), -avg_step, self.__weights[a][b], grad_w[a][b]) for b in range(self.__layer_sizes[a + 1]) ] for a in range(self.__n_layers - 1)] else: # Unregularized self.__weights = [[ functions.add_vec(1, -avg_step, self.__weights[a][b], grad_w[a][b]) for b in range(self.__layer_sizes[a + 1]) ] for a in range(self.__n_layers - 1)]
def get_response_zapazdivanie(self,t,x): ''' получить выход''' equa = EquationClass.Equation.get_instance() #print(f'state is {self.state}, x is {x}, hyst is {self.in_hyst}') # Определяем было ли уже это время if self.state == True: self.bound = self.line_down else: self.bound = self.line_up #if self.last_state != self.state: #print(f'state changed x is {x}, t is {t}, last x is {self.last_x} state is {self.state} bound is {self.bound}') #self.last_state = self.state #print(self.bound) if x < self.line_up and x >self.line_down: self.in_hyst= True if self.in_hyst == False: #print(f'outside hyst x is {x}, t is {t}, last x is {self.last_x} state is {self.state} bound is {self.bound}') if t > self.last_t or t == self.last_t: # Определяем направление #if self.last_x < x: # self.state = False #elif self.last_x > x: # self.state = True #if self.state == True: # self.bound = self.line_down #else: # self.bound = self.line_up y = functions.sign(t, x, input_bound = self.bound, out_upper= self.up, out_down= self.down) self.last_x = x self.last_t = t else: print('!!!!!') y = functions.sign(t, x, input_bound =self.bound, out_upper= self.up, out_down= self.down) else: y = functions.sign(t, x, input_bound = self.bound, out_upper = self.up, out_down= self.down) xlast=self.last_x self.last_x = x self.last_t = t if self.state == False and x > self.line_up or self.state == True and x < self.line_down: #print(f'change rele x is {x}, t is {t}, last x is {xlast} state is {self.state}') self.in_hyst = False self.state = not self.state return y
def testWeight(self, trainDataSet, testDataSet): # reset mistakes count so each iteration starts at 0 self.testMistakes = 0 self.testnpr = 0 self.testdp = 0 self.testTotal = len(testDataSet) xit = [ ] # x-sub-i-sub-t, the training vector for the current iterations yit = 0 # y-sub-i-sub-t, the label for the current training vector (yStar) yHat = 0 aVal = 0 bVal = 0 cVal = 0 dVal = 0 ### evaluate all test samples: for i in range(len(testDataSet)): xit = testDataSet[i][0] yit = testDataSet[i][1] ### make the prediction: #yHat = yit * self.dotProdTest(xit) yHat = sign(yit * self.dotProd(xit)) #print 'self.dotProdTest(xit): ', self.dotProdTest(xit), ' :' #print 'yit * self.dotProdTest(xit)', yit * self.dotProdTest(xit) #print 'yHat: ', yHat, 'yit: ', yit ### if the value is actually good, ### and we predicted good, increment npr ### which is the # lines predicted as good that are actually good if yit == 1: if yHat >= 1: self.testnpr += 1 else: self.testMistakes += 1 else: #if yit == -1: if yHat >= 1: self.testMistakes += 1 ### evaluate the prediction ### if predicted good, increment predicted good count, dp if yHat >= 1: self.testdp += 1 self.testAccuracy = 100.0 - ( 100.0 * (self.testMistakes / float(self.testTotal))) #print 'testMistakes = ', self.testMistakes, ' : test success = ', \ #self.testAccuracy, '%' if self.testdp > 0: self.testPrecision = self.testnpr / float(self.testdp) self.testRecall = self.testnpr / float(self.testGood) #print 'testPrecision: ', self.testPrecision #print 'testRecall: ', self.testRecall if (self.testPrecision + self.testRecall) > 0: self.testF1 = 2.0 * self.testPrecision * self.testRecall / ( self.testPrecision + self.testRecall)
def dms2dd(dms): """convert degrees, minutes seconds to degrees""" from functions import sign if type(dms) is str: if dms.find(':')>0: dms = dms.split(':') else: dms = dms.split(' ') dms = [float(d) for d in dms] if len(dms)==2: dms.append(0.0) return sign(dms[0])*(abs(dms[0]) + dms[1]/60. + dms[2]/3600.)
def fgsm(self, x, t): d_t = LA.array([[1 if ti == i + 1 else 0 for i in range(23)] for ti in t]) h = -d_t + x h = h @ self.w3 h = h * F.drelu(h) h = h @ self.w2 h = h * F.drelu(h) d = h @ self.w1 return F.sign(d) * self.eps0
def householder(A): """ (A|b) -> H, p, x, res (A|b) is the coefficient matrix with left hand side of an optionally overdetermined linear equation system. H and p contain all information about the transformation matrices. x is the solution, res the residual. """ assert isinstance(A, matrix) m = A.rows n = A.cols assert m >= n - 1 # calculate Householder matrix p = [] for j in xrange(0, n - 1): s = 0. for i in xrange(j, m): s += (A[i,j])**2 if not abs(s) > eps: raise ValueError('matrix is numerically singular') p.append(-sign(A[j,j]) * sqrt(s)) kappa = s - p[j] * A[j,j] A[j,j] -= p[j] for k in xrange(j+1, n): y = 0. for i in xrange(j, m): y += A[i,j] * A[i,k] y /= kappa for i in xrange(j, m): A[i,k] -= A[i,j] * y # solve Rx = c1 x = [] for i in xrange(n - 1): x.append(A[i,n - 1]) for i in xrange(n - 2, -1, -1): for j in xrange(i + 1, n - 1): x[i] -= A[i,j] * x[j] x[i] /= p[i] # calculate residual if not m == n - 1: r = [] for i in xrange(m - n + 1): r.append(A[m-1-i, n-1]) else: # determined system, residual should be 0 r = [0]*m return A, p, x, r
def householder(A): """ (A|b) -> H, p, x, res (A|b) is the coefficient matrix with left hand side of an optionally overdetermined linear equation system. H and p contain all information about the transformation matrices. x is the solution, res the residual. """ assert isinstance(A, matrix) m = A.rows n = A.cols assert m >= n - 1 # calculate Householder matrix p = [] for j in xrange(0, n - 1): s = 0. for i in xrange(j, m): s += (A[i, j])**2 if not abs(s) > eps: raise ValueError('matrix is numerically singular') p.append(-sign(A[j, j]) * sqrt(s)) kappa = s - p[j] * A[j, j] A[j, j] -= p[j] for k in xrange(j + 1, n): y = 0. for i in xrange(j, m): y += A[i, j] * A[i, k] y /= kappa for i in xrange(j, m): A[i, k] -= A[i, j] * y # solve Rx = c1 x = [] for i in xrange(n - 1): x.append(A[i, n - 1]) for i in xrange(n - 2, -1, -1): for j in xrange(i + 1, n - 1): x[i] -= A[i, j] * x[j] x[i] /= p[i] # calculate residual if not m == n - 1: r = [] for i in xrange(m - n + 1): r.append(A[m - 1 - i, n - 1]) else: # determined system, residual should be 0 r = [0] * m return A, p, x, r
def get_response(self, t, x, dx): ''' получить выход''' equa = EquationClass.Equation.get_instance() # Определяем производную if self.switch == True: dy = -2 * np.sign(equa.dy) * 200 if abs(equa.dy - self.ddy) > abs(2 * equa.b0): self.switch = False dy = 0 elif abs(self.line - x) < equa.step: dy = -2 * np.sign(equa.dy) * 100 self.switch = True self.ddy = equa.dy else: dy = 0 y = functions.sign(t, x) #print(f'y is {y}, dy is {dy} switch is {self.switch}') return y, dy
def step(self, frametime): if not self.root.console.active: if self.root.left: self.hspeed -= self.accel * frametime if self.root.right: self.hspeed += self.accel * frametime if self.root.up: if self.onGround or self.noclip: self.vspeed = -self.jumpForce if not (self.root.left or self.root.right) or self.root.console.active: if abs(self.hspeed) < 10: self.hspeed = 0 else: self.hspeed -= sign(self.hspeed) * min(abs(self.hspeed), self.moveSpeed * frametime) # gravitational force self.vspeed += self.gravity * frametime # TODO: air resistance, not hard limit self.vspeed = min(self.gravity, self.vspeed) self.hspeed = min(self.moveSpeed, max(-self.moveSpeed, self.hspeed))
def perceptron(self, trainDataSet): #self.trainTotal = len(trainDataSet) xit = [ ] # x-sub-i-sub-t, the training vector for the current iterations yit = 0 # y-sub-i-sub-t, the label for the current training vector (yStar) yHat = 0 for l in range(len(trainDataSet)): self.trainTotal += 1 xit = trainDataSet[l][0] yit = trainDataSet[l][1] ### make the prediction: yHat = y*(<w,x>) #yHat = yit * self.dotProd(xit) # Method U #yHat = yit * (self.dotProd(xit) + self.b) # Method V #yHat = sign(yit * (self.dotProd(xit) + self.b)) # Method W yHat = sign(yit * self.dotProd(xit)) # Method X #print 'initial eval: ', yit, ' : ', yHat ### update weight accordingly, ### if predicted value and actual value don't match, ## update weight, ### if they do match no update required if yit == 1: self.trainGood += 1 if yHat > 0: self.trainnpr += 1 self.traindp += 1 else: #print yit, ' : ', yHat self.updateWeight(xit, yit) self.trainMistakes += 1 else: if yHat > 0: #print yit, ' : ', yHat self.trainMistakes += 1 self.updateWeight(xit, yit) else: self.traindp += 1
def forward(self, input): feat = self.conv(input) x = F.tanh(feat) return sign(x)
sigma = gm.mpz(1599844828480432996670936450307491188612511817228907936025817182927186568673377894841834068826933399374833623579771859973397175895631949922313558451139090) proxy_private = sigma lhs = gm.powmod(g, sigma, p) temp = gm.powmod(K, K, p) rhs = (v * temp) % p proxy_public = rhs print(lhs == rhs) m = 12345678 (ori_r, ori_sig) = fn.sign(m, g, original_private, p) ori_verify = fn.verify(p, g, original_public, ori_r, ori_sig, m) print(ori_verify) (proxy_r, proxy_sig) = fn.sign(m, g, proxy_private, p) proxy_verify = fn.verify(p, g, proxy_public, proxy_r, proxy_sig, m) print(proxy_verify) (ori_r, ori_sig) = fn.sign(m, g, original_private, p) ori_verify = fn.verify(p, g, proxy_public, ori_r, ori_sig, m) print(ori_verify) (proxy_r, proxy_sig) = fn.sign(m, g, proxy_private, p)
cardN = "3141592653589793" with open("PG\cc.txt") as fd: text = fd.read() CCode = text Amount = "999" NC = functions.generate_once() CardExp = "12/04" PI = { "cardN": cardN, "CCode": CCode, "Sid": sid, "Amount": Amount, "PubKC": pub_k_c, "NC": NC } PI_signature = functions.sign("Client", str(PI)) PM = {"PI": PI, "PI_signature": PI_signature} PM = str(PM) PM_encrypted_by_KPG = functions.encrypt_asymmetric(PM.encode("utf8"), "PG") # print("criptarea este", len(PM_encrypted_by_KPG.hex()), "\n", hex_key) # print(bytes.fromhex(hex_key)) OrderDesc = "Bicicleta, id=123" OI = {"OrderDesc": OrderDesc, "Sid": sid, "Amount": Amount} OI = str(OI) OI_signature = functions.sign("Client", OI) PO = {"OI": OI, "OI_signature": OI_signature} message3 = {"PM": PM_encrypted_by_KPG.hex(), "PO": PO} message3 = str(message3) print("mesajul 3 este", message3) print("pm hex este", PM_encrypted_by_KPG.hex()) # message3_encrypted = functions.encrypt_asymmetric(message3.encode("utf8"), "Merchant")
def on_new_client(client, connection): ip = connection[0] port = connection[1] print(f"S-a conectat un nou client cu adresa ip {ip}, si portul: {port}!") msg = client.recv(3072) print(f"Mesajul pe care l-am primit: {msg}") # pub_k_c_encrypted = msg # pub_k_c = functions.decrypt_asymmetric(pub_k_c_encrypted, "Merchant") msg_json = msg.decode("utf8") msg_json = ast.literal_eval(msg_json) aes_encrypted = msg_json['aes_encrypted'] pub_k_c_encrypted = msg_json['pub_k_c_encrypted'] pub_k_c_encrypted = bytes.fromhex(pub_k_c_encrypted) aes_encrypted = bytes.fromhex(aes_encrypted) aes = functions.decrypt_asymmetric(aes_encrypted, "Merchant") pub_k_c = unpad(functions.decrypt_symmetric(pub_k_c_encrypted, aes), 48) # mesajul 2 print("Pregatim mesajul 2\n") sid = str(randint(1000, 9999)) signature = functions.sign("Merchant", sid) message2 = sid.encode("utf-8") + signature print("lungimea e", len(aes)) message2_encrypted = functions.encrypt_symmetric(message2, aes) client.sendall(message2_encrypted) msg = client.recv(8192) print(f"Mesajul pe care l-am primit: {msg}") print("Pregatim mesajul 4 sa-l trimitem\n") print("lungimea mesajului este", len(msg)) msg2_decrypted = unpad(functions.decrypt_symmetric(msg, aes), 48) msg2_decrypted = msg2_decrypted.decode("utf8") json_data = ast.literal_eval(msg2_decrypted) po = json_data['PO'] oi = po['OI'] json_oi = ast.literal_eval(oi) amount = json_oi['Amount'] oi = str(oi) oi_signature = po['OI_signature'] if functions.verify("Client", oi, oi_signature): print("Semnatura clientului asupra lui OI este in regula") else: client.sendall(b"ABORT") PM = json_data['PM'] sid_pubkc_amount = {"sid": sid, "pubkc": pub_k_c, "amount": amount} signature_sid_pubkc_amount = functions.sign("Merchant", str(sid_pubkc_amount)) message4_encrypted = {"PM": functions.encrypt_symmetric(str(PM).encode("utf8"), aes), "signature": signature_sid_pubkc_amount, "aes": functions.encrypt_asymmetric(aes, "PG")} # message4_encrypted = functions.encrypt_asymmetric(str(message4).encode("utf8"), "PG") with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sckTTP: try: sckTTP.connect(("127.0.0.2", 4321)) except Exception as e: raise SystemExit(f"Eroare la conecatarea la server: {e}") sckTTP.sendall(str(message4_encrypted).encode("utf8")) msg = sckTTP.recv(4096) print(f"Mesajul pe care l-am primit: {msg}") if msg == b'ABORT': client.sendall(b'ABORT') msg5_decrypted = unpad(functions.decrypt_symmetric(msg, aes), 48) print("Pregatim mesajul 6") msg6 = functions.encrypt_symmetric(msg5_decrypted, aes) client.sendall(msg6) print(f"Clientul cu adresa ip: {ip}, si portul: {port}, a iesit!") client.close()
def test_sign(): assert sign(6) == 1 assert sign(-6) == -1 assert sign(0) == 0
def forward(self, input): feat = self.conv(input) x = F.tanh(feat) return sign(x) #sign-binary quantizer
def on_new_client(client, connection): ip = connection[0] port = connection[1] print(f"S-a conectat un nou client cu adresa ip {ip}, si portul: {port}!") msg = client.recv(25600) print(f"Mesajul pe care l-am primit: {msg}") json_msg = ast.literal_eval(msg.decode("utf8")) # msg4_decrypted = functions.decrypt_asymmetric(msg, "PG").decode("utf8") # json_msg4_decrypted = ast.literal_eval(msg4_decrypted) aes = functions.decrypt_asymmetric(json_msg['aes'], "PG") pm = json_msg['PM'] pm = unpad(functions.decrypt_symmetric(pm, aes), 48) # print("tipul este", type(pm)) # print(pm) pm_ascii = bytes.fromhex(pm.decode("utf8")) # print(pm_ascii) pm_ascii = functions.decrypt_asymmetric(pm_ascii, "PG") # print("pm ascii este", pm_ascii) # test = input("test") # pm_decrypted = functions.decrypt_asymmetric(pm_ascii, "PG") pm_decrypted_json = ast.literal_eval(pm_ascii.decode("utf8")) pi = pm_decrypted_json['PI'] pi_signature = pm_decrypted_json['PI_signature'] if functions.verify("Client", str(pi), pi_signature): print("Putem continua, semnatura digitala asupra lui PI e autentica") else: client.sendall(b'ABORT') # signature_decrypted = unpad(functions.decrypt_symmetric(pi_signature, pi['PubKC']), 24) # pi_hash = hashlib.md5(str(pi).encode("utf8")).hexdigest() # if pi_hash == signature_decrypted.decode("utf8"): # print("Putem continua, semnatura digitala asupra lui PI e autentica") # else: # print("nu sunt egale") # client.sendall(b'ABORT') with open("PG\cc.txt") as fd: text = fd.read() card = pi['cardN'] ccode = pi['CCode'] amount = pi['Amount'] with open("./BD/bd.json") as fd: informations = json.load(fd) for client_detail in informations: if client_detail['cardN'] == card: if int(ccode) != client_detail['ccode'] or int(amount) >= client_detail['amount']: client.sendall(b'ABORT') sid = pi['Sid'] pub_k_c = pi['PubKC'] amount = pi['Amount'] sid_pubkc_amount = {"sid": sid.decode("utf8"), "pubkc": pub_k_c, "amount": amount} signature_merchant = json_msg['signature'] if functions.verify("Merchant", str(sid_pubkc_amount), signature_merchant): print("Semnatura digitala asupra sid, pubKC si amount e autentica") else: client.sendall(b'ABORT') print("Pregatim mesajul 5 catre merchant") resp = "ok" message5_info = {"resp": resp, "sid": sid.decode("utf8"), "amount": amount, "NC": pi['NC']} message5_info_signature = functions.sign("PG", str(message5_info)) message5 = {"resp": resp, "sid": sid.decode("utf8"), "signature": message5_info_signature.hex()} # message5_encrypted = functions.encrypt_asymmetric(str(message5).encode("utf8"), "Merchant") message5_encrypted = functions.encrypt_symmetric(str(message5).encode("utf8"), aes) client.sendall(message5_encrypted) print(f"Clientul cu adresa ip: {ip}, si portul: {port}, a iesit!") client.close()
plt.imshow(pictures_matrix[2]) plt.show() #%% #Selecting random units and checking convergence (question 3 of 3.2) np.random.seed(42) number_units = np.arange(weights.shape[0]) number_units = np.random.permutation(number_units) convergence = False i = 0 test = pictures_matrix[9].reshape(-1).copy() previous_iter_100 = pictures_matrix[9].reshape(-1).copy() for it in range(10): for i in range(len(number_units)): previous_test = test.copy() update_bit = fun.sign(np.dot(weights[number_units[i]], test)) test[number_units[i]] = update_bit if (i % 100 == 0) and (i != 0): if (np.array_equal(previous_iter_100, test)): number_iterations = it + 1 break plt.imshow(test.reshape(32, 32)) plt.title('Print after ' + str(int(i + (it * len(number_units)))) + ' updates.') plt.show() previous_iter_100 = test.copy() if (np.array_equal(previous_iter_100, test)): break plt.imshow(test.reshape(32, 32)) plt.title("Final Plot. Number of iterations: " + str(number_iterations))