xyzio

Archive for September 2014

Validating a XML against XSD schema in C#

leave a comment »

Inputs:

xmlFileName: Input XML file name
schemaFileName: Input XSD file name

Output:

results: Results output

using System.Xml;
using System.Xml.Schema;
using System.IO;

static List<string> results = new List<string>();

        static void Validate(string xmlFileName, string schemaFileName)
        {
            XmlDocument x = new XmlDocument();
            string source = xmlFileName;
            x.Load(source);

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CloseInput = true;
            settings.ValidationEventHandler += Handler;

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, schemaFileName);
            settings.ValidationFlags =
                 XmlSchemaValidationFlags.ReportValidationWarnings |
            XmlSchemaValidationFlags.ProcessIdentityConstraints |
            XmlSchemaValidationFlags.ProcessInlineSchema |
            XmlSchemaValidationFlags.ProcessSchemaLocation;

            StringReader r;
            using (StreamReader sr = new StreamReader(source))
            {
                r = new StringReader(sr.ReadToEnd());
            }

            using (XmlReader validatingReader = XmlReader.Create(r, settings))
            {
                while (validatingReader.Read()) { /* just loop through document */ }
            }
        }

        private static void Handler(object sender, ValidationEventArgs e)
        {
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
                results.Add(String.Format("Line: {0}, Position: {1} "{2}"", e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));
        }

Written by M Kapoor

September 30, 2014 at 3:21 pm

Posted in c#

Batch converting videos to play on the Nexus 7 using FFMPEG

leave a comment »

How to batch convert videos to play on the Nexus 7 using FFMPEG in Python.

mypath = r'path_to_video_files'

from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]

for file in onlyfiles:
    infile = '"' + mypath + file + '"'
    outfile = '"' + mypath + file + '.mp4' + '"'
    ffmpegpath = r'ffmpeg.exe'
    cmd = r' -i ' + infile + ' -acodec libmp3lame -vcodec libx264 -aspect 16:9 -s 800x480 -ab 128k -b 512k -f mp4 -strict experimental ' + outfile
    import os
    os.system(ffmpegpath + cmd)

Starting source:

http://stackoverflow.com/questions/8589976/how-to-convert-an-mkv-with-subtitles-to-something-nexus-one-friendly

Written by M Kapoor

September 29, 2014 at 3:01 pm

Posted in java

Tagged with

Passing a datastructure between Android activities as JSON

leave a comment »

Passing a data structure between Android activities as JSON using Gson.

In the sending Activity:

//Data
Droplet data = new Droplet();
//Create intent
Intent intent = new Intent(SendingClass.this, ReceivingClass.class);
//Create JSON object from data structure
Gson gson = new Gson();
String json = gson.toJson(data);
//Add JSON to intent
intent.putExtra("json", json);
//Start Activity with intent
startActivity(intent);

In the receiving Activity:

//Get string
String json = extras.getString("json","-1");
//Convert JSON to class
Gson gson = new Gson();
Droplet droplet = gson.fromJson(json, Droplet.class);

Where Droplet is defined here.

Written by M Kapoor

September 26, 2014 at 5:13 pm

Posted in java

Going through a xlsx spreadsheet by column in Python

leave a comment »

Most examples iterate by row. This one iterates by col.

import xlrd

workbook = xlrd.open_workbook('test_file.xlsx')
worksheet = workbook.sheet_by_index(0)

num_cols = worksheet.ncols - 1
curr_col = -1
while curr_col < num_cols:
    #Iterate through cols
    curr_col += 1
    col = worksheet.col(curr_col)
    for cell in col:
        #Iterate through cells in col
        print cell.value

Written by M Kapoor

September 25, 2014 at 3:29 pm

Posted in python

Generating a file filled with random characters in Python

leave a comment »

Generating a file filled with random characters in Python and printing out the elapsed time.

Output goes in tempOut.txt

#!/usr/bin/python

import random
import string
import time

start = time.time()

f = open('tempOut.txt', 'w')

for i in range(0,100000):
    line = ''
    for j in range(0,5000):
        line += str(random.choice(string.letters))

    f.write(line + "n")
    line = ''


