working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,958 snippets matching: memory

    public by cghersi @ Thotpot alumni  303274  0  5  0

    Java: generate hprof during runtime

    To generate hprof may be interesting for debug purpose, most of all before an OutOfMemory occurs on production applications! This .ini option halps to create an hprof to be analyzed before the occurrence of memory errors. See http://docs.oracle.com/javase/7/docs/technotes/samples/hprof.html for further details
    java -Xrunhprof:heap=sites,depth=10,thread=y,doe=y ...other jvm options in ini file...

    public by BrentHoover  122935  1  4  0

    A very rough and simple memory profiling middleware

    A very rough and simple memory profiling middleware: memorymiddleware.py
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    #Based on a StackOverflow post by Graham Dumpleton
    
    import os
    import psutil
    
    
    import logging
    from logging import StreamHandler
    shandler = StreamHandler()
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(shandler)
    
    
    class MemoryPerViewMiddleware(object):
    
        def process_request(self, request):
            request._mem = psutil.Process(os.getpid()).get_memory_info()
    
        def process_response(self, request, response):
            mem = psutil.Process(os.getpid()).get_memory_info()
            if hasattr(request, '_mem'):
                diff = mem.rss - request._mem.rss
                logger.debug('MEMORY USAGE %r: %s' % (int(diff), request.path))
            return response
    
    

    public by johansonkatherine  3166  0  6  1

    How to Convert MemoryStream Image to PDF inside Android Applications

    This technical tip shows how developers can convert MemoryStream image to PDF file inside their Android application. The Image class in Aspose.Pdf makes it possible to convert an image from various sources into PDF format. This may include an image from particular location over the hard-drive, an image from MemoryStream or an image at a web locatio
    try {
    
         // Create PDF document
    Pdfpdf = new Pdf();
    
         // Add a section into the PDF document
         Section sec1 = pdf.getSections().add();
    
    byte[] fileArray = null;
    
         //=====================================================//
         //	Get the Image contents into Byte Array
         //=====================================================//
    
    try {
    fileArray = getBytesFromFile(new File("/mnt/sdcard/Aspose.jpg"));
             } catch (IOException e) {
    e.printStackTrace();
             }
    
         // Create an image object in the section
    aspose.pdf.Image img1 = new aspose.pdf.Image(sec1);
    
         // Add image object into the Paragraphs collection of the section
    sec1.getParagraphs().add(img1);
    
         // Set the Image file type
    img1.getImageInfo().setImageFileType(ImageFileType.Jpeg);
    
         // Create a BinayFileStream Object to hold byte array
    BinaryFileStreambstream = new BinaryFileStream(fileArray);
         // Set the image object to use BinaySgtream object
    img1.getImageInfo().setImageStream(bstream);
    
         // Save the PDF file
    pdf.save("/mnt/sdcard/Image2PDF.pdf");
    
    }catch(java.io.IOExceptionioe){
    				System.out.println(ioe.getMessage());
    	}catch(Exception e){
    				System.out.println(e.getMessage());
    	      }
    }
    
    
    	//=====================================================//
    	// Method Returns the contents of file in a byte array
    	//=====================================================//
    
    	private static byte[] getBytesFromFile(File file) throws IOException {
    
    InputStream is = new FileInputStream(file);
    
            // Get the size of the file
    long length = file.length();
    
            /*
    	 * Ensure that file is not loarger than Integer.MAX_VALUE;
             */
    
    if (length >Integer.MAX_VALUE) {
    System.out.println("File is too large to process");
    return null;
            }
    
            // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];
    
            // Read in the bytes
    int offset = 0;
    intnumRead = 0;
    while ( (offset <bytes.length)
    &&
    ( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) ) {
    
    offset += numRead;
    
            }
    
            // Ensure all the bytes have been read in
    if (offset <bytes.length) {
    throw new IOException("Could not completely read file " + file.getName());
            }
    
    is.close();
    return bytes;
    
    	}
    

    public by cghersi  5447  2  7  0

    Object Query Language for Eclipse memory analyzer

    Memory Analyzer is a tool that helps the analysis of Hprof HEAP Dumps. Using OQL you can query the information you need in a SQL-like language! Here is an example of the use. Other information can be found here: http://eclipsesource.com/blogs/2013/01/21/10-tips-for-using-the-eclipse-memory-analyzer/
    SELECT toString(l.connectionId) FROM org.apache.activemq.command.ProducerId l WHERE (toString(l.connectionId) LIKE "ID:vm.*")

    public by lbottaro  2656  8  6  2

    How to detect your computer's RAM configuration via cmd prompt

    Using this simple WMI (Windows Management Instrumentation) command you can see how your RAM is configured on your pc. The output shows how many banks are used and their capacity. Output: Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All rights reserved. C:\wmic MEMORYCHIP get banklabel, devicelocator, caption, capaci
    C:\>wmic MEMORYCHIP get banklabel, devicelocator, caption, capacity

    public by Geometry  2935  1  6  0

    SetUnmanagedMemory: Fill memory region with specified value.

    Fill memory region with specified value. Destination pointer. Filler byte's value. Memory block's length to fill. Return's value of - pointer to destination.
    /// <summary>
    /// Fill memory region with specified value.
    /// </summary>
    /// 
    /// <param name="dst">Destination pointer.</param>
    /// <param name="filler">Filler byte's value.</param>
    /// <param name="count">Memory block's length to fill.</param>
    /// 
    /// <returns>Return's value of <paramref name="dst"/> - pointer to destination.</returns>
    /// 
    public static unsafe byte* SetUnmanagedMemory(byte* dst, int filler, int count)
    {
        return memset(dst, filler, count);
    }

    public by Geometry  2058  0  6  0

    SetUnmanagedMemory: Fill memory region with specified value.

    Fill memory region with specified value. Destination pointer. Filler byte's value. Memory block's length to fill. Return's value of - pointer to destination.
    /// <summary>
    /// Fill memory region with specified value.
    /// </summary>
    /// 
    /// <param name="dst">Destination pointer.</param>
    /// <param name="filler">Filler byte's value.</param>
    /// <param name="count">Memory block's length to fill.</param>
    /// 
    /// <returns>Return's value of <paramref name="dst"/> - pointer to destination.</returns>
    /// 
    public static IntPtr SetUnmanagedMemory(IntPtr dst, int filler, int count)
    {
        unsafe
        {
            SetUnmanagedMemory((byte*)dst.ToPointer(), filler, count);
        }
        return dst;
    }

    public by cghersi  2180  0  8  1

    Grab information from JVM regarding Memory

    Simple yet effective way to gather information regarding the current state of the memory
    public static String getMemoryInfo() {
    	Runtime r = Runtime.getRuntime();
    	StringBuilder sb = new StringBuilder();
      try {
      	// Read MemoryMXBean
      	MemoryMXBean memorymbean = ManagementFactory.getMemoryMXBean();
      	sb.append("Heap Memory Usage: " + memorymbean.getHeapMemoryUsage() + "\n");
      	sb.append("Non-Heap Memory Usage: " + memorymbean.getNonHeapMemoryUsage() + "\n");
      
      	// Read Garbage Collection information
      	sb.append("Garbage Collector Info" + "\n");
      	List<GarbageCollectorMXBean> gcmbeans = ManagementFactory.getGarbageCollectorMXBeans();
      	for (GarbageCollectorMXBean gcmbean : gcmbeans) {
      		sb.append("Name: " + gcmbean.getName() + "\n");
      		sb.append("Collection count: " + gcmbean.getCollectionCount() + "\n");
      		sb.append("Collection time: " + gcmbean.getCollectionTime() + "\n");
      		sb.append("Memory Pools: " + "\n");
      		String[] memoryPoolNames = gcmbean.getMemoryPoolNames();
      		for (int i = 0; i < memoryPoolNames.length; i++) {
      			sb.append("\t" + memoryPoolNames[i]);
      		}
      		sb.append("\n");
      	}
      
      	// Read Memory Pool Information
      	sb.append("Memory Pools Info" + "\n");
      	List<MemoryPoolMXBean> mempoolsmbeans = ManagementFactory.getMemoryPoolMXBeans();
      	for (MemoryPoolMXBean mempoolmbean : mempoolsmbeans) {
      		sb.append("Name: " + mempoolmbean.getName() + "\n");
      		sb.append("Usage: " + mempoolmbean.getUsage() + "\n");
      		sb.append("Collection Usage: " + mempoolmbean.getCollectionUsage() + "\n");
      		sb.append("Peak Usage: " + mempoolmbean.getPeakUsage()+ "\n");
      		sb.append("Type: " + mempoolmbean.getType() + "\n");
      		sb.append("Memory Manager Names: " + "\n");
      		String[] memManagerNames = mempoolmbean.getMemoryManagerNames();
      		for (int i = 0; i < memManagerNames.length; i++) {
      			sb.append("\t" + memManagerNames[i]);
      		}
      		sb.append("\n");
      	}
      } catch (Exception e) {
      	e.printStackTrace();
      }
    	long free = r.freeMemory();
    	long tot = r.totalMemory();
      sb.append("\nFREE MEMORY:").append(free).
        append("\nTOT  MEMORY:").append(tot).
        append("\nUSED MEMORY:").append(tot-free).
        append("\nMAX  MEMORY:").append(r.maxMemory());
      return sb.toString();
    }

    public by JKCPR  3335  1  6  2

    Measure memory usage in PHP (utility script):

    You can use this code snippet to measure memory usage in PHP
    <?php 
    $time = microtime(TRUE);
    $mem = memory_get_usage();
    
    /*[the code you want to measure here]*/
    
    print_r(array(
    
      'memory' => (memory_get_usage() - $mem) / (1024 * 1024),
    
      'seconds' => microtime(TRUE) - $time
    
    ));
    ?>

    public by sherazam  2496  1  5  0

    How to Convert Primitive Object to a Triangle Mesh with Custom Memory Layout in .NET Apps

    This Technical tip explains how .NET developers can convert primitive object to a triangle mesh with custom memory layout. Aspose.3D for .NET API allows developers to convert any primitive object to a triangle mesh with custom memory layout. The primitives include many of the most basic and most used objects like box, sphere, plane, cylinder, and t
    // Enter here the actual content of the snippet.            
    //This code example converts a Sphere to triangle mesh with custom memory layout.
    
    // [C# Code Sample]
    
    [StructLayout(LayoutKind.Sequential)]
    struct MyVertex
    {
        [Semantic(VertexFieldSemantic.Position)]
        FVector3 position;
        [Semantic(VertexFieldSemantic.Normal)]
        FVector3 normal;
    }
    public void TypedTriMesh()
    {
        Mesh sphere = (new Sphere()).ToMesh();
        //convert any mesh into typed TriMesh
        var myMesh = TriMesh<MyVertex>.FromMesh(sphere);
        //Get the vertex data in customized vertex structure.
        MyVertex[] vertex = myMesh.VerticesToTypedArray();
        //get the 32bit and 16bit indices
        int[] indices32bit;
        ushort[] indices16bit;
        myMesh.IndicesToArray(out indices32bit);
        myMesh.IndicesToArray(out indices16bit);
        using (MemoryStream ms = new MemoryStream())
        {
            //or we can write the vertex directly into stream like:
            myMesh.WriteVerticesTo(ms);
            //the indice data can be directly write to stream, we support 32-bit and 16-bit indice.
            myMesh.Write16bIndicesTo(ms);
            myMesh.Write32bIndicesTo(ms);
        }
        Console.WriteLine("Indices = {0}, Actual vertices = {1}, vertices before merging = {2}", myMesh.IndicesCount, myMesh.VerticesCount, myMesh.UnmergedVerticesCount);
        Console.WriteLine("Total bytes of vertices in memory {0}bytes", myMesh.VerticesSizeInBytes);
    
    }
    
    //[VB.NET Code Sample]
    
    <StructLayout(LayoutKind.Sequential)> Structure MyVertex
        <Semantic(VertexFieldSemantic.Position)>
        Private position As FVector3
        <Semantic(VertexFieldSemantic.Normal)>
        Private normal As FVector3
    End Structure
    Public Sub TypedTriMesh()
        Dim sphere As Mesh = (New Sphere()).ToMesh()
        'convert any mesh into typed TriMesh
        Dim myMesh = TriMesh(Of MyVertex).FromMesh(sphere)
        'Get the vertex data in customized vertex structure.
        Dim vertex As MyVertex() = myMesh.VerticesToTypedArray()
        'get the 32bit and 16bit indices
        Dim indices32bit As Integer()
        Dim indices16bit As UShort()
        myMesh.IndicesToArray(indices32bit)
        myMesh.IndicesToArray(indices16bit)
        Using ms As New MemoryStream()
            'or we can write the vertex directly into stream like:
            myMesh.WriteVerticesTo(ms)
            'the indice data can be directly write to stream, we support 32-bit and 16-bit indice.
            myMesh.Write16bIndicesTo(ms)
            myMesh.Write32bIndicesTo(ms)
        End Using
        Console.WriteLine("Indices = {0}, Actual vertices = {1}, vertices before merging = {2}", myMesh.IndicesCount, myMesh.VerticesCount, myMesh.UnmergedVerticesCount)
        Console.WriteLine("Total bytes of vertices in memory {0}bytes", myMesh.VerticesSizeInBytes)
        End Sub
    
    //This code example converts a Box to triangle mesh with custom memory layout.
    
    // [C# Code Sample]
    
    // get mesh of the Box
    Mesh box = (new Box()).ToMesh();
    //create a customized vertex layout
    VertexDeclaration vd = new VertexDeclaration();
    VertexField position = vd.AddField(VertexFieldDataType.FVector4, VertexFieldSemantic.Position);
    vd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Normal);
    // get a triangle mesh
    TriMesh triMesh = TriMesh.FromMesh(box);
    
    //[VB.NET Code Sample]
    
    ' get mesh of the Box
    Dim box As Mesh = (New Box()).ToMesh()
    'create a customized vertex layout
    Dim vd As New VertexDeclaration()
    Dim position As VertexField = vd.AddField(VertexFieldDataType.FVector4, VertexFieldSemantic.Position)
    vd.AddField(VertexFieldDataType.FVector3, VertexFieldSemantic.Normal)
    ' get a triangle mesh
    Dim triMesh As TriMesh = TriMesh.FromMesh(box)
    
    
    • Public Snippets
    • Channels Snippets