working on it ...

Filters

Explore Public Snippets

Sort by

Found 48k snippets matching: read

    public by lbottaro modified Sep 10, 2013  302847  30  7  0

    How to read and parse a txt file in python

    This code shows how to read a txt file and parse the data
    import os
    import sys
    
    myfile = open('/some/path/to/file.txt', "r")
    # EXAMPLE OF FILE FORMAT:
    # abc 123 234 456 678
    # def 122223 2333334 454446 611178
    # ghi 144423 211134 44456 61114478
    
    for line in myfile.readlines():
        name= ''
        numList = list()
    
        print line
        try:
            name = line.split()[0] # it will get 'abc'/'def'/'ghi'
            numList = line.split()[1:] # it will get all other stuff inline...
        except:
            print "Invalid file format"
            myfile.close()
            sys.exit(1)
        
        if not numList:
            print("Invalid numList format! name= " + str(name))
            myfile.close()
            sys.exit(1)
    
        print 'name='+str(name)
        print 'numList='+str(numList)
    
    myfile.close()

    public by cghersi modified Jan 10, 2017  289502  1  8  0

    How to read a file into a string in Java

    This simple snippet reads a file and put the content into a returned string
    private static String readFileAsString(String filePath) throws java.io.IOException{
    
    	StringBuffer fileData = new StringBuffer(1000);
    	BufferedReader reader = new BufferedReader(new FileReader(filePath));
    	char[] buf = new char[1024];
    	int numRead=0;
    	while((numRead=reader.read(buf)) != -1){
    		String readData = String.valueOf(buf, 0, numRead);
    		fileData.append(readData);
    		buf = new char[1024];
    	}
    
    	reader.close();
    	return fileData.toString();
    }            

    public by sukhjinderkahlon modified Mar 9, 2016  325907  6  5  0

    How to Work with Excel Files Using Apache POI

    This code will work as a utility to read and write excel files using Apache POI Library. 3.13
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFCell;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class ExcelUtils {
    
    	private static HSSFSheet ExcelWSheet;
    	private static HSSFWorkbook ExcelWBook;
    	private static HSSFCell Cell;
    
    	private static HSSFRow Row;
    	
    	private static String filePath;
    	public static void setExcelFile(String Path,String SheetName) throws Exception {
    
    			try {
    
       			// Open the Excel file
    				filePath=Path;
    
    			FileInputStream ExcelFile = new FileInputStream(Path);
    
    			// Access the required test data sheet
    
    			ExcelWBook = new HSSFWorkbook(ExcelFile);
    
    			ExcelWSheet = ExcelWBook.getSheet(SheetName);
    			
    
    			} catch (Exception e){
    
    				throw (e);
    
    			}
    
    	}
    
    	//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
    
        public static String getCellData(int RowNum, int ColNum) throws Exception{
    
    			try{
    
      			Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
    
      			String CellData = Cell.getStringCellValue();
    
      			return CellData;
    
      			}catch (Exception e){
    
    				return"";
    
      			}
    
        }
    
    
        
      //This method is to write in the Excel cell, Row num and Col num are the parameters
    
    	public static void setCellData(String Result,  int RowNum, int ColNum) throws Exception	{
    
    			try{
    
      			Row  = ExcelWSheet.getRow(RowNum);
    
    			Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
    
    			if (Cell == null) {
    
    				Cell = Row.createCell(ColNum);
    
    				Cell.setCellValue(Result);
    
    				} else {
    
    					Cell.setCellValue(Result);
    
    				}
    
      // Constant variables Test Data path and Test Data file name
    
      				FileOutputStream fileOut = new FileOutputStream(filePath);
    
      				ExcelWBook.write(fileOut);
    
      				fileOut.flush();
    
    					fileOut.close();
    
    				}catch(Exception e){
    
    					throw (e);
    
    			}
    
    		}
    
    	
    }
              

    public by cghersi @ MailUp API DEV modified Jan 20, 2015  206433  6  6  1

    MailUp REST API - How to subscribe to a particular list several contacts with the "Confirmed Optin" Procedure

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void SubcribeRecipientsWithDoubleOptin(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Subscribe recipients:
        int idList = 1;
        List<ConsoleRecipientItem> recipients = new List<ConsoleRecipientItem>();
        ConsoleRecipientItem recipient1 = new ConsoleRecipientItem()
        {
            Email = "test1@mailup.com",
            Name = "First New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3331234567",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name1_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName1_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        ConsoleRecipientItem recipient2 = new ConsoleRecipientItem()
        {
            Email = "test2@mailup.com",
            Name = "Second New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3337654321",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name2_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName2_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        recipients.Add(recipient1);
        recipients.Add(recipient2);
        int subscriptionResult = 0;
        try
        {
            subscriptionResult = client.AddRecipientsToList(idList, recipients, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 2.1) wait for the end of import task:
        if (subscriptionResult > 0)
        {
            Console.WriteLine("Recipients Import started; import ID:" + subscriptionResult);
    
            //optionally we can check the import status:
            bool completed = false;
            do
            {
                ConsoleImportStatus importStatus = client.CheckImportStatus(subscriptionResult);
                if (importStatus == null)
                {
                    Console.WriteLine("Cannot check the import status for import task #" + subscriptionResult);
                    return;
                }
                completed = importStatus.Completed;
            } while (!completed);
            Console.WriteLine("Recipients Added!");
        }
        else
        {
            Console.WriteLine("An error occurred while adding the recipients.");
            return;
        }
    
        // 3) Retrieve the sendingID of the confirmation email related to the previous task:
        int sendingID = -1;
        try
        {
            sendingID = client.GetSendingIDForImport(subscriptionResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot retrieve sending ID due to " + ex.Message);
            return;
        }
        if (sendingID <= 0)
        {
            Console.WriteLine("Cannot retrieve sending ID.");
            return;
        }
    
        // 4) Send the confirmation email:
        EmailSendingItem sendingResult = null;
        try
        {
            sendingResult = client.SendEmailMessage(sendingID);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot send email due to " + ex.Message);
            return;
        }
        if (sendingResult == null)
            Console.WriteLine("Cannot send confirmation email.");
        else
            Console.WriteLine("Confirmation email sent!");
    }
                

    public by cghersi modified Jan 29, 2016  100681  198  13  9

    Java: read from USB using RXTX library

    This is a well-tested class to read from USB device using RXTX library. First of all place rxtxSerial.so (or rxtxSerial.dll) in the classpath. The received bytes are stored in a queue called "receivedBytes". This queue is filled by the serialEvent() callback called by RXTX framework. Users of this class should retrieve the ready data from "receiv
    import gnu.io.*;
    import java.io.*;
    
    import java.util.Enumeration;
    import java.io.IOException;
    
    /**
     * This class provides the utilities to read the data exchanged via USB port.
     */
    public class USBComm implements SerialPortEventListener {
    
    	/**
    	 * Stream for the storage of incoming data
    	 */
    	private InputStream inputStream;
    	/**
    	 * Stream for the dispatching of data
    	 */
    	private OutputStream outputStream;
    	/**
    	 * Timeout of the USB port
    	 */
    	private final int PORT_TIMEOUT = 2000;
    	/**
    	 * Representation of the serial port used for the communication
    	 */
    	private SerialPort serialPort;
    	/**
    	 * Buffer that stores the received bytes from the media
    	 */
    	protected LinkedBlockingQueue<Byte> receivedBytes;
    
    	/**
    	 * Builds a new manager for the communication via USB port.
    	 * @exception IOException if an error occurred during the opening of the USB port
    	 */
    	public USBComm() throws IOException {
    	  receivedBytes = new LinkedBlockingQueue<Byte>(100000);
    		String port = "COM1"; //place the right COM port here, OS dependent
    	
    		//Check that the USB port exists and is recognized:
    		Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();
    		boolean portFound = false;
    		CommPortIdentifier portId = null;
    		while (portList.hasMoreElements()) {
    			portId = (CommPortIdentifier) portList.nextElement();
    		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    		    	System.out.println.info(portId.getName());
    				if (portId.getName().equals(port)) {
    					System.out.println("Found port: " + port);
    				    portFound = true;
    				    break;
    				} 
    		    } 
    		} 
    	
    		if (!portFound) 
    		    throw new IOException("port " + port + " not found.");
    	
    		try {
    			System.out.println("USB port opening...");
    		    serialPort = (SerialPort) portId.open("USBCommunicator", PORT_TIMEOUT);
    		    System.out.println("USB port opened");
    		    inputStream = serialPort.getInputStream();
    		    outputStream = serialPort.getOutputStream();
    		    serialPort.addEventListener(this);
    			    	serialPort.notifyOnDataAvailable(true);
    			//#==================================================================#
    			// WARNING! - DO NOT SET THE FOLLOWING PROPERTY WITH RXTX LIBRARY, IT
    			// 			  CAUSES A PROGRAM LOCK:
    			// 	serialPort.notifyOnOutputEmpty(true);
    			//#==================================================================#
    			    	
    		    //wait for a while to leave the time to javax.comm to
    		    //correctly configure the port:
    		    Thread.sleep(1000);
    		    
    			int baudRate = 115200; //set propertly
    	    	serialPort.setSerialPortParams(baudRate, 
    	    		SerialPort.DATABITS_8, 
    	    		SerialPort.STOPBITS_1, 
    				SerialPort.PARITY_NONE);
    		    
    	    	serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    	    		
    		    System.out.println("setted SerialPortParams");
    		} catch (Exception e) {
    			System.err.println(e.getMessage());
    			throw new IOException(e.getMessage());
    		}
    	}
    
    	
    	public void closeUSB(){
    		//close the streams for serial port:
    		try {
    			inputStream.close();
    			outputStream.close();
    		} catch (IOException e) {
    			System.err.println("Cannot close streams:" + e.getMessage(), e);
    		}
    	}
    
    	/**
    	 * Listener for USB events
    	 * 
    	 * @param event new event occurred on the USB port
    	 */
    	public void serialEvent(SerialPortEvent event){
    		switch (event.getEventType()) {
    	
    			case SerialPortEvent.BI:
    			case SerialPortEvent.OE:
    			case SerialPortEvent.FE:
    			case SerialPortEvent.PE:
    			case SerialPortEvent.CD:
    			case SerialPortEvent.CTS:
    			case SerialPortEvent.DSR:
    			case SerialPortEvent.RI:
    			case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
    				//nothing to do...
    			    break;
    	
    			case SerialPortEvent.DATA_AVAILABLE:
    				byte received = -1;
    				do {
    					try {
    						received = (byte)inputStream.read();
    					} catch (IOException e) {
    						System.err.println("Error reading USB:" + e.getMessage());
    					}
    				
    					synchronized (receivedBytes) {
    						try {
    							receivedBytes.add(received);
    						} catch (IllegalStateException ew) {
    							System.err.println(ew.getMessage());
    							receivedBytes.poll();
    							receivedBytes.add(received);
    						}
    					}
    				} while(received != -1);
    
    			    break;
    		}
    	}
    
    	protected void write(byte[] buffer){
    	    try {
    	    	outputStream.write(buffer);
    	    	outputStream.flush();
    	    } catch (IOException e) {
    	    	System.err.println("Cannot write:" + e.getMessage());
    	    }
    	}
    }            

    public by bfranzoi modified Aug 3, 2016  145440  0  5  0

    document.ready

    $(document).ready(function() {
    
    
    
    
    });

    public by Lee Wei Yeong modified Jun 25, 2013  182385  0  4  0

    @ http://www.haskellforall.com/2013/06/from-zero-to-cooperative-threads-in-33.html

    @ http://www.haskellforall.com/2013/06/from-zero-to-cooperative-threads-in-33.html: free-monad-transform.hs
    data FreeF f a x = Pure a | Free (f x)
    
    newtype FreeT f m a =
        FreeT { runFreeT :: m (FreeF f a (FreeT f m a)) }
    
    instance (Functor f, Monad m) => Monad (FreeT f m) where
        return a = FreeT (return (Pure a))
        FreeT m >>= f = FreeT $ m >>= \v -> case v of
            Pure a -> runFreeT (f a)
            Free w -> return (Free (fmap (>>= f) w))
    
    instance MonadTrans (FreeT f) where
        lift = FreeT . liftM Pure
    
    liftF :: (Functor f, Monad m) => f r -> FreeT f m r
    liftF x = FreeT (return (Free (fmap return x)))
    
    

    public by Geometry modified Aug 7, 2016  88476  0  5  0

    FromText: Creates a new CsvReader to read from a string.

    Creates a new CsvReader to read from a string. The text containing the fields in the CSV format. if field names are located on the first non commented line, otherwise, .
    /// <summary>
    ///   Creates a new CsvReader to read from a string.
    /// </summary>
    /// 
    /// <param name="text">The text containing the fields in the CSV format.</param>
    /// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
    /// 
    public static CsvReader FromText(string text, bool hasHeaders)
    {
        return new CsvReader(new StringReader(text), hasHeaders, text.Length);
    }

    public by cghersi @ MailUp API DEV modified Nov 19, 2014  112656  9  5  0

    How to Retrieve your personal information with MailUp .NET SDK

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void GetPersonalDataFields(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Prepare the input:
        //nothing to do here...
    
        // 3) Invoke the web method:
        CollectionOf<ConsoleDynamicFieldItem> result = null;
        try
        {
            result = client.GetPersonalDataFields();
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
    
        if (result != null)
            Console.WriteLine("Personal Data Fields Retrieved: " + result.Count);
        else
            Console.WriteLine("Cannot retrieve Personal Data Fields.");
    }
    

    public by lucky80 modified May 8, 2013  8202  34  6  0

    C#: Read XML file into string

    This is a method to read XML file into string
    public static string GetXmlStringFromFile(string strFile)
            {
                // Load the xml file into XmlDocument object.
                XmlDocument xmlDoc = new XmlDocument();
                try
                {
                    xmlDoc.Load(strFile);
                }
                catch (XmlException e)
                {
                    throw new GenericException("Error in GetXmlString function", e);
                }
                // Now create StringWriter object to get data from xml document.
                StringWriter sw = new StringWriter();
                XmlTextWriter xw = new XmlTextWriter(sw);
                xmlDoc.WriteTo(xw);
                return sw.ToString();
            }
    • Public Snippets
    • Channels Snippets