f.close()

end = time.time()

print "Elapsed: " + str(end - start)

Written by M Kapoor

September 24, 2014 at 4:58 pm

Posted in python

Getting a JSON object from DigitalOcean in Java

leave a comment »

How to get a JSON object from DigitalOcean. This uses Gson.

Getting the HTTP object.

Inputs:

url: URL to access i.e. https://api.digitalocean.com/v2/droplets/
auth_key: Authorization key from DO.

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

    private static InputStream retrieveStream(String url, String auth_key) {

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet(url);

        getRequest.addHeader("Authorization","Bearer " + auth_key);
    try {
        HttpResponse getResponse = client.execute(getRequest);  
        statusCode = getResponse.getStatusLine().getStatusCode();

        HttpEntity getResponseEntity = getResponse.getEntity();
        return getResponseEntity.getContent();
    } 
    catch (IOException e) {
        getRequest.abort();
    }
    return null;
}

Converting the response into a Java object:

        InputStream stream = retrieveStream(url, auth_key);
        Reader reader = new InputStreamReader(stream);

        Gson gson = new Gson();
        Droplets response = gson.fromJson(reader, Droplets.class);

Where Droplets.class is implemented like this and Droplet.class is implemented like this.

Written by M Kapoor

September 23, 2014 at 3:46 pm

Posted in java

C#: Recursively getting a list of files with a specific extension

leave a comment »

How to recursively get a list of files with a specific extension in C#.

Inputs:

sDir – Starting directory
SExtension – file extension to filter by
List files – A empty list that is used to keep found files while recursing.

        public List<string> getFiles(string sDir, string sExtension, List<string> files)
        {
            foreach (string d in Directory.GetDirectories(sDir))
            {
                foreach (string f in Directory.GetFiles(d))
                {
                    if (f.EndsWith(sExtension))
                    {
                        files.Add(f);
                    }
                }
                getFiles(d, sExtension, files);
            }
            return files;
        }

Starting Source:
http://stackoverflow.com/questions/929276/how-to-recursively-list-all-the-files-in-a-directory-in-c

Written by M Kapoor

September 22, 2014 at 3:28 pm

Posted in c#

How to get an API Token from Digital Ocean

with 2 comments

An authorization token is required when connecting to Digital Ocean through a third-party app.  The token is used in the header tag of the connection to verify that you’ve authorized the connection.

To get the API token, log into the control panel through the log-in page:  https://cloud.digitalocean.com/login

Then click on the Apps & API (1) link and go to the Generate new token (2) button.

 

After clicking on the Apps & API link, you’ll get to New Personal Access Token page.  First enter a token name (3) – I have TestToken in the example below.  Then select the access level (4), read is recommended unless you want the app you are authorizing to edit droplets and settings in your account.  Finally, click on Generate Token (5) to generate your token.

Clicking Generate Token will take you back to the Personal Access tokens page.  At this point you’ll be presentated with the token.  Copy this token to a safe place.  You will only see it once.  Use the delete button to delete the token.

 

 

 

Written by M Kapoor

September 21, 2014 at 8:26 pm

Browsing through Amazon’s Top 10 Best Sellers

leave a comment »

This project lets you browse through Amazon’s various product categories and view the top 10 sellers for that category.  You can browse down into sub-categories as well as up into parent categories.

I wrote this to learn about Amazon’s Product Advertising API.  Using the API is simple, especially with the sample code provided by Amazon.  Amazon returns a lot of information, so the slightly tricky part was figuring out how to parse the XML to get only the information I need.

 

Amazon Top Ten Browser

 

Written by M Kapoor

September 10, 2014 at 4:37 pm

RSS Feed Creator with hosting

leave a comment »

Need a way to get your audiobooks, open courseware, videos, or other content onto your podcast player? The RSS Feed Maker will take your URLs and convert them into a RSS document and give you a URL to give to your podcast player.

The RSS feed is created with Argotic and the files are hosted on Amazon’s S3 file hosting service.

 

 

 

 

 

 

 

 

 

 

 

Written by M Kapoor

September 8, 2014 at 11:59 pm