working on it ...

Filters

Explore Public Snippets

Sort by

Found 7,853 snippets

    public by nala58008  196  1  2  0

    ThreadedTcpServerWorker

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package com.devdungeon.tcpexamples.threadedserver;
    
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Socket;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    /**
     *
     * @author dtron
     */
    public class ThreadedTcpServerWorker extends Thread {
    
        protected Socket connectionSocket = null;
    
        public ThreadedTcpServerWorker(Socket connectionSocket) {
            this.connectionSocket = connectionSocket;
        }
    
        public void run() {
            System.out.println("Hello from a thread!");
    
            try {
                BufferedReader inFromClient = new BufferedReader(new InputStreamReader(this.connectionSocket.getInputStream()));
                DataOutputStream outToClient = new DataOutputStream(this.connectionSocket.getOutputStream());
                String clientRequest = null;
    
                clientRequest = inFromClient.readLine();
                System.out.println("Received from client: " + clientRequest);
                outToClient.write("HTTP/1.1 200 OK\n\n".getBytes());
                outToClient.write(clientRequest.getBytes());
                outToClient.close();
                inFromClient.close();
                        
            } catch (IOException ex) {
                Logger.getLogger(ThreadedTcpServerWorker.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    

    public by sherazam  2874  3  5  0

    How to Convert PDF Pages to TIFF Image inside .NET Applications

    This technical tip shows how to convert PDF pages to TIFF image inside .NET Applications. The TiffDevice class allows you to convert PDF pages to TIFF images. This class provides a method named Process which allows you to convert all the pages in a PDF file to a single TIFF image. To convert a particular page in a PDF file to a TIFF image, use an
    // Enter here the actual content of the snippet.            
    //The following code snippet shows how to convert all the PDF pages to a single TIFF image.
    
    //[C# Code Sample]
     
    
    // Open document
    Document pdfDocument = new Document("input.pdf");
    
    // Create Resolution object
    Resolution resolution = new Resolution(300);
    
    // Create TiffSettings object
    TiffSettings tiffSettings = new TiffSettings();
    tiffSettings.Compression = CompressionType.None;
    tiffSettings.Depth = ColorDepth.Default;
    tiffSettings.Shape = ShapeType.Landscape;
    tiffSettings.SkipBlankPages = false;
    
    // Create TIFF device
    TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings);
    
    // Convert a particular page and save the image to stream
    tiffDevice.Process(pdfDocument, "output.tif");
    
    //[VB.NET Code Sample]
     
    
    'Open document
    Dim pdfDocument As New Document("input.pdf")
    
    'Create Resolution object
    Dim resolution As New Resolution(300)
    
    'Create TiffSettings object
    Dim tiffSettings As New TiffSettings()
    tiffSettings.Compression = CompressionType.None
    tiffSettings.Depth = ColorDepth.Default
    tiffSettings.Shape = ShapeType.Landscape
    tiffSettings.SkipBlankPages = False
    
    'Create TIFF device
    Dim tiffDevice As New TiffDevice(resolution, tiffSettings)
    
    'Convert a particular page and save the image to stream
    tiffDevice.Process(pdfDocument, "output.tif")
    
    
    //Convert One Page to TIFF Image
    
    //[C# Code Sample]
     
    
    // Open document
    Document pdfDocument = new Document("input.pdf");
    
    // Create Resolution object
    Resolution resolution = new Resolution(300);
    
    // Create TiffSettings object
    TiffSettings tiffSettings = new TiffSettings();
    tiffSettings.Compression = CompressionType.None;
    tiffSettings.Depth = ColorDepth.Default;
    tiffSettings.Shape = ShapeType.Landscape;
    tiffSettings.SkipBlankPages = false;
    
    // Create TIFF device
    TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings);
    
    
    // Convert a particular page and save the image to stream
    tiffDevice.Process(pdfDocument, 1, 1, "output.tif");
    
    
    //[VB.NET Code Sample]
     
    
    'Open document
    Dim pdfDocument As New Document("input.pdf")
    
    'Create Resolution object
    Dim resolution As New Resolution(300)
    
    'Create TiffSettings object
    Dim tiffSettings As New TiffSettings()
    tiffSettings.Compression = CompressionType.None
    tiffSettings.Depth = ColorDepth.Default
    tiffSettings.Shape = ShapeType.Landscape
    tiffSettings.SkipBlankPages = False
    
    'Create TIFF device
    Dim tiffDevice As New TiffDevice(resolution, tiffSettings)
    
    'Convert a particular page and save the image to stream
    tiffDevice.Process(pdfDocument, 1, 1, "output.tif")
    
    //Use Bradley algorithm during conversion
    
    //[C# Code Sample]
     
    
    string outputImageFile = @"c:\resultant.tif";
    string outputBinImageFile = @"c:\37116-bin.tif";
    //open document
    Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(@"c:\input.pdf");
    //create Resolution object
    Resolution resolution = new Resolution(300);
    //create TiffSettings object
    TiffSettings tiffSettings = new TiffSettings();
    tiffSettings.Compression = CompressionType.LZW;
    tiffSettings.Depth = Aspose.Pdf.Devices.ColorDepth.Format1bpp;
    //create TIFF device
    TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings);
    //convert a particular page and save the image to stream
    tiffDevice.Process(pdfDocument, outputImageFile);
    
    using (FileStream inStream = new FileStream(outputImageFile, FileMode.Open))
    {
           using (FileStream outStream = new FileStream(outputBinImageFile, FileMode.Create))
           {
                  tiffDevice.BinarizeBradley(inStream, outStream, 0.1);
           }
    }
    
    //[VB.NET Code Sample]
     
    
    Dim outputImageFile As String = "c:\resultant.tif"
    Dim outputBinImageFile As String = "c:\37116-bin.tif"
    'open document
    Dim pdfDocument As Aspose.Pdf.Document = New Aspose.Pdf.Document("c:\input.pdf")
    'create Resolution object
    Dim resolution As Aspose.Pdf.Devices.Resolution = New Aspose.Pdf.Devices.Resolution(300)
    'create TiffSettings object
    Dim tiffSettings As TiffSettings = New TiffSettings()
    tiffSettings.Compression = CompressionType.LZW
    tiffSettings.Depth = Aspose.Pdf.Devices.ColorDepth.Format1bpp
    'create TIFF device
    Dim tiffDevice As TiffDevice = New TiffDevice(resolution, tiffSettings)
    'convert a particular page and save the image to stream
    tiffDevice.Process(pdfDocument, outputImageFile)
    
    Using inStream As FileStream = New FileStream(outputImageFile, FileMode.Open)
    
        Using outStream As FileStream = New FileStream(outputBinImageFile, FileMode.Create)
            tiffDevice.BinarizeBradley(inStream, outStream, 0.1)
        End Using
    End Using
    
    

    public by toandv  326  0  3  0

    Array Covariance

    Array Covariance: ArrayCovariance.scala
    // Arrays are covariant in Java, but it's not necessary.
    String[] s = new String[2];
    Object[] o = s;
    o[0] = 1; // ArrayStoreException
    
    // Arrays in Scala are not covariant
    val a: Array[NonEmpty] = Array(new NonEmpty(1, Empty, Empty))
    val b: Array[IntSet] = a // Compilation error
    
    

    public by code.universe  1792  0  5  0

    equalTo() - override

    equalTo() - override descr
    import org.apache.commons.lang3.builder.EqualsBuilder;
    
    class Cake {
    	String type;
    
    	public Cake(String type) {
    		this.type = type;
    
    	}
    
    	@Override
    	public boolean equals(Object obj) {
    		if (!(obj instanceof Cake)) {
    			return false;
    		} else if (obj == this) {
    			return true;
    		}
    
    		Cake rhs = (Cake) obj;
    		return new EqualsBuilder().append(type, rhs.type).isEquals();
    
    
    	}
    
    }

    public by terekhovm  3949  0  6  0

    equalTo() - override

    equalTo() - override descr
    import org.apache.commons.lang3.builder.EqualsBuilder;
    
    class Cake {
    	String type;
    
    	public Cake(String type) {
    		this.type = type;
    
    	}
    
    	@Override
    	public boolean equals(Object obj) {
    		if (!(obj instanceof Cake)) {
    			return false;
    		} else if (obj == this) {
    			return true;
    		}
    
    		Cake rhs = (Cake) obj;
    		return new EqualsBuilder().append(type, rhs.type).isEquals();
    
    
    	}
    
    }

    public by dlee0113  2406  0  3  0

    Simple Word Counter implemented using Akka

    Simple Word Counter implemented using Akka: WordCounter.scala
    import akka.actor.{ Actor, ActorRef, Props, ActorSystem }
    
    case class ProcessStringMsg(string: String)
    case class StringProcessedMsg(words: Integer)
    
    class StringCounterActor extends Actor {
      def receive = {
        case ProcessStringMsg(string) => {
          val wordsInLine = string.split(" ").length
          sender ! StringProcessedMsg(wordsInLine)
        }
        case _ => println("Error: message not recognized")
      }
    }
    
    case class StartProcessFileMsg()
    
    class WordCounterActor(filename: String) extends Actor {
    
      private var running = false
      private var totalLines = 0
      private var linesProcessed = 0
      private var result = 0
      private var fileSender: Option[ActorRef] = None
    
      def receive = {
        case StartProcessFileMsg() => {
          if (running) {
            // println just used for example purposes;
            // Akka logger should be used instead
            println("Warning: duplicate start message received")
          } else {
            running = true
            fileSender = Some(sender) // save reference to process invoker
            import scala.io.Source._
            fromFile(filename).getLines.foreach { line =>
              context.actorOf(Props[StringCounterActor]) ! ProcessStringMsg(line)
              totalLines += 1
            }
          }
        }
        case StringProcessedMsg(words) => {
          result += words
          linesProcessed += 1
          if (linesProcessed == totalLines) {
            fileSender.map(_ ! result) // provide result to process invoker
          }
        }
        case _ => println("message not recognized!")
      }
    }
    
    object Sample extends App {
    
      import akka.util.Timeout
      import scala.concurrent.duration._
      import akka.pattern.ask
      import akka.dispatch.ExecutionContexts._
      implicit val ec = global
        
      override def main(args: Array[String]) {
        val system = ActorSystem("System")
        val actor = system.actorOf(Props(new WordCounterActor(args(0))))
        implicit val timeout = Timeout(25 seconds)
        val future = actor ? StartProcessFileMsg()
        future.map { result =>
          println("Total number of words " + result)
          system.shutdown
        }
      }
    }
    
    

    public by DanielOgbuagu  201738  1  5  0

    Adding a *.jar file (originating from java-wrapped C++ code) to an SBT project classpath

    I thought using unmanaged dependencies in SBT projects was simply dropping a jar file into the lib directory, until I bought an SDK for a biometric device. Both the C++ and the Java packages were provided. I opted for the Java package, copying the provided jar file and the JNI (*.so) files into the appropriate locations and configuring the ja
    /**
     * In my <code>build.sbt</code> file, I appended a blank line and then the following:
     */
    
    libraryDependencies += "groupID" % "artifactId" % "revision" from "file:///home/Danogbuagu/Projects/biometric-lib/filename.jar"
    
    // where,
    // groupID for example is like: com.zigzagcompany 
    // artifactId for example is like: zigzag
    // revision for example is like: 1.3.4
    // Remember the line befor the code and that after.

    public by SammSampa  2463  3  6  1

    Loop through an Object Contents in Javascript

    // Enter here the actual content of the snippet.            
    var obj={
      id:1,
      url:'http://www.facebook.com',
    }
    
     Object.getOwnPropertyNames(obj).forEach(function (val, idx, array) {
    
                console.log(val + 'has' + obj[val]);
      });            

    public by DanielOgbuagu  4161  1  6  4

    Creating MongoDb Compound Indexes in Liftweb (i.e. Scala)

    // Assuming the following Person class and companion object:
    class Person extends MongoRecord[Person] with ObjectIdPk[Person] {
      def meta = Person
    
      object surname extends StringField(this, 40) 
    
      object firstName extends StringField(this, 40) 
    
      object otherNames extends StringField(this, 40) {
        override def optional_? = true
      }
      
      // other fields ...
      
    }
    
    object Person extends Person with MongoMetaRecord[Person]
    with RogueMetaRecord[Person] with Loggable {
    
      import mongodb.BsonDSL._
    
      override def collectionName = "Persons"
    
    // Now, here's the compound index, unique on the combined fields.
      val nameKeys = (surname.name -> 1) ~ (firstName.name -> 1)
      createIndex(nameKeys, unique = true)
    }
    

    public by apellizzaro  3337  0  6  1

    Case class constructor

    Best practice on how to have a overloaded constructor for case classes
    Case Class Friend (michele:String, antonio: Int);
    
    Object Friend {
    
    	public Friend (i:Int, s:String) = Friend (s,i)
    }
    
    
    • Public Snippets
    • Channels Snippets