Faster than stringifyStrictObjectMemory(), but cost a bit more memory
500876
function stringifyStrictObject( v , runtime )
{
	var i , iMax , keys ;
	
	runtime.str += '{' ;
	
	keys = Object.keys( v ) ;
	
	for ( i = 0 , iMax = keys.length ; i < iMax ; i ++ )
	{
		if ( v[ keys[ i ] ] !== undefined )
		{
			if ( i ) { runtime.str += ',' ; }
			stringifyString( keys[ i ] , runtime ) ;
			runtime.str += ':' ;
			stringifyAnyType( v[ keys[ i ] ] , runtime ) ;
		}
	}
	
	runtime.str += '}' ;
}
495728
private ByteBuffer toColumnName(Object obj) {
        SimpleCompositeBuilder composite = new SimpleCompositeBuilder(bufferSize, Equality.EQUAL);

        // Iterate through each component and add to a CompositeType structure
        for (FieldMapper<?> mapper : components) {
            try {
                composite.addWithoutControl(mapper.toByteBuffer(obj));
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return composite.get();
    }
1296163
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
        // Write out capacity and any hidden stuff
        s.defaultWriteObject();
    }
154895
function (string) {
         // TextEncoder + Uint8Array to binary string is faster than checking every bytes on long strings.
         // http://jsperf.com/utf8encode-vs-textencoder
         // On short strings (file names for example), the TextEncoder API is (currently) slower.
         if (JSZip.support.uint8array && typeof TextEncoder === "function") {
            var u8 = TextEncoder("utf-8").encode(string);
            return JSZip.utils.transformTo("string", u8);
         }
         if (JSZip.support.nodebuffer) {
            return JSZip.utils.transformTo("string", new Buffer(string, "utf-8"));
         }

         // array.join may be slower than string concatenation but generates less objects (less time spent garbage collecting).
         // See also http://jsperf.com/array-direct-assignment-vs-push/31
         var result = [], resIndex = 0;

         for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
               result[resIndex++] = String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
               result[resIndex++] = String.fromCharCode((c >> 6) | 192);
               result[resIndex++] = String.fromCharCode((c & 63) | 128);
            } else {
               result[resIndex++] = String.fromCharCode((c >> 12) | 224);
               result[resIndex++] = String.fromCharCode(((c >> 6) & 63) | 128);
               result[resIndex++] = String.fromCharCode((c & 63) | 128);
            }

         }

         return result.join("");
      }
900278
private static void listData(final Memory mem, final long offsetBytes, final long lengthInts,
      final StringBuilder sb) {
    final long memCap = mem.getCapacity();
    final long expectedCap = offsetBytes + (4L * lengthInts);
    checkCapacity(memCap, expectedCap);
    for (int i = 0; i < lengthInts; i++) {
      sb.append(String.format(fmt, i, mem.getInt(offsetBytes + (4L * i)))).append(LS);
    }
  }
39839
def as_bitcode(self):
        
        ptr = c_char_p(None)
        size = c_size_t(-1)
        ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size))
        if not ptr:
            raise MemoryError
        try:
            assert size.value >= 0
            return string_at(ptr, size.value)
        finally:
            ffi.lib.LLVMPY_DisposeString(ptr)
1105912
def string_to_bytes(string, size):
    """"""
    if len(string) > size:
        raise PyVLXException("string_to_bytes::string_to_large")
    encoded = bytes(string, encoding='utf-8')
    return encoded + bytes(size-len(encoded))
