Archive for September 2014

Validating a XML against XSD schema in C#

leave a comment »


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


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;

            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 |

            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:

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:

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

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


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 = ''


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.


url: URL to access i.e.
auth_key: Authorization key from DO.

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) {
    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#.


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))
                getFiles(d, sExtension, files);
            return files;

Starting Source:

Written by M Kapoor

September 22, 2014 at 3:28 pm

Posted in c#