@Override public byte[] asBytes() { if (allocationMode == AllocationMode.HEAP) { ByteArrayOutputStream bos = new ByteArrayOutputStream(getElementSize() * length()); DataOutputStream dos = new DataOutputStream(bos); if (dataType() == Type.DOUBLE) { if (doubleData == null) throw new IllegalStateException("Double array is null!"); try { for (int i = 0; i < doubleData.length; i++) dos.writeDouble(doubleData[i]); } catch (IOException e) { throw new RuntimeException(e); } } else { if (floatData == null) throw new IllegalStateException("Double array is null!"); try { for (int i = 0; i < floatData.length; i++) dos.writeFloat(floatData[i]); } catch (IOException e) { throw new RuntimeException(e); } } return bos.toByteArray(); } else { ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos); if (dataType() == Type.DOUBLE) { for (int i = 0; i < length(); i++) { try { dos.writeDouble(getDouble(i)); } catch (IOException e) { e.printStackTrace(); } } } else { for (int i = 0; i < length(); i++) { try { dos.writeFloat(getFloat(i)); } catch (IOException e) { e.printStackTrace(); } } } return bos.toByteArray(); } }
protected void write(DataOutputStream out) throws IOException { out.writeUTF(allocationMode.name()); out.writeInt(length()); out.writeUTF(dataType().name()); if (dataType() == Type.DOUBLE) { for (int i = 0; i < length(); i++) out.writeDouble(getDouble(i)); } else { for (int i = 0; i < length(); i++) out.writeFloat(getFloat(i)); } }
/** Writes the entire state of the MersenneTwister RNG to the stream */ public void writeState(DataOutputStream stream) throws IOException { int len = mt.length; for (int x = 0; x < len; x++) stream.writeInt(mt[x]); len = mag01.length; for (int x = 0; x < len; x++) stream.writeInt(mag01[x]); stream.writeInt(mti); stream.writeDouble(__nextNextGaussian); stream.writeBoolean(__haveNextNextGaussian); }
private byte[] getBytes(double[] array) { try { ByteArrayOutputStream bytestream = new ByteArrayOutputStream(); DataOutputStream datastream = new DataOutputStream(bytestream); for (double n : array) { datastream.writeDouble(n); } datastream.flush(); return bytestream.toByteArray(); } catch (IOException ioe) { Logging.logger().finest(ioe.getMessage()); } return null; }
@Override public void writeToFile(DataOutputStream out, Scene theScene) throws IOException { super.writeToFile(out, theScene); out.writeInt(VERSION); // Hardness. out.writeDouble((Double) getPropertyValue(0)); // setNamePositive. String str = (String) getPropertyValue(1); out.writeInt(str.length()); out.writeBytes(str); // setNameNegative. str = (String) getPropertyValue(2); out.writeInt(str.length()); out.writeBytes(str); }
@SuppressWarnings("rawtypes") private static void writeObjectToStream(Object obj, DataOutputStream data) throws IOException { Class objClass = obj.getClass(); if (objClass.equals(Boolean.class)) { data.writeBoolean((Boolean) obj); } else if (objClass.equals(Byte.class)) { data.writeByte((Byte) obj); } else if (objClass.equals(Integer.class)) { data.writeInt((Integer) obj); } else if (objClass.equals(String.class)) { data.writeUTF((String) obj); } else if (objClass.equals(Double.class)) { data.writeDouble((Double) obj); } else if (objClass.equals(Float.class)) { data.writeFloat((Float) obj); } else if (objClass.equals(Long.class)) { data.writeLong((Long) obj); } else if (objClass.equals(Short.class)) { data.writeShort((Short) obj); } }
public void writeBytes(OutputStream os) throws IOException { // Map between any modified UTF-8 and it's constant pool index. Map utf8ToIndex = new HashMap(); DataOutputStream dos = new DataOutputStream(os); TypeArray tags = getTags(); int len = (int) getLength(); int ci = 0; // constant pool index // collect all modified UTF-8 Strings from Constant Pool for (ci = 1; ci < len; ci++) { byte cpConstType = tags.getByteAt(ci); if (cpConstType == JVM_CONSTANT_Utf8) { Symbol sym = getSymbolAt(ci); utf8ToIndex.put(sym.asString(), new Short((short) ci)); } else if (cpConstType == JVM_CONSTANT_Long || cpConstType == JVM_CONSTANT_Double) { ci++; } } for (ci = 1; ci < len; ci++) { int cpConstType = (int) tags.getByteAt(ci); // write cp_info // write constant type switch (cpConstType) { case JVM_CONSTANT_Utf8: { dos.writeByte(cpConstType); Symbol sym = getSymbolAt(ci); dos.writeShort((short) sym.getLength()); dos.write(sym.asByteArray()); if (DEBUG) debugMessage("CP[" + ci + "] = modified UTF-8 " + sym.asString()); break; } case JVM_CONSTANT_Unicode: throw new IllegalArgumentException("Unicode constant!"); case JVM_CONSTANT_Integer: dos.writeByte(cpConstType); dos.writeInt(getIntAt(ci)); if (DEBUG) debugMessage("CP[" + ci + "] = int " + getIntAt(ci)); break; case JVM_CONSTANT_Float: dos.writeByte(cpConstType); dos.writeFloat(getFloatAt(ci)); if (DEBUG) debugMessage("CP[" + ci + "] = float " + getFloatAt(ci)); break; case JVM_CONSTANT_Long: { dos.writeByte(cpConstType); long l = getLongAt(ci); // long entries occupy two pool entries ci++; dos.writeLong(l); break; } case JVM_CONSTANT_Double: dos.writeByte(cpConstType); dos.writeDouble(getDoubleAt(ci)); // double entries occupy two pool entries ci++; break; case JVM_CONSTANT_Class: { dos.writeByte(cpConstType); // Klass already resolved. ConstantPool constains klassOop. Klass refKls = (Klass) getObjAt(ci); String klassName = refKls.getName().asString(); Short s = (Short) utf8ToIndex.get(klassName); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = class " + s); break; } // case JVM_CONSTANT_ClassIndex: case JVM_CONSTANT_UnresolvedClass: { dos.writeByte(JVM_CONSTANT_Class); String klassName = getSymbolAt(ci).asString(); Short s = (Short) utf8ToIndex.get(klassName); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = class " + s); break; } case JVM_CONSTANT_String: { dos.writeByte(cpConstType); String str = OopUtilities.stringOopToString(getObjAt(ci)); Short s = (Short) utf8ToIndex.get(str); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = string " + s); break; } // case JVM_CONSTANT_StringIndex: case JVM_CONSTANT_UnresolvedString: { dos.writeByte(JVM_CONSTANT_String); String val = getSymbolAt(ci).asString(); Short s = (Short) utf8ToIndex.get(val); dos.writeShort(s.shortValue()); if (DEBUG) debugMessage("CP[" + ci + "] = string " + s); break; } // all external, internal method/field references case JVM_CONSTANT_Fieldref: case JVM_CONSTANT_Methodref: case JVM_CONSTANT_InterfaceMethodref: { dos.writeByte(cpConstType); int value = getIntAt(ci); short klassIndex = (short) extractLowShortFromInt(value); short nameAndTypeIndex = (short) extractHighShortFromInt(value); dos.writeShort(klassIndex); dos.writeShort(nameAndTypeIndex); if (DEBUG) debugMessage( "CP[" + ci + "] = ref klass = " + klassIndex + ", N&T = " + nameAndTypeIndex); break; } case JVM_CONSTANT_NameAndType: { dos.writeByte(cpConstType); int value = getIntAt(ci); short nameIndex = (short) extractLowShortFromInt(value); short signatureIndex = (short) extractHighShortFromInt(value); dos.writeShort(nameIndex); dos.writeShort(signatureIndex); if (DEBUG) debugMessage( "CP[" + ci + "] = N&T name = " + nameIndex + ", type = " + signatureIndex); break; } } // switch } dos.flush(); return; }
/** * 从文件加载,同时缓存为二进制文件 * * @param path * @return */ public static MaxEntModel create(String path) { MaxEntModel m = new MaxEntModel(); try { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8")); DataOutputStream out = new DataOutputStream(new FileOutputStream(path + Predefine.BIN_EXT)); br.readLine(); // type m.correctionConstant = Integer.parseInt(br.readLine()); // correctionConstant out.writeInt(m.correctionConstant); m.correctionParam = Double.parseDouble(br.readLine()); // getCorrectionParameter out.writeDouble(m.correctionParam); // label int numOutcomes = Integer.parseInt(br.readLine()); out.writeInt(numOutcomes); String[] outcomeLabels = new String[numOutcomes]; m.outcomeNames = outcomeLabels; for (int i = 0; i < numOutcomes; i++) { outcomeLabels[i] = br.readLine(); TextUtility.writeString(outcomeLabels[i], out); } // pattern int numOCTypes = Integer.parseInt(br.readLine()); out.writeInt(numOCTypes); int[][] outcomePatterns = new int[numOCTypes][]; for (int i = 0; i < numOCTypes; i++) { StringTokenizer tok = new StringTokenizer(br.readLine(), " "); int[] infoInts = new int[tok.countTokens()]; out.writeInt(infoInts.length); for (int j = 0; tok.hasMoreTokens(); j++) { infoInts[j] = Integer.parseInt(tok.nextToken()); out.writeInt(infoInts[j]); } outcomePatterns[i] = infoInts; } // feature int NUM_PREDS = Integer.parseInt(br.readLine()); out.writeInt(NUM_PREDS); String[] predLabels = new String[NUM_PREDS]; m.pmap = new DoubleArrayTrie<Integer>(); TreeMap<String, Integer> tmpMap = new TreeMap<String, Integer>(); for (int i = 0; i < NUM_PREDS; i++) { predLabels[i] = br.readLine(); TextUtility.writeString(predLabels[i], out); tmpMap.put(predLabels[i], i); } m.pmap.build(tmpMap); for (Map.Entry<String, Integer> entry : tmpMap.entrySet()) { out.writeInt(entry.getValue()); } m.pmap.save(out); // params Context[] params = new Context[NUM_PREDS]; int pid = 0; for (int i = 0; i < outcomePatterns.length; i++) { int[] outcomePattern = new int[outcomePatterns[i].length - 1]; for (int k = 1; k < outcomePatterns[i].length; k++) { outcomePattern[k - 1] = outcomePatterns[i][k]; } for (int j = 0; j < outcomePatterns[i][0]; j++) { double[] contextParameters = new double[outcomePatterns[i].length - 1]; for (int k = 1; k < outcomePatterns[i].length; k++) { contextParameters[k - 1] = Double.parseDouble(br.readLine()); out.writeDouble(contextParameters[k - 1]); } params[pid] = new Context(outcomePattern, contextParameters); pid++; } } // prior m.prior = new UniformPrior(); m.prior.setLabels(outcomeLabels); // eval m.evalParams = new EvalParameters(params, m.correctionParam, m.correctionConstant, outcomeLabels.length); } catch (Exception e) { logger.severe("从" + path + "加载最大熵模型失败!" + TextUtility.exceptionToString(e)); return null; } return m; }
public void run() { int i, j, storedValues, sleepTime = 3000, timeoutCtr = 0, lastFlags = -1, trackCnt = 0, lastLocMethod = -5; String bssid; WMapEntry currEntry; DataOutputStream out; FileInputStream in; while (running) { try { if (scanData.getNoGPSExitInterval() > 0) { if (System.currentTimeMillis() > lastGPSTime + scanData.getNoGPSExitInterval()) { break; } } if (ScanService.scanData.getThreadMode() == OWMapAtAndroid.THREAD_MODE_UPLOAD) { if ((m_uploadThread != null) && (m_uploadThread.isUploading())) OWMapAtAndroid.sendMessage( ScannerHandler.MSG_SIMPLE_ALERT, 0, 0, getResources().getText(R.string.upload_in_progress)); else m_uploadThread = new UploadThread(scanData, this, SP, false, notification, null); ScanService.scanData.setThreadMode(OWMapAtAndroid.THREAD_MODE_SCAN); } else { if ((posState == 0) && (scanData != null) && (scanData.isScanningEnabled())) { posState = 1; timeoutCtr = 0; if (scanData.getFlags() != lastFlags) { if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0) scanData.getWifiManager().createWifiLock(WifiManager.WIFI_MODE_FULL, "OpenWLANMap"); else scanData .getWifiManager() .createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, "OpenWLANMap"); lastFlags = scanData.getFlags(); } if ((scanData.getFlags() & OWMapAtAndroid.FLAG_NO_NET_ACCESS) == 0) myWLocate.wloc_request_position(WLocate.FLAG_NO_IP_LOCATION); else { myWLocate.wloc_request_position( WLocate.FLAG_NO_NET_ACCESS | WLocate.FLAG_NO_IP_LOCATION); // stopGoogleLocation(); } } else if (!scanData.isScanningEnabled()) { try { trackCnt += 1500; Thread.sleep(1500); } catch (InterruptedException ie) { } } if (posState == 1) { // sleep while waiting for result try { trackCnt += 2500; java.lang.Thread.sleep(2500); // is interrupted from result handler timeoutCtr++; if (timeoutCtr > 3) { timeoutCtr = 0; posState = 0; } } catch (InterruptedException ie) { } } if ((posState == 2) || (posState == 100)) { loc_info locationInfo; NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); locationInfo = myWLocate.last_location_info(); if (lastLocMethod != locationInfo.lastLocMethod) { scanData.getmView().setMode(locationInfo.lastLocMethod); scanData.getmView().postInvalidate(); lastLocMethod = locationInfo.lastLocMethod; } if (posState == 100) locationInfo.lastLocMethod = -1; OWMapAtAndroid.sendMessage( OWMapAtAndroid.ScannerHandler.MSG_UPD_LOC_STATE, (int) (lastRadius * 1000), locationInfo.lastLocMethod, locationInfo); if (SP.getBoolean("autoConnect", false)) { if (!mWifi.isConnected()) { for (i = 0; i < locationInfo.wifiScanResult.size(); i++) { ScanResult result; result = locationInfo.wifiScanResult.get(i); result.capabilities = result.capabilities.toUpperCase(Locale.US); if ((isFreeHotspot(result) & WMapEntry.FLAG_IS_FREIFUNK) != 0) { // auto-connect to this open network WifiConfiguration wifiConfig = new WifiConfiguration(); wifiConfig.BSSID = result.BSSID; wifiConfig.priority = 1; wifiConfig.allowedKeyManagement.set(KeyMgmt.NONE); wifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wifiConfig.status = WifiConfiguration.Status.ENABLED; int netId = scanData.getWifiManager().addNetwork(wifiConfig); scanData.getWifiManager().enableNetwork(netId, true); } } } } if ((posValid) && (locationInfo.wifiScanResult != null) && (locationInfo.wifiScanResult.size() > 0)) { boolean foundExisting; for (i = 0; i < locationInfo.wifiScanResult.size(); i++) { ScanResult result; result = locationInfo.wifiScanResult.get(i); bssid = result.BSSID.replace(":", "").replace(".", "").toUpperCase(Locale.US); if (bssid.equalsIgnoreCase("000000000000")) break; foundExisting = false; scanData.getLock().lock(); for (j = 0; j < scanData.getWmapList().size(); j++) { currEntry = scanData.getWmapList().elementAt(j); if (currEntry.getBSSID().equalsIgnoreCase(bssid)) { currEntry.setPos(lastLat, lastLon); foundExisting = true; break; } } if (!foundExisting) { String lowerSSID; storedValues = scanData.incStoredValues(); scanData.getmView().setValue(storedValues); scanData.getmView().postInvalidate(); currEntry = new WMapEntry(bssid, result.SSID, lastLat, lastLon, storedValues); lowerSSID = result.SSID.toLowerCase(Locale.US); if ((lowerSSID.endsWith("_nomap")) || // Google unsubscibe option (lowerSSID.contains("iphone")) || // mobile AP (lowerSSID.contains("android")) || // mobile AP (lowerSSID.contains("motorola")) || // mobile AP (lowerSSID.contains("deinbus.de")) || // WLAN network on board of German bus (lowerSSID.contains("fernbus")) || // WLAN network on board of German bus (lowerSSID.contains("flixbus")) || // WLAN network on board of German bus (lowerSSID.contains("ecolines")) || // WLAN network on board of German bus (lowerSSID.contains("eurolines_wifi")) || // WLAN network on board of German bus (lowerSSID.contains("contiki-wifi")) || // WLAN network on board of bus (lowerSSID.contains("guest@ms ")) || // WLAN network on Hurtigruten ships (lowerSSID.contains("admin@ms ")) || // WLAN network on Hurtigruten ships (lowerSSID.contains("nsb_interakti")) || // WLAN network in NSB trains (lowerSSID.equals("southwestwifi"))) // WLAN network on Southwest flights currEntry.setFlags(currEntry.getFlags() | WMapEntry.FLAG_IS_NOMAP); else currEntry.setFlags(currEntry.getFlags() | isFreeHotspot(result)); if (isFreeHotspot(currEntry.getFlags())) scanData.incFreeHotspotWLANs(); scanData.getWmapList().add(currEntry); if ((scanData.getUploadThres() > 0) && (storedValues > scanData.getUploadThres())) { if ((m_uploadThread == null) || (!m_uploadThread.isUploading())) { if (mWifi.isConnected()) { m_uploadThread = new UploadThread(scanData, this, SP, true, notification, mWifi); } } } } result.capabilities = result.capabilities.toUpperCase(Locale.US); scanData.getLock().unlock(); } } scanData.getLock().lock(); for (j = 0; j < scanData.getWmapList().size(); j++) { currEntry = scanData.getWmapList().elementAt(j); if ((currEntry.getLastUpdate() + OWMapAtAndroid.RECV_TIMEOUT < System.currentTimeMillis()) && ((currEntry.getFlags() & WMapEntry.FLAG_IS_VISIBLE) == 0)) { scanData.getWmapList().remove(j); if (currEntry.posIsValid()) { int padBytes = 0, k; try { in = scanData.getCtx().openFileInput(OWMapAtAndroid.WSCAN_FILE); padBytes = in.available() % 28; in.close(); if (padBytes > 0) padBytes = 28 - padBytes; } catch (IOException ioe) { ioe.printStackTrace(); } try { out = new DataOutputStream( scanData .getCtx() .openFileOutput( OWMapAtAndroid.WSCAN_FILE, Context.MODE_PRIVATE | Context.MODE_APPEND)); if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0); out.write(currEntry.getBSSID().getBytes(), 0, 12); if ((currEntry.getFlags() & WMapEntry.FLAG_IS_NOMAP) != 0) { out.writeDouble(0.0); out.writeDouble(0.0); } else { out.writeDouble(currEntry.getLat()); out.writeDouble(currEntry.getLon()); } out.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if ((currEntry.getFlags() & (WMapEntry.FLAG_IS_FREIFUNK | WMapEntry.FLAG_IS_NOMAP)) == WMapEntry.FLAG_IS_FREIFUNK) { padBytes = 0; try { in = scanData.getCtx().openFileInput(OWMapAtAndroid.WFREI_FILE); padBytes = in.available() % 12; in.close(); if (padBytes > 0) padBytes = 12 - padBytes; } catch (IOException ioe) { ioe.printStackTrace(); } try { out = new DataOutputStream( scanData .getCtx() .openFileOutput( OWMapAtAndroid.WFREI_FILE, Context.MODE_PRIVATE | Context.MODE_APPEND)); if (padBytes > 0) for (k = 0; k < padBytes; k++) out.writeByte(0); out.write(currEntry.getBSSID().getBytes(), 0, 12); out.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } } // flushData(false); } scanData.getLock().unlock(); m_lastSpeed = locationInfo.lastSpeed; if (!SP.getBoolean("adaptiveScanning", true)) sleepTime = 500; else if (locationInfo.lastSpeed > 90) sleepTime = 350; else if (locationInfo.lastSpeed < 0) sleepTime = 1300; // no speed information, may be because of WLAN localisation else if (locationInfo.lastSpeed < 6) sleepTime = 2500; // user seems to walk else { double f; f = 1.0 - (locationInfo.lastSpeed / 90.0); sleepTime = (int) ((1000.0 * f) + 350); } try { trackCnt += sleepTime; java.lang.Thread.sleep(sleepTime); // sleep between scans } catch (InterruptedException ie) { } posState = 0; } } } catch (NullPointerException npe) // in case the parent activity dies too fast { npe.printStackTrace(); } if ((trackCnt > 500000) && (lastLat != 0) && (lastLon != 0)) { if (SP.getBoolean("track", false)) new UploadPositionTask().execute(null, null, null); trackCnt = 0; } } onDestroy(); // remove all resources (in case the thread was stopped due to some other reason }