1291375
protected void _writeSimpleObject(Object value) throws IOException, JsonGenerationException {
	    /* 31-Dec-2009, tatu: Actually, we could just handle some basic
	     *    types even without codec. This can improve interoperability,
	     *    and specifically help with TokenBuffer.
	     */
	    if (value == null) {
	        writeNull();
	        return;
	    }
	    if (value instanceof String) {
	        writeString((String) value);
	        return;
	    }
	    if (value instanceof Number) {
	        Number n = (Number) value;
	        if (n instanceof Integer) {
	            writeNumber(n.intValue());
	            return;
	        } else if (n instanceof Long) {
	            writeNumber(n.longValue());
	            return;
	        } else if (n instanceof Double) {
	            writeNumber(n.doubleValue());
	            return;
	        } else if (n instanceof Float) {
	            writeNumber(n.floatValue());
	            return;
	        } else if (n instanceof Short) {
	            writeNumber(n.shortValue());
	            return;
	        } else if (n instanceof Byte) {
	            writeNumber(n.byteValue());
	            return;
	        } else if (n instanceof BigInteger) {
	            writeNumber((BigInteger) n);
	            return;
	        } else if (n instanceof BigDecimal) {
	            writeNumber((BigDecimal) n);
	            return;
	            
	        // then Atomic types
	            
	        } else if (n instanceof AtomicInteger) {
	            writeNumber(((AtomicInteger) n).get());
	            return;
	        } else if (n instanceof AtomicLong) {
	            writeNumber(((AtomicLong) n).get());
	            return;
	        }
	    } else if (value instanceof Boolean) {
	        writeBoolean(((Boolean) value).booleanValue());
	        return;
	    } else if (value instanceof AtomicBoolean) {
	        writeBoolean(((AtomicBoolean) value).get());
	        return;
	    }
	    throw new IllegalStateException("No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed "
	            +value.getClass().getName()+")");
	}
639268
public void updateMemoryInfo() {

		MemoryMXBean meminfo = ManagementFactory.getMemoryMXBean();

		MemoryUsage usage = meminfo.getHeapMemoryUsage();
		long _heapUsed = usage.getUsed();
		updateMaximum(heapUsed, _heapUsed);
		updateMaximum(heapTotal, usage.getMax());

		usage = meminfo.getNonHeapMemoryUsage();
		updateMaximum(nonHeapUsed, usage.getUsed());
		updateMaximum(nonHeapTotal, usage.getMax());

		// Log the memory usage if requested. Check the log level before logging
		// to minimize object creation overheads during preparation of the call
		// parameters.
		if (memoryLogger.isLoggable(Level.INFO)) {
			memoryLogger.log(Level.INFO, "MEM", new Object[] { _heapUsed });
		}
	}
1358013
function readMessageInChunksFromOutbox(message_hash, len, handleMessage){
	var CHUNK_LEN = 1000000;
	var start = 1;
	var message = '';
	function readChunk(){
		db.query("SELECT SUBSTR(message, ?, ?) AS chunk FROM outbox WHERE message_hash=?", [start, CHUNK_LEN, message_hash], function(rows){
			if (rows.length === 0)
				return handleMessage();
			if (rows.length > 1)
				throw Error(rows.length+' msgs by hash in outbox, start='+start+', length='+len);
			message += rows[0].chunk;
			start += CHUNK_LEN;
			(start > len) ? handleMessage(message) : readChunk();
		});
	}
	readChunk();
}
1020906
private static byte[] extractBytes(
      String str, 
      int startIndex, 
      int endIndex,
      char[] charArray, 
      boolean canFastConvert) throws UnsupportedEncodingException {
    if (canFastConvert) {
      // fast conversion, just copy the raw bytes
      final int len = endIndex - startIndex;
      byte[] strBytes = new byte[len];
      for (int i = 0; i < len; i++) {
        strBytes[i] = (byte) charArray[startIndex + i];
      }
      return strBytes;
    } 
    // otherwise, do expensive conversion
    return str.substring(startIndex, endIndex).getBytes(utf8charsetName);
  }
574825
@Override
    public final int encode(ValueReference<ByteBuffer> data, int size)
    {
        int bufferSize = size;
        ByteBuffer buf = data.get();
        if (buf == null) {
            buf = this.buffer;
            bufferSize = this.bufferSize;
            buffer.clear();
        }

        if (inProgress == null) {
            return 0;
        }

        int pos = 0;

        buf.limit(buf.capacity());
        while (pos < bufferSize) {
            //  If there are no more data to return, run the state machine.
            //  If there are still no data, return what we already have
            //  in the buffer.
            if (toWrite == 0) {
                if (newMsgFlag) {
                    inProgress = null;
                    break;
                }
                next();
            }

            //  If there are no data in the buffer yet and we are able to
            //  fill whole buffer in a single go, let's use zero-copy.
            //  There's no disadvantage to it as we cannot stuck multiple
            //  messages into the buffer anyway. Note that subsequent
            //  write(s) are non-blocking, thus each single write writes
            //  at most SO_SNDBUF bytes at once not depending on how large
            //  is the chunk returned from here.
            //  As a consequence, large messages being sent won't block
            //  other engines running in the same I/O thread for excessive
            //  amounts of time.
            if (pos == 0 && data.get() == null && toWrite >= bufferSize) {
                writeBuf.limit(writeBuf.capacity());
                data.set(writeBuf);
                pos = toWrite;
                writeBuf = null;
                toWrite = 0;
                return pos;
            }

            //  Copy data to the buffer. If the buffer is full, return.
            int toCopy = Math.min(toWrite, bufferSize - pos);
            int limit = writeBuf.limit();
            writeBuf.limit(Math.min(writeBuf.capacity(), writeBuf.position() + toCopy));
            int current = buf.position();
            buf.put(writeBuf);
            toCopy = buf.position() - current;
            writeBuf.limit(limit);
            pos += toCopy;
            toWrite -= toCopy;
        }

        data.set(buf);

        return pos;
    }
