def __init__(self, filename, port_cp=4729, port_up=47290): self.filename = filename + '.pcap' self.port_cp = port_cp self.port_up = port_up self.ip_id = 0 self.base_address = 0x7f000001 d = str(Environment.getExternalStorageDirectory() ) + '/MobileSentinel/' + filename print("PCAP location: " + d) filepath = os.path.join(d, self.filename) self.pcap_file = open(filepath, 'wb') self.eth_hdr = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x08\x00' pcap_global_hdr = struct.pack( '<LHHLLLL', 0xa1b2c3d4, 2, 4, 0, 0, 0xffff, 1, ) self.pcap_file.write(pcap_global_hdr) self.pcap_file.flush()
def android_ext_dir(): try: import jnius env = jnius.autoclass('android.os.Environment') except ImportError: from android.os import Environment as env # Chaquopy import hook return env.getExternalStorageDirectory().getPath()
def graph(x1, y1, z1, name, direc, totalSeg, inputDate): d = str(Environment.getExternalStorageDirectory()) n = str(name) dir = str(direc) my_dpi = 96 pixel = 256 fig = plt.figure(figsize=(pixel / my_dpi, pixel / my_dpi), dpi=my_dpi) ax = fig.gca(projection='3d') ax.plot(z1, y1, x1, c='k', linewidth=3) #your data list (z,y,x) if totalSeg != 1: x = [] y = [] z = [] for i in range(1, totalSeg): data = loadtxt(d + "/FreeForm-Writing/." + inputDate + "/Seg/" + str(i) + "Seg.csv", ndmin=2, delimiter=",") #savetxt(d + "/FreeForm-Writing/." + inputDate + "/.Working/" + str(i) + "Seg.csv",data,delimiter=",") x.extend(data[:, 0].tolist()) y.extend(data[:, 1].tolist()) z.extend(data[:, 2].tolist()) ax.plot(z, y, x, c='r', linewidth=3) #penupDown segment ax.view_init(-90, 140) ax.grid(False) ax.set_xticks([]) ax.set_yticks([]) ax.set_zticks([]) plt.axis('off') plt.savefig(dir + '/' + n, transparent=True) #filename of the saved file plt.show()
def test(): # print(file) d = str(Environment.getExternalStorageDirectory()) #heart = join(dirname(__file__), "heart.wav") heart = join(d, "heart.wav") (signal, rate) = lr.load(heart, sr=None) return np.array(list(signal), dtype=np.float)
def test(o): filename = join(dirname(__file__), "sam.jpg") decoded = cv2.imdecode(np.frombuffer(o, np.uint8), -1) #src = cv2.imread(decoded) grayScale = cv2.cvtColor( decoded, cv2.COLOR_RGB2GRAY ) kernel = cv2.getStructuringElement(1,(17,17)) # Perform the blackHat filtering on the grayscale image to find the # hair countours blackhat = cv2.morphologyEx(grayScale, cv2.MORPH_BLACKHAT, kernel) #cv2.imshow("BlackHat",blackhat) #cv2.imwrite('blackhat_sample1.jpg', blackhat, [int(cv2.IMWRITE_JPEG_QUALITY), 90]) # intensify the hair countours in preparation for the inpainting # algorithm ret,thresh2 = cv2.threshold(blackhat,10,255,cv2.THRESH_BINARY) #print( thresh2.shape ) #cv2.imshow("Thresholded Mask",thresh2) #cv2.imwrite('thresholded_sample1.jpg', thresh2, [int(cv2.IMWRITE_JPEG_QUALITY), 90]) # inpaint the original image depending on the mask dst = cv2.inpaint(decoded,thresh2,1,cv2.INPAINT_TELEA) #data= np.array(dst,dtype="int32") im_resize = cv2.resize(dst, (224, 224)) is_success, im_buf_arr = cv2.imencode(".jpg", im_resize) byte_im = im_buf_arr.tobytes() d = str(Environment.getExternalStorageDirectory()) # cv2.imwrite(d+'sample1.jpg', dst, [int(cv2.IMWRITE_JPEG_QUALITY), 90]) final= join(d,'sample1.jpg') return byte_im
def processGPURoofline(self): try: os.chdir( os.path.join(str(Environment.getExternalStorageDirectory()), "GPURoofline/")) except: return None summaries = get_test_summaries() generate_roofline_plot(summaries) generate_bandwidth_plot(get_best_summary(summaries)) print("Plotting complete")
def readLocations(self): self.locations = {} self.order = [] if Environment.getExternalStorageState() != Environment.MEDIA_MOUNTED: return storageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS) subdir = File(storageDir, "WeatherForecast") if subdir.exists(): f = File(subdir, "locations.txt") try: stream = BufferedReader(FileReader(f)) while True: line = stream.readLine() if line == None: break spec = line.trim() pieces = spec.split("/") if len(pieces) < 3: continue place = pieces[len(pieces) - 1] self.locations[place] = spec self.order.add(place) stream.close() except FileNotFoundException: pass
def initiate_parsing(packet_list, dump_directory, dump_filename, detection_view=None, isVulnerable=None): # Setup dump parser modules my_parser = parsers.QualcommParser(packet_list, detection_view, isVulnerable) d = str(Environment.getExternalStorageDirectory()); filepath = os.path.join(d, 'MobileSentinel/' + dump_directory + '/' + dump_filename) try: io_device = iodevices.FileIO([str(filepath)]) my_parser.set_io_device(io_device) except Exception as e: print(e) writer = writers.PcapWriter(dump_directory, GSMTAP_PORT, IP_OVER_UDP_PORT) my_parser.set_writer(writer) my_parser.read_dump()
def __init__(self, context): LinearLayout.__init__(self, context) self.handler = None envDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS) self.fileAdapter = SpriteFileListAdapter(envDir, [".spr", ",ff9", ".ff9"]) self.fileView = ListView(context) self.fileView.setOnItemClickListener(self) self.fileView.setAdapter(self.fileAdapter) self.addView( self.fileView, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
def Clustering(inputDate): dir = str(Environment.getExternalStorageDirectory()) file = loadtxt(dir + "/FreeForm-Writing/." + inputDate + "/.Working/inputData.csv",delimiter=",") inData = file.reshape(-1,1) y = KMeans(n_clusters=2).fit(inData) scr = score(inData,y.labels_) cluster_map = pd.DataFrame() cluster_map['data_index'] = file cluster_map['cluster'] = y.labels_ c0 = [item[0] for item in cluster_map[cluster_map.cluster == 0].values.tolist()] c1 = [item[0] for item in cluster_map[cluster_map.cluster == 1].values.tolist()] if len(c0) > len(c1): clust0 = c1 else: clust0 = c0 if(len(clust0) > 5): inData1 = np.array(clust0).reshape(-1,1) y1 = KMeans(n_clusters=2).fit(inData1) scr1 = score(inData1,y1.labels_) cluster_map1 = pd.DataFrame() cluster_map1['data_index'] = clust0 cluster_map1['cluster'] = y1.labels_ cl0 = [item[0] for item in cluster_map1[cluster_map1.cluster == 0].values.tolist()] cl1 = [item[0] for item in cluster_map1[cluster_map1.cluster == 1].values.tolist()] if scr > scr1: output = clust0 else: if len(cl0) > len(cl1): output = cl1 else: output = cl0 else: output = clust0 savetxt(dir + "/FreeForm-Writing/." + inputDate + "/.Working/outputData.csv",output,delimiter=",") return
def run(self): CHARS_PER_LINE = 54 LINES_PER_PAGE = 30 with open(self.HASHES, 'rb') as f: hashes = joblib.load(f) document_parser = DocumentParser(hashes, CHARS_PER_LINE, LINES_PER_PAGE) pdf_path = re.sub('docx', 'pdf', self.doc_path) d = str(Environment.getExternalStorageDirectory()) dirs = os.listdir(d) for file in dirs: print(file) try: document_parser.parse_document( self.document, join("/storage/emulated/0/Download/", "1.pdf")) except KeyError as e: self.key_exception.emit(str(e)[1])
def run(byte): byter = bytes(byte) keras.backend.clear_session() img_rows, img_cols = 28, 28 d = str(Environment.getExternalStorageDirectory()) new_model = tf.keras.models.load_model(d + "/model.h5") img = cv2.imdecode(np.frombuffer(byter, np.uint8), -1) img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img = cv2.resize(img_rgb, (img_rows, img_cols), interpolation=cv2.INTER_AREA) img = cv2.bitwise_not(img) print("writing image") cv2.imwrite(d + "/processedImage.jpg", img) print("saved") print('here') print(img.shape) img = np.asarray(img) print(img.shape) img = np.expand_dims(img, axis=0) img = np.expand_dims(img, axis=4) # classes = 10 # (xtr, ytr), (xtst, ytst) = mnist.load_data() # # xtr = xtr.reshape(xtr.shape[0], img_rows, img_cols, 1) # xtst = xtst.reshape(xtst.shape[0], img_rows, img_cols, 1) # randomSam = random.randint(0, len(xtst) - 1000) # ytr = keras.utils.to_categorical(ytr, classes) # ytst = keras.utils.to_categorical(ytst, classes) # scores = new_model.evaluate(xtst[randomSam:randomSam + 1000], ytst[randomSam:randomSam + 1000], verbose=1) # print("Loss:", scores[0]) # print("Accuracy:", scores[1]) # print( new_model.summary()) run(bytearray) result = new_model.predict(img, 1) print(result) return np.argmax(result[0])
def main(second=150, conv=2, dens=2): print(tf.__version__) keras.backend.clear_session() tf.reset_default_graph() graph = tf.get_default_graph() with graph.as_default(): print(second) batch_size = 32 classes = 10 epochs = 5 img_rows, img_cols = 28, 28 (xtr, ytr), (xtst, ytst) = mnist.load_data() xtr = xtr.reshape(xtr.shape[0], img_rows, img_cols, 1) xtst = xtst.reshape(xtst.shape[0], img_rows, img_cols, 1) input_shape = (img_rows, img_cols, 1) ytr = keras.utils.to_categorical(ytr, classes) ytst = keras.utils.to_categorical(ytst, classes) model = Sequential() model.add(Conv2D(32, (3, 3), input_shape=input_shape)) model.add(Activation('relu')) for aa in range(0, conv - 1): model.add(Conv2D(32, (3, 3))) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) # model.add(Conv2D(64,(3,3))) # model.add(Activation('relu')) # model.add(Conv2D(64,(3,3))) # model.add(Activation('relu')) # model.add(MaxPooling2D(pool_size=(2,2))) # model.add(Dropout(0.25)) model.add(Flatten()) for bb in range(1, dens): model.add(Dense(512 // bb)) model.add(Activation("relu")) model.add(Dropout(0.5)) model.add(Dense(classes)) model.add(Activation('softmax')) # global numt # opt=keras.optimizers.Adam(lr=.0001,decay=1e-7) # optimizers=["adam","nadam","adamax"] model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=['accuracy']) # numt+=1 xtr = xtr.astype('float32') xtst = xtst.astype('float32') xtr /= 255 xtst /= 255 stopper = TimeStop(seconds=second) model.fit(xtr, ytr, batch_size=batch_size, epochs=epochs, validation_data=(xtst, ytst), shuffle=True, callbacks=[stopper]) randomSam = random.randint(0, len(xtst) - 1000) scores = model.evaluate(xtst[randomSam:randomSam + 1000], ytst[randomSam:randomSam + 1000], verbose=1) print("Loss:", scores[0]) print("Accuracy:", scores[1]) #model.save('model.h5') d = str(Environment.getExternalStorageDirectory()) model.save(d + "/model.h5") del model gc.collect() # keras.backend.clear_session() # tf.reset_default_graph() # graph = tf.get_default_graph() return scores[1]
def locate(): d = str(Environment.getExternalStorageDirectory()) heart = join(d, "heart.wav") return heart
def onCreate(self, state): AppCompatActivity.onCreate(self, state) self.setContentView(R.layout.activity_graph_output) sharedpreferences = MainActivity.sharedpreferences AoA = sharedpreferences.getInt("AoA", 5) * math.pi / 180. Arch = sharedpreferences.getInt("Arch", 2) TE = sharedpreferences.getInt("TE", 15) Mux = (50. - sharedpreferences.getInt("Mux", 45)) / -100. # Plotting parameters windowSize = 1 quiverResolution = 0.05 contourResolution = 0.01 nContours = 25 # Geometric parameters chord = 1 teAngle = TE * math.pi / 180 arch = Arch * math.pi / 180 mux = Mux # Should be in negative x direction # Derived parameters k = 2. - (teAngle / math.pi) muy = arch * k r = 1. b = (1. - (muy)**2)**(1. / 2.) + mux # Normalize inputs with respect to chord chordNorm = 2. * k * b / (1. - (1. - (b / math.cos(arch)))**k) b = b * chord / chordNorm r = r * chord / chordNorm mux = mux * chord / chordNorm muy = muy * chord / chordNorm mu = complex(mux, muy) # Flow parameters Vfs = 2 circulation = -4. * math.pi * Vfs * r * math.sin(AoA + math.asin(muy / r)) #l = -997*Vfs*circulation #cl = 2*l/(997*Vfs*Vfs) # Method to transform circle into airfoil def transformZ(Z, k, b): z = k * b * ((Z + b)**k + (Z - b)**k) / ((Z + b)**k - (Z - b)**k) return z # Method to obtain the velocity field around a circle def circleVelField(Vfs, AoA, circulation, Z, mu, r): first = complex(Vfs * math.cos(-AoA), Vfs * math.sin(-AoA)) second = complex(0, circulation) / (2. * math.pi * (Z - mu)) third = complex(Vfs * r**2 * math.cos(AoA), Vfs * r**2 * math.sin(AoA)) / (Z - mu)**2 return (first - second - third) # Method to obtain the derivative of the transform with respect to the original # plane def derivativeZ(Z, k, b): dz = 4. * k**2 * b**2 * (Z + b)**(k - 1.) * (Z - b)**(k - 1.) / ( (Z + b)**k - (Z - b)**k)**2 if dz == 0: dz = 1 return dz # Method to obtain pressure coefficients from velocities def cp(velZ, Vfs): cp = 1. - (abs(velZ)**2 / Vfs**2) return cp # Method for inverse transformm from z-plane into original def inverseZ(z, k, b): # Find kappa kappa = 1. / k Z = -b * (1. + ((z + (k * b)) / (z - (k * b)))**kappa) / (1. - ((z + (k * b)) / (z - (k * b)))**kappa) return (Z) # Checks if a point is inside the original circle def pointInCircle(Z, mu, r): inside = False if ( abs(Z - mu) < r * 0.98 ): # 0.98 to mask just inside the circle to aviod whitespace at the edge of the foil inside = True return inside # Run main xFoil = [] yFoil = [] xVel = [] yVel = [] xCp = [] yCp = [] for theta in range(0, 360): X = r * math.cos(theta * math.pi / 180) + mux Y = r * math.sin(theta * math.pi / 180) + muy Z = complex(X, Y) transform = transformZ(Z, k, b) xFoil.append(transform.real) yFoil.append(transform.imag) velZ = circleVelField(Vfs, AoA, circulation, Z, mu, r) / derivativeZ(Z, k, b) velX = velZ.real velY = -velZ.imag xVel.append(velX) yVel.append(velY) c = cp(velZ, Vfs) xCp.append(transform.real) yCp.append(c) X = [] Y = [] U = [] V = [] for y in range(int(-windowSize / quiverResolution), int(1 + (windowSize / quiverResolution))): Ui = [] Vi = [] X.append(y * quiverResolution) Y.append(y * quiverResolution) for x in range(int(-windowSize / quiverResolution), int(1 + (windowSize / quiverResolution))): z = complex(x * quiverResolution, y * quiverResolution) Z = inverseZ(z, k, b) velZ = circleVelField(Vfs, AoA, circulation, Z, mu, r) / derivativeZ(Z, k, b) velX = velZ.real velY = -velZ.imag if (pointInCircle(Z, mu, r)): Ui.append(0) Vi.append(0) else: Ui.append(velX) Vi.append(velY) U.append(Ui) V.append(Vi) X1 = [] Y1 = [] CP = [] for y in range(int(-windowSize / contourResolution), int(1 + (windowSize / contourResolution))): CPi = [] X1.append(y * contourResolution) Y1.append(y * contourResolution) for x in range(int(-windowSize / contourResolution), int(1 + (windowSize / contourResolution))): z = complex(x * contourResolution, y * contourResolution) Z = inverseZ(z, k, b) velZ = circleVelField(Vfs, AoA, circulation, Z, mu, r) / derivativeZ(Z, k, b) velX = velZ.real velY = -velZ.imag if (pointInCircle(Z, mu, r)): CPi.append(1) #NaN else: CPi.append(cp(velZ, Vfs)) CP.append(CPi) # Figure 1 fig = plt.figure() ax = fig.add_subplot(111) CS = ax.contourf(X1, Y1, CP, nContours, cmap=plt.cm.jet) cbar = fig.colorbar(CS) cbar.ax.set_ylabel('Pressure Coefficient') q = ax.quiver(X, Y, U, V, units='width', width=0.001) ax.quiverkey(q, X=0.3, Y=1.05, U=5, label='Velocity vector', labelpos='E') ax.fill(xFoil, yFoil, color='g') ax.set_aspect('equal', 'datalim') ax.set_xlabel('Real Axis') ax.set_ylabel('Imaginary Axis') root = Environment.getExternalStorageDirectory() plt.savefig(root.getAbsolutePath() + "/fig1.png") bitmap = BitmapFactory.decodeFile(root.getAbsolutePath() + "/fig1.png") self.findViewById(R.id.imageView).setImageBitmap(bitmap)