Permalink
Browse files

add cpp and python samples

  • Loading branch information...
1 parent 0d634e4 commit 24873b93803482679636ed11c408d4d221e18e7e @stanfeldman committed Apr 19, 2012
View
1 .gitignore
@@ -12,6 +12,7 @@
# generated files
bin/
gen/
+*.bin
# Local configuration file (sdk path, etc)
local.properties
View
77 cpp/html_parsing.cpp
@@ -0,0 +1,77 @@
+#include <iostream>
+#include <sys/time.h>
+#include <sstream>
+#include <string>
+#include <curl/curl.h>
+#include <libxml/tree.h>
+#include <libxml/parser.h>
+#include <libxml/HTMLparser.h>
+#include <libxml/xpath.h>
+#include <libxml/xpathInternals.h>
+using namespace std;
+
+double GetCurrentTime()
+{
+ struct timezone tz;
+ struct timeval t;
+ gettimeofday(&t, &tz) ;
+ return double(t.tv_sec*1000) + double( t.tv_usec ) / 1000.0;
+}
+
+size_t write_data(char* ptr, size_t size, size_t nmemb, void* userdata)
+{
+ ostringstream* stream = (ostringstream*)userdata;
+ size_t count = size * nmemb;
+ stream->write(ptr, count);
+ return count;
+}
+
+void printXPathNodes(xmlNodeSetPtr nodes)
+{
+ cout << "nodes count: " << nodes->nodeNr << endl;
+}
+
+void parseHtml(string html)
+{
+ xmlInitParser();
+ xmlDocPtr doc = htmlReadMemory(html.c_str(), html.size(), "html", NULL,
+ HTML_PARSE_RECOVER|HTML_PARSE_NOERROR|HTML_PARSE_NOWARNING);
+ xmlNode* root = xmlDocGetRootElement(doc);
+ cout << root->name << endl;
+ cout << "analyzing html..." << endl;
+ xmlXPathContextPtr xPathCtx = xmlXPathNewContext(doc);
+ xmlXPathObjectPtr xPathObj = xmlXPathEvalExpression(BAD_CAST "a.question-hyperlink", xPathCtx);
+ printXPathNodes(xPathObj->nodesetval);
+ xmlXPathFreeObject(xPathObj);
+ xmlXPathFreeContext(xPathCtx);
+ xmlFreeDoc(doc);
+ xmlCleanupParser();
+}
+
+int main()
+{
+ double start_time = GetCurrentTime();
+ CURL* curl = curl_easy_init();
+ if(!curl)
+ return 1;
+ char errorBuffer[CURL_ERROR_SIZE];
+ curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer);
+ curl_easy_setopt(curl, CURLOPT_URL, "stackoverflow.com");
+ //curl_easy_setopt(curl, CURLOPT_HEADER, 1);
+ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
+ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
+ ostringstream stream;
+ curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream);
+ CURLcode res = curl_easy_perform(curl);
+ if(res != CURLE_OK)
+ {
+ cout << errorBuffer << endl;
+ return 1;
+ }
+ string s = stream.str();
+ //cout << s << endl;
+ parseHtml(s);
+ curl_easy_cleanup(curl);
+ cout << "prog duration: " << GetCurrentTime() - start_time << " ms" << endl;
+ return 0;
+}
View
50 cpp/templates.cpp
@@ -0,0 +1,50 @@
+#include <iostream>
+#include <vector>
+#include <stdexcept>
+
+template<typename T>
+T const& max(T const& a, T const& b)
+{
+ return a < b ? b : a;
+}
+
+template<>
+double const& max(double const& a, double const& b)
+{
+ std::cout << "double max" << std::endl;
+ return a < b ? b : a;
+}
+
+template<typename T, typename Contaner=std::vector<T> >
+class Stack
+{
+ public:
+ void push(T item);
+ T pop();
+ private:
+ Contaner items;
+};
+template<typename T, typename Contaner>
+void Stack<T, Contaner>::push(T item)
+{
+ items.push_back(item);
+}
+template<typename T, typename Contaner>
+T Stack<T, Contaner>::pop()
+{
+ if(items.empty())
+ throw std::out_of_range("empty stack");
+ T item = items.back();
+ items.pop_back();
+ return item;
+}
+
+int main()
+{
+ std::cout << max(4,5) << std::endl;
+ std::cout << max(4.0,3.1) << std::endl;
+ Stack<int> s = Stack<int>();
+ s.push(1); s.push(2);
+ std::cout << s.pop() << ";" << s.pop() << std::endl;
+ return 0;
+}
View
9 d/html_parsing.d
@@ -0,0 +1,9 @@
+import std.stdio;
+import std.net.curl;
+import std.string;
+
+void main()
+{
+ auto content = get("dlang.org");
+ writeln(content);
+}
View
14 groovy/first.groovy
@@ -0,0 +1,14 @@
+class Greet
+{
+ Greet(who) { name = who }
+
+ def hello()
+ {
+ println "Hello, $name"
+ }
+
+ def name
+}
+
+g = new Greet("Stas")
+g.hello()
View
10 html/drawing.html
@@ -0,0 +1,10 @@
+<html>
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Drawing</title>
+ <script type="text/javascript" src="https://raw.github.com/mitsuhiko/classy/1.4/classy.js"></script>
+ <script type="text/javascript" src="drawing.js"></script>
+ </head>
+ <body>
+ </body>
+</html>
View
51 html/drawing.js
@@ -0,0 +1,51 @@
+window.requestAnimationFrame = (function()
+{
+ return window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ window.oRequestAnimationFrame ||
+ window.msRequestAnimationFrame ||
+ function(callback, element){
+ window.setTimeout(callback, 1000 / 60);
+ };
+})();
+
+window.onload = function()
+{
+ var canvas = document.createElement("canvas");
+ if(!canvas || !canvas.getContext)
+ return;
+ canvas.width = 500;
+ canvas.height = 500;
+ document.body.appendChild( canvas );
+ var context = canvas.getContext("2d");
+ var img = new Image();
+ img.src = "img.png";
+ img.onload = function()
+ {
+ context.img = img;
+ (function animloop(){
+ draw(context);
+ requestAnimationFrame(animloop, context);
+ })();
+ };
+};
+
+function draw(context)
+{
+ context.fillStyle = "#ffffaa";
+ context.fillRect(0, 0, 500, 300);
+ context.fillStyle = "#000000";
+ context.font = "20px _sans";
+ context.fillText("hello world", 195, 80);
+ context.drawImage(context.img, 50, 80);
+ var time = new Date().getTime() * 0.002;
+ var x = Math.sin( time ) * 96 + 128;
+ var y = Math.cos( time * 0.9 ) * 96 + 128;
+ context.fillStyle = 'rgb(255,0,0)';
+ context.beginPath();
+ context.arc( x, y, 10, 0, Math.PI * 2, true );
+ context.closePath();
+ context.fill();
+}
+
View
BIN html/img.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
10 html/modules_sample/page.html
@@ -0,0 +1,10 @@
+<html>
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>Modules</title>
+ <script data-main="scripts/main-built" src="http://requirejs.org/docs/release/1.0.7/minified/require.js"></script>
+ </head>
+ <body>
+ <h1>lala</h1>
+ </body>
+</html>
View
1 html/modules_sample/scripts/main-built.js
@@ -0,0 +1 @@
+define("utils/helper",{from_helper:"hi from helper",func:function(a){return a+555}}),require(["utils/helper"],function(a){console.log(a.from_helper),console.log(a.func(5))}),define("main",function(){})
View
5 html/modules_sample/scripts/main.js
@@ -0,0 +1,5 @@
+require(["utils/helper"], function(helper)
+{
+ console.log(helper.from_helper);
+ console.log(helper.func(5));
+});
View
5 html/modules_sample/scripts/utils/helper.js
@@ -0,0 +1,5 @@
+define(
+{
+ from_helper: "hi from helper",
+ func: function(x) { return x+555; }
+});
View
7 java/jbox2d_sample/.classpath
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry kind="lib" path="libs/JBox2D-2.0.1.jar"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
View
17 java/jbox2d_sample/.project
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>jbox2d_sample</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
View
BIN java/jbox2d_sample/libs/JBox2D-2.0.1.jar
Binary file not shown.
View
16 java/jbox2d_sample/src/feldman/samples/java/Main.java
@@ -0,0 +1,16 @@
+package feldman.samples.java;
+
+public class Main
+{
+ public static void main(String[] args)
+ {
+ PhysicsWorld world = new PhysicsWorld();
+ for(int i = 0; i < 5; ++i)
+ world.addRandom();
+ float fps = (float)60;
+ float timestep = 1/fps;
+ int iterations = 500;
+ for(int j = 0; j < 10; ++j)
+ world.update(timestep, iterations);
+ }
+}
View
60 java/jbox2d_sample/src/feldman/samples/java/PhysicsWorld.java
@@ -0,0 +1,60 @@
+package feldman.samples.java;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Random;
+
+import org.jbox2d.collision.AABB;
+import org.jbox2d.collision.shapes.CircleDef;
+import org.jbox2d.common.Vec2;
+import org.jbox2d.dynamics.Body;
+import org.jbox2d.dynamics.BodyDef;
+import org.jbox2d.dynamics.World;
+
+public class PhysicsWorld extends ArrayList<Body>
+{
+ public PhysicsWorld()
+ {
+ super();
+ AABB aabb = new AABB();
+ aabb.lowerBound.set((float)100.0, (float)100.0);
+ aabb.upperBound.set((float)-100.0, (float)-100.0);
+ Vec2 gravity = new Vec2((float)0.0, (float)-10.0);
+ world = new World(aabb, gravity, true);
+ }
+
+ public void addRandom()
+ {
+ BodyDef bd = new BodyDef();
+ bd.position.set(random.nextFloat()*100, random.nextFloat()*100);
+ Body body = world.createBody(bd);
+ CircleDef cd = new CircleDef();
+ cd.radius = (float)1.8;
+ cd.density = (float)1.0;
+ body.createShape(cd);
+ body.setMassFromShapes();
+ add(body);
+ }
+
+ public void update(float timestep, int iterations)
+ {
+ world.step(timestep, iterations);
+ draw();
+ }
+
+ public void draw()
+ {
+ Iterator<Body> it = iterator();
+ System.out.println("next step");
+ while(it.hasNext())
+ {
+ Body body = it.next();
+ Vec2 position = body.getPosition();
+ float angle = body.getAngle();
+ System.out.format("x: %f, y: %f, angle: %f\n", position.x, position.y, angle);
+ }
+ }
+
+ private Random random = new Random();
+ private World world;
+}
View
48 python/fsm.py
@@ -0,0 +1,48 @@
+from time import time
+
+edges = { (1,"a"): 2, (2,"a"): 2, (2,"1"): 3, (3,"1"):3 }
+accepting = [3]
+
+def fsmsim(input, current, edges, accepting):
+ if not input:
+ return current in accepting
+ else:
+ letter = input[0]
+ #for k, v in edges.items():
+ # if k[1] == letter:
+ # return fsmsim(input[1:], v, edges, accepting)
+ if (current, letter) in edges:
+ return fsmsim(input[1:], edges[(current, letter)], edges, accepting)
+ return False
+
+#start_time = time()
+#print fsmsim("aaa111", 1, edges, accepting)
+#print "time: %s ms" % ((time()-start_time)*1000)
+
+edges = { (1, 'a') : [2, 3],
+ (2, 'a') : [2],
+ (3, 'b') : [4, 3],
+ (4, 'c') : [5] }
+accepting = [2, 5]
+
+def nfsmsim(string, current, edges, accepting):
+ if not string:
+ return current in accepting
+ else:
+ letter = string[0]
+ if (current, letter) in edges:
+ nexts = edges[(current, letter)]
+ if not isinstance(nexts, list):
+ return fsmsim(input[1:], nexts, edges, accepting)
+ else:
+ for next in nexts:
+ result = nfsmsim(string[1:], next, edges, accepting)
+ if result:
+ return result
+ return False
+
+print "Test case 1 passed: " + str(nfsmsim("abc", 1, edges, accepting) == True)
+print "Test case 2 passed: " + str(nfsmsim("aaa", 1, edges, accepting) == True)
+print "Test case 3 passed: " + str(nfsmsim("abbbc", 1, edges, accepting) == True)
+print "Test case 4 passed: " + str(nfsmsim("aabc", 1, edges, accepting) == False)
+print "Test case 5 passed: " + str(nfsmsim("", 1, edges, accepting) == False)
View
38 python/nlp1.py
@@ -0,0 +1,38 @@
+import nltk
+from time import time
+from urllib2 import urlopen
+
+raw = """
+The Project Gutenberg EBook of Crime and Punishment, by Fyodor Dostoevsky
+This eBook is for the use of anyone anywhere at no cost and with
+almost no restrictions whatsoever. You may copy it, give it away or
+re-use it under the terms of the Project Gutenberg License included, price
+"""
+tokens = nltk.word_tokenize(raw)
+text = nltk.Text(tokens)
+print text.collocations()
+print text.concordance("give")
+print text.similar("cost")
+
+def edit_distance(a, b):
+ n, m = len(a), len(b)
+ if n > m:
+ a, b = b, a
+ n, m = m, n
+ prev_row = xrange(m+1)
+ for i, c1 in enumerate(a):
+ curr_row = [i+1]
+ for j, c2 in enumerate(b):
+ i = prev_row[j+1]+1
+ d = curr_row[j]+1
+ s = prev_row[j] + (c1 != c2)
+ curr_row.append(min(i, d, s))
+ prev_row = curr_row
+ return prev_row[n]
+
+start_time = time()
+print nltk.metrics.edit_distance("Levenshtein", "Lenvinsten")
+print "nltk edit_distance: %s ms" % ((time()-start_time)*1000)
+start_time = time()
+print edit_distance("Levenshtein", "Lenvinsten")
+print "my edit_distance: %s ms" % ((time()-start_time)*1000)
View
7 scala/First.scala
@@ -0,0 +1,7 @@
+object First
+{
+ def main(args : Array[String])
+ {
+ println("hi from Scala!")
+ }
+}

0 comments on commit 24873b9

Please sign in to comment.