1190996
def readMemory(buffer, size, URL, encoding, options):
    
    ret = libxml2mod.xmlReadMemory(buffer, size, URL, encoding, options)
    if ret is None:raise treeError('xmlReadMemory() failed')
    return xmlDoc(_obj=ret)
873698
public static Long toLongObject(@Nullable String str, Long defaultValue) {
		if (StringUtils.isEmpty(str)) {
			return defaultValue;
		}
		try {
			return Long.valueOf(str);
		} catch (final NumberFormatException nfe) {
			return defaultValue;
		}
	}
340505
public static String generateMemoryStatus(Model net, int minibatch, InputType... inputTypes){
        MultiLayerNetwork mln = null;
        ComputationGraph cg = null;
        boolean isMLN;
        if(net instanceof MultiLayerNetwork){
            mln = (MultiLayerNetwork)net;
            isMLN = true;
        } else {
            cg = (ComputationGraph)net;
            isMLN = false;
        }

        StringBuilder sb = genericMemoryStatus();

        int bytesPerElement;
        switch (Nd4j.dataType()){
            case DOUBLE:
                bytesPerElement = 8;
                break;
            case FLOAT:
                bytesPerElement = 4;
                break;
            case HALF:
                bytesPerElement = 2;
                break;
            default:
                bytesPerElement = 0;    //TODO
        }

        sb.append("\n----- Workspace Information -----\n");
        List<MemoryWorkspace> allWs = Nd4j.getWorkspaceManager().getAllWorkspacesForCurrentThread();
        sb.append(f("Workspaces: # for current thread", (allWs == null ? 0 : allWs.size())));
        //sb.append(f("Workspaces: # for all threads", allWs.size()));      //TODO
        long totalWsSize = 0;
        if(allWs != null && allWs.size() > 0) {
            sb.append("Current thread workspaces:\n");
            //Name, open, size, currently allocated
            String wsFormat = "  %-26s%-12s%-30s%-20s";
            sb.append(String.format(wsFormat, "Name", "State", "Size", "# Cycles")).append("\n");
            for (MemoryWorkspace ws : allWs) {
                totalWsSize += ws.getCurrentSize();
                long numCycles = ws.getGenerationId();
                sb.append(String.format(wsFormat, ws.getId(),
                        (ws.isScopeActive() ? "OPEN" : "CLOSED"),
                        fBytes(ws.getCurrentSize()),
                        String.valueOf(numCycles))).append("\n");
            }
        }
        sb.append(fBytes("Workspaces total size", totalWsSize));
        Map<String,Pointer> helperWorkspaces;
        if(isMLN){
            helperWorkspaces = mln.getHelperWorkspaces();
        } else {
            helperWorkspaces = cg.getHelperWorkspaces();
        }
        if(helperWorkspaces != null && !helperWorkspaces.isEmpty()){
            boolean header = false;
            for(Map.Entry<String,Pointer> e : helperWorkspaces.entrySet()){
                Pointer p = e.getValue();
                if(p == null){
                    continue;
                }
                if(!header){
                    sb.append("Helper Workspaces\n");
                    header = true;
                }
                sb.append("  ").append(fBytes(e.getKey(), p.capacity()));
            }
        }

        long sumMem = 0;
        long nParams = net.params().length();
        sb.append("\n----- Network Information -----\n")
                .append(f("Network # Parameters", nParams))
                .append(fBytes("Parameter Memory", bytesPerElement * nParams));
        INDArray flattenedGradients;
        if(isMLN){
            flattenedGradients = mln.getFlattenedGradients();
        } else {
            flattenedGradients = cg.getFlattenedGradients();
        }
        if(flattenedGradients == null){
            sb.append(f("Parameter Gradients Memory", "<not allocated>"));
        } else {
            sumMem += (flattenedGradients.length() * bytesPerElement);
            sb.append(fBytes("Parameter Gradients Memory", bytesPerElement * flattenedGradients.length()));
        }
            //Updater info
        BaseMultiLayerUpdater u;
        if(isMLN){
            u = (BaseMultiLayerUpdater)mln.getUpdater(false);
        } else {
            u = cg.getUpdater(false);
        }
        Set<String> updaterClasses = new HashSet<>();
        if(u == null){
            sb.append(f("Updater","<not initialized>"));
        } else {
            INDArray stateArr = u.getStateViewArray();
            long stateArrLength = (stateArr == null ? 0 : stateArr.length());
            sb.append(f("Updater Number of Elements", stateArrLength));
            sb.append(fBytes("Updater Memory", stateArrLength * bytesPerElement));
            sumMem += stateArrLength * bytesPerElement;

            List<UpdaterBlock> blocks = u.getUpdaterBlocks();
            for(UpdaterBlock ub : blocks){
                updaterClasses.add(ub.getGradientUpdater().getClass().getName());
            }

            sb.append("Updater Classes:").append("\n");
            for(String s : updaterClasses ){
                sb.append("  ").append(s).append("\n");
            }
        }
        sb.append(fBytes("Params + Gradient + Updater Memory", sumMem));
            //Iter/epoch
        sb.append(f("Iteration Count", BaseOptimizer.getIterationCount(net)));
        sb.append(f("Epoch Count", BaseOptimizer.getEpochCount(net)));

            //Workspaces, backprop type, layer info, activation info, helper info
        if(isMLN) {
            sb.append(f("Backprop Type", mln.getLayerWiseConfigurations().getBackpropType()));
            if(mln.getLayerWiseConfigurations().getBackpropType() == BackpropType.TruncatedBPTT){
                sb.append(f("TBPTT Length", mln.getLayerWiseConfigurations().getTbpttFwdLength() + "/" + mln.getLayerWiseConfigurations().getTbpttBackLength()));
            }
            sb.append(f("Workspace Mode: Training", mln.getLayerWiseConfigurations().getTrainingWorkspaceMode()));
            sb.append(f("Workspace Mode: Inference", mln.getLayerWiseConfigurations().getInferenceWorkspaceMode()));
            appendLayerInformation(sb, mln.getLayers(), bytesPerElement);
            appendHelperInformation(sb, mln.getLayers());
            appendActivationShapes(mln, (inputTypes == null || inputTypes.length == 0 ? null : inputTypes[0]), minibatch, sb, bytesPerElement);
        } else {
            sb.append(f("Backprop Type", cg.getConfiguration().getBackpropType()));
            if(cg.getConfiguration().getBackpropType() == BackpropType.TruncatedBPTT){
                sb.append(f("TBPTT Length", cg.getConfiguration().getTbpttFwdLength() + "/" + cg.getConfiguration().getTbpttBackLength()));
            }
            sb.append(f("Workspace Mode: Training", cg.getConfiguration().getTrainingWorkspaceMode()));
            sb.append(f("Workspace Mode: Inference", cg.getConfiguration().getInferenceWorkspaceMode()));
            appendLayerInformation(sb, cg.getLayers(), bytesPerElement);
            appendHelperInformation(sb, cg.getLayers());
            appendActivationShapes(cg, sb, bytesPerElement);
        }

        //Listener info:
        Collection<TrainingListener> listeners;
        if(isMLN){
            listeners = mln.getListeners();
        } else {
            listeners = cg.getListeners();
        }

        sb.append("\n----- Network Training Listeners -----\n");
        sb.append(f("Number of Listeners", (listeners == null ? 0 : listeners.size())));
        int lCount = 0;
        if(listeners != null && !listeners.isEmpty()){
            for(TrainingListener tl : listeners) {
                sb.append(f("Listener " + (lCount++), tl));
            }
        }
        
        return sb.toString();
    }
677467
private static String[] fmtObjectToStrArray(Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof String[]) {
            return (String[]) object;
        }
        if (object instanceof Collection) {
            Collection c = (Collection) object;
            return (String[]) c.toArray(new String[c.size()]);
        }
        return null;
    }
791877
def parseMemory(buffer, size):
    
    ret = libxml2mod.xmlParseMemory(buffer, size)
    if ret is None:raise parserError('xmlParseMemory() failed')
    return xmlDoc(_obj=ret)