Who is talking?


almost 4 years ago | Sumit Bajaj: Sumit Bajaj's Blogs

Brightcove video event handling is way to capture the video events and perform some operations on occurrence of that event.AlertNote: Brightcove API services does not work on local environment (for example: direct browsing of page) so you have to host the website on IIS.Here are the steps to include video on page and capture the events and perform some action on event occurrence.Open any HTML page and write the mentioned javascript code in head section.Javascript Section<script type="text/javascript">         var player;         var modVP;         var modExp;         var modCon;                  function myTemplateLoaded(experienceID) {                          player = brightcove.api.getExperience(experienceID);             modVP = player.getModule(brightcove.api.modules.APIModules.VIDEO_PLAYER);             modExp = player.getModule(brightcove.api.modules.APIModules.EXPERIENCE);             modCon = player.getModule(brightcove.api.modules.APIModules.CONTENT);             modExp.addEventListener(brightcove.api.events.ExperienceEvent.TEMPLATE_READY, onTemplateReady);         }         function onTemplateReady(evt) {                      modVP.addEventListener(brightcove.api.events.MediaEvent.BEGIN, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.CHANGE, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.COMPLETE, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.ERROR, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.PLAY, onMediaEventFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.PROGRESS, onMediaProgressFired);             modVP.addEventListener(brightcove.api.events.MediaEvent.STOP, onMediaEventFired);         }         function onMediaEventFired(evt) {             alert(evt.type);             if (evt.type === brightcove.api.events.MediaEvent.BEGIN) {                 alert('Here Video Begins!!');             }         }    </script>Body Section<div style="display: none"></div>    <script language="JavaScript" type="text/javascript"src="http://admin.brightcove.com/js/BrightcoveExperiences.js">            </script>    <object id="myExperience2128824061001"class="BrightcoveExperience">        <param name="bgcolor" value="#FFFFFF" />        <param name="width" value="480" />        <param name="height" value="270" />        <param name="playerID" value="PLAYED_ID" />        <param name="playerKey" value="AQ~~,AAABywrPJyk~,MP34hwWOTrN8Z6UocoZHuAZdr8inViSF"/>        <param name="isVid" value="true" />        <param name="isUI" value="true" />        <param name="dynamicStreaming"value="true" />                <!-- smart player api params -->        <param name="includeAPI" value="true" />        <param name="templateLoadHandler"value="Test" />        <param name="templateLoadHandler"value="myTemplateLoaded" />        <param name="templateReadyHandler"value="onTemplateReady" />        <param name="@videoPlayer" value="VIDEO_ID" />    </object>

Ditch jsFiddle - Codepen is awesome

almost 4 years ago | Shadab Ahmed: Shadab's Blog

If you like jsFiddle then you should definitely try Codepen. I am now a Codepen convert for the reasons listed. Reasons why Codepen is better than jsFiddle The most awesome feature on Codepen is live update . No need to save and reload unlike jsFiddle Another awesome feature on Codepen - Compiled preview for both CoffeScript and SCSS. See below: Codepen Preview More options for markup, apart from HTML HTML Options Codepen Fully SCSS compliant. jsFiddle fails to compile SCSS when I added this: .arrow::after{ content: ">"; } Complete error description for SCSS unlike jsFiddle, which silently fails and you have to dig with your browser inspector tool. jsFiddle SCSS Error jsFiddle Error - Silently renders scss as css and just adds an error message in the beginning of the file Codepen SCSS Error Codepen Error - Matching line number and error description For CoffeeScript, Codepen shows you a similar error banner like the scss error but does not show any details. This is atleast better than jsFiddle which fails silently The UI is your preference, but I had no problems switching from jsFiddle to Codepen. Cool Codepens This is a simulator I created for the problem: N Rumors There are n people, each in possession of a different rumor. They want to share the news with each other by sending electronic messages. What is the minimum number of messages they need to send to guarantee that everyone of them gets all the rumors? Assume that a sender includes all the rumors he or she knows at the time the message is sent and that a message may only have one addressee. Each cell in the simulator has the person number in blue and number of rumors with the person in green. If a person is sending out a message his cell becomes pink and the cells for people receiving the message are green. Full code here. Works in Chrome and Firefox. Check out this Pen! Much more impressive codepens: Falling Leaves Tearable Fabric Wall Clock You will find many more cool codepens on their homepage. Happy Codepenning :)

Lean Lego and Hacked Tables

almost 4 years ago | Sven Kräuter: makingthingshappen blog.

We are in the middle of an energetic scene: groups of two are presenting each other prototyped solutions for problems you can have when planning a vacation. Concentrated listening, questions and answers. Feedback loop in full effect. But how could it come to this? sketching the prototype The power of the back of the napkin (Photo by @cuxdu) Like many good stories it all begins with a cliché<!-- more -->: agile conference, evening get together at the bar, two agilists, one napkin and a pen. While discussing the similarities between one core principle of strategicplay and the product development approach of the accelerated feedback loop it became obvious to us that the creative problem solving approach of “diverge & converge” approach is also part of the quantifeid learning when applying lean startup techniques. All of a sudden Katrin aka @cuxdu stated that we should prototype a workshop around the idea of, well, rapid prototyping. Assisted by strategic play. We sketched the topics that had to be covered and a rough timeline. Could probably work, let’s see if we still like the idea tomorrow morning before Play 4 Agile’s session planning. Which we did, so there we are right in the middle of a group of people that is really amazing to facilitate. Find problems, let your partner group pick one to solve. Prototype a solution, get feedback by showing it to your target group on the other side of the table. Ditch your solution strategy because it didn’t work or enhance the solution that hit a nerve to make it even more appealing. Pivot or persevere. Rinse and repeat. Prototyping with Lego or Paper & Pencil - anything goes. Amazingly we see almost all theoretic arguments in favor of rapid prototyping happening in the workshop: failing fast saves you budget - in this case time - to adapt to the misunderstood customer demand. If you pleased your customer with your solution you start working on putting smiles on their faces by continuing to steer in the direction you chose. The build-measure-learn loops are accelerated by the decreasing timebox sizes Katrin & me set. One pair of groups even accellerates beyond these boundaries by having several increments in a single timebox - quite astonishing! I think I will offer this workshop at the next open space I participate in to iterate it a little. One success factor here is the mix of people: agilists have the matching feedback and failure culture by default. Another one is the amazing atmosphere at the conference itself that just inspires you. Perhaps the amazing results we saw were caused by the opening day’s facilitation technique to get everyboy’s mind in a creative state: three people putting some stress on the left and right brain half for 20 seconds until you reached a state of an open mind indicated by glowing eyes. I think I was yelled at for a little longer by the way ;-). The same observation could be made at the hacktable we organized. It’s an open format where you meet and bring things or topics with you that you want to hack on in a group. Hacktable with Raspberry Pi & Lego case. Coincidence? Our friends at humanist lab hosted the event - we provided hacked tables out of spare desk materials for the hacktable which is quite poetic I guess ;-). The result were the same glowing eyes I saw after the brain massage at the beginning of Play 4 Agile. Shining eyes & open minds - post hacktable talks. What does this mean for the mentioned workshop? I’ll continue working on it in surroundings where the eyes start glowing on their own like a hacktable or an open space unconference. Our agile colleagues at ScrumCenter are using the format via a Creative Commons (CC-BY-SA) license for their lean startup product owner certification and as you may imagine I am more than curious about their experience. In addition I want to let the format prove itself in not so matching surroundings where the mindset of the people perhaps isn’t too much biased towards an open failure and feedback culture to see how much work is to put in getting people into the mood for an accelerated feedback loop. If you are interested in hosting this workshop yourself or with my facilitation go ahead and get in touch. I’m curious how the idea will develop and try to keep you posted!

How Clojure Babies are Made: Leiningen's Trampoline

almost 4 years ago | Daniel Higginbotham: Flying Machine Studios

In the last "How Clojure Babies are Made" article I hinted that Leiningen avoids waste by using a trampoline. In this installment of this awkwardly-named Clojure series, you'll learn what the trampoline does and how it does it. The Rationale Behind the Trampoline I know what you're thinking, wise-hearted reader. "Why would anyone need to provide a rationale for a trampoline? That's like trying to give a reason for rainbows, or a newborn's laughter, or Michael Jackson's Thriller." Allow me to explain myself. lein trampoline does indeed give you a feeling of weightless freedom, just not in the way that you're used to. See, whenever you use Leiningen to run code from your project, you end up with two Java processes running. Each process loads a separate instance of the JVM. We saw this in the previous article in the output of ps | grep lein. The first process is for Leiningen itself, and it's responsible for setting up everything necessary for your project code to run. The second process is where your code actually executes. If you were to run lein -h, you would only start one Java process, as none of your project code would need to be executed. Leiningen starts a separate process for your project in order to enforce isolation. This is because Leiningen is a true gentleman who does not allow his namespaces and dependencies (like, say, a completely different version of Clojure) to interfere with your meticulously hand-crafted, artisinal program. However, like a doting father, the Leiningen process continues to stay open for the entire duration of your program's execution. If you have a long-running process, like a web server for your Justin Bieber fan site, then Leiningen stays open the whole time consuming memory that could be put to use in compositing images of the Biebs with hearts all over them. This is where the trampoline comes into play. It allows the Leiningen process to exit completely before your project's process starts. Now, instead of two JVM's running, you only have one. I think the name "trampoline" was chosen to evoke an image of Leiningen providing a launching point for your program. However, I choose to envision the trampoline process as follows: Leiningen takes your program, which is embodied as one of those cymbal-clanging monkeys with unsettling eyes, and winds it up. Leiningen gingerly places the wind-up monkey which is your program on the floor of a cozy Hobbit hole. Leiningen steps outside and mounts a gigantic trampoline in Bilbo's front yard. Leiningen takes two warm-up bounces and then, with a mighty "Hyup!", rockets himself into the sky, his mustaches flapping in the wind. He grows smaller and smaller until, with a bright sparkle, he disappears entirely. Your cymbal-clanging web server starts up, allowing users to profess their undying love for teenage pop stars. How lein trampoline Works Though you don't really need to understand how lein trampoline works in order to use it, I think it's pretty cool. Below I walk you through it step by step, with relevant code. We'll be using the project under leiningen/lein-build of the make-a-clojure-baby github repo. Run lein trampoline run from the command line. If you're on a linux machine, this executes a bash script. This script is probably at ~/bin/lein on your system. The bash script sets the TRAMPOLINE_FILE environment variable to a path. Later in this process, Leiningen will write a command to this file. Here's the part of the script that sets the environment variable: if ([ "$LEIN_FAST_TRAMPOLINE" != "" ] || [ -r .lein-fast-trampoline ]) && [ -r project.clj ]; then INPUTS="$@ $(cat project.clj) $LEIN_VERSION $(cat "$LEIN_HOME/profiles.clj")" INPUT_CHECKSUM=$(echo $INPUTS | shasum - | cut -f 1 -d " ") # Just don't change :target-path in project.clj, mkay? TRAMPOLINE_FILE="target/trampolines/$INPUT_CHECKSUM" else TRAMPOLINE_FILE="/tmp/lein-trampoline-$$" trap "rm -f $TRAMPOLINE_FILE" EXIT fi The first Java process starts: /usr/bin/java \ -client -XX:+TieredCompilation \ -Xbootclasspath/a:/Users/daniel/.lein/self-installs/leiningen-2.0.0-standalone.jar \ -Dfile.encoding=UTF-8 \ -Dmaven.wagon.http.ssl.easy=false \ -Dleiningen.original.pwd=/Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build \ -Dleiningen.script=/Users/daniel/bin/lein \ -classpath :/Users/daniel/.lein/self-installs/leiningen-2.0.0-standalone.jar \ clojure.main \ `# clojure.main is the entry point` \ -m leiningen.core.main \ trampoline run 1 This causes Java to execute the -main method in clojure.main, which in turn loads leiningen.core.main and executes its -main function. leiningen.core.main/-main applies the trampoline task: (defn ^:higher-order trampoline "Run a task without nesting the project's JVM inside Leiningen's. Calculates the Clojure code to run in the project's process for the given task and allows Leiningen's own JVM process to exit before running it rather than launching a subprocess of Leiningen's JVM. Use this to save memory or to work around stdin issues." [project task-name & args] (when (= :leiningen (:eval-in project)) (main/info "Warning: trampoline has no effect with :eval-in-leiningen.")) (binding [*trampoline?* true] (main/apply-task (main/lookup-alias task-name project) (-> (assoc project :eval-in :trampoline) (vary-meta update-in [:without-profiles] assoc :eval-in :trampoline)) args)) (if (seq @eval/trampoline-forms) (write-trampoline project @eval/trampoline-forms @eval/trampoline-profiles) (main/abort task-name "did not run any project code for trampolining."))) trampoline calls leiningen.core.main/apply-task but with a twist: it passes that function an updated project configuration, setting :eval-in to :trampoline. You can see this is the snippet above. Eventually, leiningen.core.eval/eval-in-project gets applied. The cool thing about this function is that it then calls leiningen.core.eval/eval-in, which is a multi-method. It has different definitions for :subprocess, :trampoline, :nrepl, and a few more. This is one of the first times I've seen defmethod "in the wild" and it really tickled my pfeffernuesse. Definitely check it out on github. Since we updated our project configuration in the last step so that :eval-in is :trampoline, the :trampoline method gets matched: (defmethod eval-in :trampoline [project form] (swap! trampoline-forms conj form) (swap! trampoline-profiles conj (select-keys project [:dependencies :source-paths :resource-paths :test-paths]))) This updates the trampoline-forms and trampoline-profiles atoms within the leiningen.core.eval namespace. The trampoline function shown in step 5 above continues executing: (if (seq @eval/trampoline-forms) (write-trampoline project @eval/trampoline-forms @eval/trampoline-profiles) (main/abort task-name "did not run any project code for trampolining."))) write-trampoline writes out the entire Java command necessary to finally run our project's main function. It writes this command to the path in the TRAMPOLINE_FILE environment variable set by the bash script in step 2 above. The Leiningen process exits and the bash process from step 2 continues. It checks for the existence of TRAMPOLINE_FILE, and since it exists, it essentially evaluates the command in it, kicking off the Java process which will run your code: if [ -r "$TRAMPOLINE_FILE" ] && [ "$LEIN_TRAMPOLINE_WARMUP" = "" ]; then TRAMPOLINE="$(cat $TRAMPOLINE_FILE)" if [ "$INPUT_CHECKSUM" = "" ]; then rm $TRAMPOLINE_FILE fi exec sh -c "exec $TRAMPOLINE" else exit $EXIT_CODE fi It's a bit of circuitous route, but Leiningen is not one to shy away from hard work! The End I hope you found this article interesting! The following topics are next on my list of things to write about: How Leiningen manages dependencies How to distribute a full application How to distribute a library So long for now, and may the lambda be with you!

USP/Points of differentiation : Quikr vs OLX – Any one ?

almost 4 years ago | Niraj Bhandari: Technology Product Management

I got thinking about the Quikr and OLX the other day after watching their TV Commercials (TVC) back to back. …Continue reading →

Integrating Rails and Node.js via Redis

almost 4 years ago | Rocky Jaiswal: Still Learning

It’s been a while since I blogged, not really for the lack of content but rather the lack of time. I travelled to beautiful Berlin in Jan-Feb and was also doing the Coursera course https://www.coursera.org/course/algo which pretty much ate up all my...

Notice - Ember Generated vs Hand-made Controllers

almost 4 years ago | Eduard Moldovan: eduardmoldovan.com - tech

Today I found another good thing I did not know about. Which actually feels obvious now, but it did not before I experienced it.

How Clojure Babies Are Made: Understanding lein run

almost 4 years ago | Daniel Higginbotham: Flying Machine Studios

Leiningen reminds me a lot of Major Alex Louis Armstrong from Fullmetal Alchemist: What artistry! They are both manly They are both artistic Sometimes you don't know what the f* they're saying (but it's amazing anyway) Mustaches Sparkles Though the Strong Arm Alchemist will forever remain inscrutable, we do have some hope in understanding Leiningen better. In this post, we'll peek under Leiningen's lederhosen so that we can begin to learn precisely what it does and how to make effective use of it in developing, testing, running, and deploying Clojure applications. Here's what we'll learn: How to build and run a Clojure program without Leiningen What happens when you run lein run Basic Leiningen architecture What happens when you run a Leiningen task In the next post, we'll learn: How Leiningen avoids waste with a trampoline How Leiningen manages dependencies How to distribute a full application How to distribute a library Other stuff Leiningen does This post builds on How Clojure Babies Are Made: Compiling and Running a Java Program, so make sure you understand everything in that post first. It doesn't have any pictures of sparkly, sensitive, muscle-bound men though so if that's what you're hoping for you're out of luck. We're here to learn Clojure, dammit, not ogle cartoons! Brief Overview of Leiningen Leiningen is the Swiss Army Bazooka of Clojure development. It handles: Project compilation. Your Clojure has to get converted into Java bytecode somehow, and Leiningen automates the process. Dependency management. Similar to Ruby's bundler and gemfiles, Leiningen automates the process of resolving and downloading the Java jars your project depends on Running tasks. Superficially similar to Ruby's Rake, except that Rake is not very declarative. This could have its own blog post. Deployment. Helps with creating Java jars which can be executed and/or incorporated in other projects. Similar to Ruby gems. How to Build and Run a Clojure Program Without Leiningen By understanding how to build and run a Clojure program manually, you'll better understand what Leiningen does to automate the process. We'll be working with the files under leiningen/manual-build which you can get from the make a clojure baby repo. All path references will be relative to make-a-clojure-baby/leiningen/manual-build. The program we're compiling will make us fluent in the ways of German Love: (ns learn-a-language.important-phrases (:gen-class)) ;; It's time for some German love! (def german [["I love you." "Ich liebe dich."] ["You make me so happy!" "Du machst mich so glucklich!"] ["I miss you." "Ich vermisse dich./Du fehlst mir."] ["Pass me the mustard." "Gib mir den Senf."] ["Kiss me!" "Kuss mich!"]]) (defn -main [which] (let [phrases (get german (Integer. which))] (println "English: " (first phrases)) (println "German: " (second phrases)))) One important thing to note here is that we included the :gen-class directive in the ns declaration. This tells Clojure to generate a named Java class when it compiles the namespace. Remember that Java requires a public main method within a public class to serve as the entry point for the JVM. Using :gen-class allows us to use learn-a-language.important-phrases/-main as the entry point. Let's go ahead and compile. First, start up a Clojure repl (note that the git repo includes the 1.5.1 release of Clojure as clojure.jar): java -cp .:clojure.jar clojure.main Notice that we specifed the classpath with -cp .:clojure.jar. This does two things: It allows us to execute the main method in clojure.main similarly to what we saw at the end of the last post It adds the current directory to the classpath so that when you actually start loading Clojure files and compiling namespaces, the Clojure repl can find them. To see what I mean, try starting the repl with java -jar clojure.jar and then running the code below. You should now have a Clojure repl running in your terminal. Copy and paste the following lines into it: (load "learn_a_language/important_phrases") (compile 'learn-a-language.important-phrases) The first line reads the specified file. The second actually compiles the learn-a-language.important-phrases namespace, generating a boatload of Java class files in the classes/learn_a_language directory: $ ls classes/learn_a_language/ important_phrases$_main.class important_phrases$fn__19.class important_phrases$fn__48.class important_phrases$loading__4910__auto__.class important_phrases.class important_phrases__init.class (I won't go into into detail about the purposes of the various class files, but you can start to learn more about that in clojure's compilation documentation.) After going through the above steps, you might have a question on your mind grapes: "Where did the classes directory come from?" Oh, gentle-hearted reader. Your dedication to learning has touched my heart. I shall answer your query: Clojure places compiled files under *compile-path*, which is classes by default. Therefore, classes must exist and be accessible from the classpath. You'll notice that there's a classes directory in the git repo with a .gitkeep file in it. Never change, dear, inquisitive reader. Never! Now that we've compiled our Clojure program, let's get it running: # Notice that you have to provide a numerical argument $ java -cp classes:clojure.jar learn_a_language/important_phrases 0 English: I love you. German: Ich liebe dich. $ java -cp classes:clojure.jar learn_a_language/important_phrases 3 English: Pass me the mustard. German: Gib mir den Senf. Success! You are now ready to express your love for Leiningen in its native tongue. I highly recommend you use this program to come up with tweets to send to @technomancy to express your appreciation. But before you do that, notice the classpath. We need to include both the classes directory, because that's where the learn_a_language/important_phrases class files live, and clojure.jar, because the class files generated by compile need to be able to access Clojure class files. To sum up: # load clojure repl $ java -cp .:clojure.jar clojure.main # in Clojure repl user=> (load "learn_a_language/important_phrases") user=> (compile 'learn-a-language.important-phrases) # back to command line java -cp classes:clojure.jar learn_a_language/important_phrases 0 I hope this brief foray into the world of manually building and running a Clojure program has been educational. You can see how it would be burdensome to go through his process over and over again while developing a program. Let's finally bring in our pal Leiningen to automate this process. How Leiningen Compiles and Runs a Basic Clojure Program Let's build the "learn a language" program with Leiningen. We have a very basic project at make-a-clojure-baby/leiningen/lein-build. Under that the directory, the file src/learn_a_language/important_phrases.clj is the same as the one listed above. lein run Lein automates the build + run process with lein run. Go ahead and try that now: $ lein run 2 Compiling learn-a-language.important-phrases English: I miss you. German: Ich vermisse dich./Du fehlst mir. You can probably guess what's happening at this point, at least to a degree. Leiningen is compiling important_phrases.clj resulting in a number of Java .class files. We can, in fact, see these class files: $ ls target/classes/learn_a_language important_phrases$_main.class important_phrases$loading__4784__auto__.class important_phrases__init.class Leiningen then somehow constructs a classpath such that both Clojure and the "important phrases" classes are accessible by Java. Finally, the -main function is executed. I know what you're thinking at this point, noble reader. You're thinking that the "somehow" in "somehow constructs a classpath" is a particularly un-manly, un-artistic, un-mustached, un-sparkly word, unbefitting an article on Leiningen. And you are absolutely right. To avoid your wrath, let's dig into Leiningen's source code so that we can understand what's going on with complete clarity. Walking Through "lein run" To get an idea of where to start, let's run lein run 1 again and then run ps | grep lein. The output has been broken up to make more sense (apologies for the goofy highlighting): # you can actually copy and paste the part after the PID to try this # in your terminal 8420 /usr/bin/java \ -client -XX:+TieredCompilation \ -Xbootclasspath/a:/Users/daniel/.lein/self-installs/leiningen-2.0.0-standalone.jar \ -Dfile.encoding=UTF-8 \ -Dmaven.wagon.http.ssl.easy=false \ -Dleiningen.original.pwd=/Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build \ -Dleiningen.script=/Users/daniel/bin/lein \ -classpath :/Users/daniel/.lein/self-installs/leiningen-2.0.0-standalone.jar \ clojure.main \ `# clojure.main is the entry point` \ -m leiningen.core.main \ run 1 8432 /usr/bin/java \ `# your classpath will be different` \ -classpath \ /Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build/test:\ /Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build/src:\ /Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build/dev-resources:\ /Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build/resources:\ /Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build/target/classes:\ /Users/daniel/.m2/repository/org/clojure/clojure/1.5.1/clojure-1.5.1.jar -XX:+TieredCompilation \ -Dclojure.compile.path=/Users/daniel/projects/web_sites/make-a-clojure-baby/leiningen/lein-build/target/classes \ -Dlearn-a-language.version=0.1.0-SNAPSHOT \ -Dfile.encoding=UTF-8 \ -Dclojure.debug=false \ clojure.main \ `# clojure.main is the entry point` \ `# this next part specifies code to be evaluated by Clojure` \ -e (do \ (try \ (clojure.core/require 'learn-a-language.important-phrases) \ (catch java.io.FileNotFoundException ___6081__auto__)) \ (set! *warn-on-reflection* nil) \ (clojure.core/let \ [v__6079__auto__ \ (clojure.core/resolve 'learn-a-language.important-phrases/-main)] \ (if \ (clojure.core/ifn? v__6079__auto__) \ (v__6079__auto__ "1") \ (clojure.lang.Reflector/invokeStaticMethod \ "learn-a-language.important-phrases" \ "main" \ (clojure.core/into-array \ [(clojure.core/into-array java.lang.String '("1"))]))))) There are two things happening here. When you first run lein run, then the process with PID 8420 starts. There are a lot of configuration variables that we don't necessarily need to care about. What's essentially happening is we're saying: Start up the JVM with the leiningen standalone jar on the classpath Use clojure.main as the Java entry point Pass -m leiningen.core.main run 1 as arguments to clojure.main That last step specifies the Clojure entry point, as opposed to the Java entry point. Clojure uses it to load the leiningen.core.main namespace and then execute the -main function within it. leiningen.core.main/-main receives the arguments run 1. We can view Leiningen's leiningen.core.main/-main function on github: (defn -main "Command-line entry point." [& raw-args] (try (user/init) (let [project (project/init-project (if (.exists (io/file "project.clj")) (project/read) (assoc (project/make (:user (user/profiles))) :eval-in :leiningen :prep-tasks []))) [task-name args] (task-args raw-args project)] (when (:min-lein-version project) (verify-min-version project)) (configure-http) (warn-chaining task-name args) (apply-task task-name project args)) (catch Exception e (if (or *debug* (not (:exit-code (ex-data e)))) (.printStackTrace e) (when-not (:suppress-msg (ex-data e)) (println (.getMessage e)))) (exit (:exit-code (ex-data e) 1)))) (exit 0)) Just as we would suspect from the ps output, this is the command line entry point for lein. One of the first things this function does is figure out your project configuration from your project.clj file. Here's ours: (defproject learn-a-language "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.5.1"]] :main learn-a-language.important-phrases) The most important line, for our purposes, is :main learn-a-language.important-phrases This tells Leiningen what function to execute when you run lein run. If you specify a namespace without a function, as we do above, then Leiningen defaults to using the -main function. Next, if you look about 2/3 of the way down in the leiningen.core.main/-main function, you'll see the apply-task function being called. This calls resolve-task which eventually resolves to leiningen.run, which you can also see on github. This is pretty cool — run is just another task from Leiningen's point of view. Wait... did I just say "cool"? I meant MANLY and ARTISTIC and SPARKLY. But yeah, it looks like basic leiningen architecture includes the leiningen.core collection of namespaces, which handle task resolution and application, and plain ol' leiningen, which appears to be mostly a collection of default tasks. Leiningen uses this same mechanism to execute any function in your Clojure project as a task. Bodacious! I recommend checking out the code for the other Leiningen tasks. You'll see how they do more than just require and run a single function, but the task-running infrastructure remains the same. Anyway, once the run task has been resolved, it is executed and the result is the second process we saw in the ps | grep lein output above, the process with PID 8432. A sub-process is created to enforce isolation between Leiningen and your project. I won't go into how the command for the sub-process gets constructed, as you can figure that all out from leiningen/run. What's more important is what it actually does. The command loads Clojure and tells it to evaluate the following: (do (try (clojure.core/require 'learn-a-language.important-phrases) (catch java.io.FileNotFoundException ___6081__auto__)) (set! *warn-on-reflection* nil) (clojure.core/let [v__6079__auto__ (clojure.core/resolve 'learn-a-language.important-phrases/-main)] (if (clojure.core/ifn? v__6079__auto__) (v__6079__auto__ "1") (clojure.lang.Reflector/invokeStaticMethod "learn-a-language.important-phrases" "main" (clojure.core/into-array [(clojure.core/into-array java.lang.String '("1"))]))))) You can see how the end result is that learn-a-language.important-phrases/-main gets executed with the argument "1". One interesting thing to note about this approach is that the :gen-class directive isn't actually needed. In the manual build at the beginning of this article, we needed :gen-class because we were specifying learn-a-language.important-phrases as the JVM entry point. When we use lein run, the entry point is clojure.main. Once Clojure is loaded, we use it to evaluate some code which loads the learn-a-language.important-phrases namespace and then calls the -main function. Wrapping Things Up So now we know how Leiningen compiles and runs a basic Clojure program! Can you feel your mustache growing? Can you feel your artistry blooming? Are you feeling just a smidge more sparklier? I sure hope so! Here's everything we covered: Building and running a Clojure program manually: Load the Clojure repl Load your Clojure code (make sure it includes :gen-class) Compile your Clojure code. By default code gets put in classes directory Run your code, making sure the classpath includes the classes directory and clojure.jar # load clojure repl $ java -cp .:clojure.jar clojure.main # in Clojure repl user=> (load "learn_a_language/important_phrases") user=> (compile 'learn-a-language.important-phrases) # back to command line java -cp classes:clojure.jar learn_a_language/important_phrases 0 Building and running a Clojure program with Leiningen: Run lein run Magic! Start Java with clojure.main as the entry point Execute the leiningen.core/-main function Setup project config with project.clj Resolve the task to be run Run the task Automagically set the classpath Use clojure.main as the Java entry point Construct some Clojure code to evaluate so that the project's main function gets executed. This happens in a sub-process to enforce isolcation from Leiningen. Check out Leiningen's eval-in-project function for more info. In the next article we'll cover: How Leiningen avoids waste with a trampoline How Leiningen manages dependencies How to distribute a full application How to distribute a library Manliness I hope you enjoyed this article. Please do leave me any feedback - I'm always looking for ways to improve my writing!

Puzzle - A surpassing problem

almost 4 years ago | Shadab Ahmed: Shadab's Blog

Another week, another interesting puzzle. This puzzle is taken from a programming exercise posed by Martin Rem in 1988 A Surpassing Problem By definition, a surpasser of an element of an array is a greater element to the right, so x[j] is a surpasser of x[i] if i < j and x[i] < x[j]. The surpasser count of an element is the number of surpassers. For example, the surpasser count of the string GENERATING are given by G E N E R A T I N G 5 6 2 5 1 4 0 I 0 0 The maximum surpasser count is 6. The first occurrence of the letter E has six surpassers, namely N, R, T, I, N, and G. Rem's problem is to compute the maximum surpasser count of an array of length n > 1 and to do so with an O(n log n) algorithm. Click to view my solution Not the most succint solution, but it does match the O(n logn) criteria. Infact I am using the same RangeCountTree used in the last puzzle.Here's what I am doing (assuming word only contains capital letters):1. Start iterating from the reverse of the string. For the current example, you first see a G so insert a range A,G in the tree. The range A,G in the tree would now have count 1. This just means that surpassers count for letters A to F is 1.  Please note that A,G means letters A to F(G is excluded). 2. Now let's build this tree for NERATING. See it below:The representation is such, that for any new character, the corresponding range in the tree would give the count of surpassers.3. Calculate the max_surpassers while building the tree itself. So now when you see E next after NERATING, the matching range for E in the above tree is E,G -> 6. Therefore the current max_surpassers is now 6Let's see how the tree looks for the whole string GENERATING:Now if the string was changed to REGENERATING, you would see that the current tree has E,G -> 7 , so the max surpassers calculated would be 7We could do the same thing for finding max surpassers in a list of numbers, only difference being that we would insert each range as (-Infinity, current_number)Code here:require './range_count_tree' data = "REGENERATING" rtree = RangeCountTree.new max_surpassers = 0 data.reverse.each_char do |char| # Set range_start to A for the min possible range range_start = ?A.ord range_end = char.ord # Find the surpassers for the current character in the current tree current_max_node = rtree.find(range_end) # set max surpassers if current surpassers is larger max_surpassers = current_max_node.count if current_max_node && current_max_node.count > max_surpassers # Do not add this range to the tree, since we will not encounter any characters in this range # This is just an optimization and not necessary next if range_start == range_end # Update the current tree for the next stream of characters rtree.add([range_start, range_end]) end puts "Max surpassers is #{max_surpassers}" I think there is a much better solution which would put my verbose approach to shame with its simplicity

Notice - Remy Sharp created '5 minute fork'

almost 4 years ago | Eduard Moldovan: eduardmoldovan.com - tech

As he puts it "The number of times I've come across a cool demo, only to be faced with a github repo and no live link - it just bums me out" - such a good idea. Obviously, this is suitable mainly for frontend projects.

Notice - Yac, As Yet Another Cache

almost 4 years ago | Eduard Moldovan: eduardmoldovan.com - tech

Yac is a user data cache based on shared memory for PHP. It can be used to replace APC or local memcached.

Notice - Ember.js and the default template action target

almost 4 years ago | Eduard Moldovan: eduardmoldovan.com - tech

Since the newest Ember.js release, I have had trouble determining the default target of an action, in a template.

How Clojure Babies Are Made: Compiling and Running a Java Program

almost 4 years ago | Daniel Higginbotham: Flying Machine Studios

If you’re at all like me, the moment you got your first Clojure program running you belted out, “SOOO MUUUUUUUCH POOOOOOOWEEEEEEEER!” and thrust one or both fists into the air. Then, fifteen minutes later, you found yourself muttering things like “What’s a maven?” and “Classpath what now?” and “What is Leiningen actually doing, anyway? Sure, those are the most handsome mustaches I ever laid eyes on, but can I really trust them?” This post is here to help you out. In it, I will describe how Java compiles and runs programs, and how this relates to Clojure. In an upcoming post, I will also describe how Leiningen makes this process way easier. Here’s an outline of what’s to come: Java Compilation javac Class lookup rules & classpath imports packages JAR files Running Class file classpath Executable JAR Leiningen Running an app without Leiningen classpath management Incorporating Clojure automatically Dependency managemenet (Update: Part 2 of this series is now available!) Java Java is going to rule the universe. The sooner you accept that, the better. If you don’t have the JDK installed installed, you might want to do that now. To check, just try running java and javac in your terminal. By the way - this post assumes you’re somewhat familiar with the terminal. It also assumes you’re familiar with object-oriented programming. Compiling and Running a Basic Program This section will lay a foundation for your understanding of Java. It doesn’t address Clojure directly, but the knowledge you gain will be useful in your Clojuring. Let’s put our game faces on and start with a basic program. Visit the github repo for the examples in this post and clone that baby for all you’re worth. In the folder ShiverMeTimbers, you should find an article named ShiverMeTimbers.java. Here are its contents: public class ShiverMeTimbers { public static void main(String[] args) { System.out.println("Shiver me timbers!!!"); } } Once you’ve recovered from your swoon, cd to ShiverMeTimbers and run javac ShiverMeTimbers.java. If you typed everything correctly and you’re pure of heart, you should now see a file named ShiverMeTimbers.class. $ ls ShiverMeTimbers.class ShiverMeTimbers.java You’ve just compiled your first Java program, son! Now run it with java ShiverMeTimbers. You should see: Shiver me timbers!!! Which I’m pretty sure is like the Lord’s prayer, but for pirates. Anyway, what’s happening here is you used the Java compiler, javac, to create a Java class file, ShiverMeTimbers.class. This file is packed with oodles of Java bytecode which the Java Virtual Machine executes when running a program. When you ran java ShiverMeTimbers, the JVM first looked on your classpath for a class named ShiverMeTimbers. In Java, you’re only allowed to have one public class per file and the filename and class name must be the same. This is how java knows to try looking in ShiverMeTimbers.class for the ShiverMeTimbers class’s bytecode. Also, by default, the classpath includes the directory ., or the current directory. Try running java -classpath /tmp ShiverMeTimbers and you will get an error, even though ShiverMeTimbers.class is right there in the same directory. After java found the bytecode for the ShiverMeTimbers class, it executed that class’s main method. Java’s kind of like C that way, in that whenever you say “run something, and use this class as your entry point”, it always will run that class’s main method. Which means that that method has to be public, as you can see above. (Here’s more info on Java’s access modifiers if you’re curious.) Key Ideas javac compiles java source code to bytecode which the JVM can execute java searches the classpath for the class you specified and executes its main method. That method must be public. In the next section you’ll learn about handling program code that’s spread over more than one file. If you don’t remove your socks now, they’re liable to get knocked off! Packages and Imports In this section, you’ll learn about how Java handles programs which are spread over more than one file. You’ll also learn how to use Java libraries. Once again, we’ll look at both compiling and running a program. This section has direct implications for Clojure programming, so pay attention! Let’s start with a couple definitions: package: Similar to Clojure’s namespaces, packages serve two purposes. They provide code organization, just like clojure namespaces. They also enforce access rules, which we don’t really care about. The directory that a Java file lives in must mirror the package it belongs to. If a file has the line package com.shapemaster in it, then it must be located at com/shapemaster somewhere on your classpath. More about classpath later. import: Java allows you to import classes, which basically means that you can refer to them without using their namespace prefix. So, if you have a class in com.shapemaster named Square, you could write import com.shapemaster.Square; or import com.shapemaster.*; at the top of a .java file so that you can use Square in your code instead of com.shapemaster.Square. Code example below. Now let’s see package and import in action. Here they are as used by the files in make-a-clojure-baby/ContrivedPackageExample. Pay attention to the comments, as they explain a lot of what’s going on Contents of make-a-clojure-baby/ContrivedPackageExample/Conversation.java: public class Conversation { public static void main(String[] args) { // The "ns1" prefix is necessary because ShyGhost belongs to // the "ns1" package, and we haven't imported the classes in // that package ns1.ShyGhost shyGhost = new ns1.ShyGhost(); shyGhost.talk(); } } Contents of make-a-clojure-baby/ContrivedPackageExample/ns1/ShyGhost.java: // The classes defined in this file belong to the "ns1" package. // Notice that this file is in the "ns1" directory. package ns1; // This basically means, "I hate typing the namespace prefix all the // time so please allow me to not do that" import ns2.*; public class ShyGhost { public void talk() { // the shy ghost can't speak for himself and has to get // someone else to do it for him // Notice that even though SuperManlyIguana belongs to the ns2 // namespace, we don't have to use the ns2 prefix SuperManlyIguana smi = new SuperManlyIguana(); smi.talk(); } } Contents of make-a-clojure-baby/ContrivedPackageExample/ns2/SuperManlyIguana.java: // The classes defined in this file belong to the "ns2" package package ns2; public class SuperManlyIguana { public void talk() { System.out.println("Why hello there"); } } You can run all the above code with the following: cd make-a-clojure-baby/ContrivedPackageExample javac Conversation.java java Conversation Can you guess what this outputs? I bet you can! Anyway, so far we’ve established the relationship between importing, packages, and directory structure: Packages organize code and require a matching directory structure. Importing classes allows you to “de-namespace” them. One piece that’s missing, which I alluded to above, is the role of the classpath. Try the following: cd make-a-clojure-baby/ContrivedPackageExample/ns1 javac ../Conversation.java Boom! The Java compiler just told you to hang your head in shame, and maybe weep a little: ../Conversation.java:13: error: package ns1 does not exist ns1.ShyGhost shyGhost = new ns1.ShyGhost(); ^ ../Conversation.java:13: error: package ns1 does not exist ns1.ShyGhost shyGhost = new ns1.ShyGhost(); ^ It thinks that the ns1 package doesn’t exist. But that’s stupid, right? I mean, you’re in the ns1 directory and everything! What’s happening here is that the java compiler is looking for ./ns1/ShyGhost which it can’t find because you’re already in the ns1 directory. This is because the default classpath includes ’.’. Without changing directories, try running javac -classpath ../ ../Conversation.java Et voila! It works! So let’s amend our understanding of the relationship between importing, packages, and the directory structures: when you’re compiling a Java program, Java searches your classpath for packages. Guess what: the same things happens when you’re running a Java program, too. Run the following: cd make-a-clojure-baby/ContrivedPackageExample mkdir hide mv ns1 hide java Conversation Another explosion! Now try: java -classpath .:hide Converstaion Success! I hope this clarifies the relationship between your directory structure, the classpath, packages, and importing. Key Ideas Packages provide a way for you to organize classes. Your directory structure must reflect your package names Imports allow you to be lazy and not prefix a class name with its package javac and java search the classpath for packages JAR Files JAR, or Java ARchive, files allow you to bundle all your .class files into one single file. Run the following: cd make-a-clojure-baby/ContrivedPackageExample jar cvfe contrived.jar Conversation *.class ns*/*.class java -jar contrived.jar It works, just like before. You bundled all the class files into contrived.jar with the file patterns *.class and ns*/*.class. You also indicated that the Conversation class is the “entry point” with the e flag. The “entry point” is the class which contains the main method which should be executed when the JAR as a whole is run. Behind the scenes, java knows which class is the entry point because when you create a jar, the file META-INF/MANIFEST.MF automaticaally gets generated and added. When you add the e flag, the following line gets added: Main-Class: Conversation By the way, you might be wondering why Java isn’t throwing any exceptions like “can’t find package”. The reason is that the JAR file maintains the directory structure. You can see its contents with: jar tf contrived.jar You’ll see that the directory structure is maintained. One final point: a JAR file is really just a Zip file with a “.jar” extension. You can treat it just the same as any other zip file. Pulling it All Together: clojure.jar Let’s pull all of this together with some Clojure! Download the 1.5.1 stable release and unzip it. Then cd to the directory that gets created and run java -jar clojure-1.5.1.jar You should get that most soothing of sights, the Clojure REPL. So, how did it actually start up? Let’s have a look at META-INF/MANIFEST.MF in the jar file: Manifest-Version: 1.0 Archiver-Version: Plexus Archiver Created-By: Apache Maven Built-By: hudson Build-Jdk: 1.6.0_20 Main-Class: clojure.main It looks like clojure.main is specified as the entry point. Where does this class come from? Well, have a look at clojure/main.java on github: /** * Copyright (c) Rich Hickey. All rights reserved. * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file epl-v10.html at the root of this distribution. * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * You must not remove this notice, or any other, from this software. **/ package clojure; import clojure.lang.Symbol; import clojure.lang.Var; import clojure.lang.RT; public class main{ final static private Symbol CLOJURE_MAIN = Symbol.intern("clojure.main"); final static private Var REQUIRE = RT.var("clojure.core", "require"); final static private Var LEGACY_REPL = RT.var("clojure.main", "legacy-repl"); final static private Var LEGACY_SCRIPT = RT.var("clojure.main", "legacy-script"); final static private Var MAIN = RT.var("clojure.main", "main"); public static void legacy_repl(String[] args) { REQUIRE.invoke(CLOJURE_MAIN); LEGACY_REPL.invoke(RT.seq(args)); } public static void legacy_script(String[] args) { REQUIRE.invoke(CLOJURE_MAIN); LEGACY_SCRIPT.invoke(RT.seq(args)); } public static void main(String[] args) { REQUIRE.invoke(CLOJURE_MAIN); MAIN.applyTo(RT.seq(args)); } } As you can see, the class main is defined. It belongs to the package clojure and defines a public static main method. This is all Java needs to run a program. I hope this has helped clarify Java and how it relates to Clojure! In my next post, I’ll dig in to Leiningen. Fun for everybody!!!

Firefox OS And Blackberry 10

almost 4 years ago | Eduard Moldovan: eduardmoldovan.com - tech

Today we had a small gathering organized by Telenor here in Budapest. The topic was mobile devices, operating systems and their security.

RangeCountTree - A BST for range intersections

almost 4 years ago | Shadab Ahmed: Shadab's Blog

Recently I came across an interesting puzzle: An editor of The History of the World of Science wants to find out the time when the largest number of prominent scientists were alive. The prominent scientists are, by definition, the people mentioned > in the book with the dates of their birth and death. (No living scientists are included in the book.) ? Devise an algorithm for this task if it has the book's index as its input. The entries in the index are sorted alphabetically and give the persons' birth and death years. If person A died the same year >person B was born, assume that the former event happened before the latter one. After giving it a bit of thought, I implemented an interesting data structure to solve it like a basic binary search tree. Here it goes: Here's the tree generated for the data in scientists.rb(using graphviz): tree

Notice - vic.js

almost 4 years ago | Eduard Moldovan: eduardmoldovan.com - tech

Vic.js is a permissive validation/correction abstraction available for JavaScript.

Reentrancy error when styling DataGrid with dynamic columns

almost 4 years ago | Jimmy Skowronski: jimmy skowronski

A couple days ago I’ve wrote a short post showing how to create DataGrid with dynamic columns. Since then I was playing with the grid making it looking nicer and one of things I wanted to add was cell background depending on the value. Here is an example DynamicDataGrid3 The idea is pretty simple one, a cell should be red when value is negative and green when positive. If I would have standard DataGrid with set columns I could do set the column template to look like that <sdk:DataGridTemplateColumn HeaderStyle="{StaticResource headerStyle}"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Category}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> <sdk:DataGridTemplateColumn.CellStyle> <Style TargetType="sdk:DataGridCell" BasedOn="{StaticResource cellStyle}"> <Setter Property="Background" Value="{Binding Value, Converter={StaticResource ValueToSolidBrushConverter}}" /> </Style> </sdk:DataGridTemplateColumn.CellStyle> </sdk:DataGridTemplateColumn>   But I couldn’t. Following the code from the previous post my template is set in the code behind and looks like this string cellTemp = string.Format(@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <TextBlock Text=""{{Binding Summary[{0}].Total}}"" /> </DataTemplate>", index); The other option was to wrap the cell in a simple grid and set the background binding as required. I did that string cellTemp = string.Format(@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <Grid Background=""{{Binding Summary[{0}].Value, Mode=OneWay, Converter={{StaticResource ValueToSolidBrushConverter}}}}""> <TextBlock Text=""{{Binding Summary[{0}].Total}}"" /> </Grid> </DataTemplate>", index); After creating a converter, I’ve added it to the page resources and was ready to go. To my surprise I’ve got this reentrancy_error WTF? At this point I was quite perplexed. After wasting serious chunk of time on fruitless searching for an answer I have up and started looking for workaround. After a few runs to eliminate element I figured out that the problem happens when the converter is applied. Finally I’ve decided to cheat and modify the cell style on the fly. Here is the new CreateColumn method private DataGridTemplateColumn CreateColumn(int index, string header) { string cellTemp = string.Format(@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <TextBlock Text=""{{Binding Summary[{0}].Total}}"" /> </DataTemplate>", index); DataGridTemplateColumn column = new DataGridTemplateColumn(); column.Header = header; column.CellTemplate = (DataTemplate)XamlReader.Load(cellTemp); column.HeaderStyle = LayoutRoot.Resources["headerStyle"] as Style; var cellStyle = LayoutRoot.Resources["cellStyle"] as Style; Style style = new Style(cellStyle.TargetType); style.BasedOn = cellStyle; Binding b = new Binding(string.Format("Summary[{0}].Value", index)); b.Mode = BindingMode.OneWay; b.Converter = new ValueToSolidBrushConverter(); style.Setters.Add(new Setter(BackgroundProperty, b)); column.CellStyle = style; return column; } The idea is that I already have have a cell style that is generally applied for each cell. In the code above I’m creating a new style that is based on the existing one, then creating binding using the converter I want, and then suing this new style as a CellStyle. And that works just fine. HTH

Functional Illiteracy In JavaScript

almost 4 years ago | Mark Daggett: Mark Daggett's Blog

When someone cannot read or write in their native language, they are considered functionally illiterate. This level of illiteracy means that they subsist in their daily life through their ability to speak fluently, and recognize certain written keywords. Illiteracy is not a sign of stupidity; in many cases it is the result a lack of opportunity to learn. However, illiteracy does stunt the potential of otherwise bright people. The sad fact is their inability to participate in society through the mastery of language makes them at higher risk of being in poverty and committing crime. Most computer languages are written, not spoken (try speaking JavaScript out loud and you’ll see what I mean). Therefore, being able to write code does not make you literate. Being an illiterate developer means that you skim across the surface of the language, copying snippets of code from others trying cobble, together a working program with little or no understanding of how or why it works. As with illiterates in the wider world, illiterate developers are not unintelligent. Often it means that they didn’t have the luxury of taking a deep dive through the mechanics of the programming language. Many illiterate developers are practicing software professionals, backed into a corner by impending deadlines, or lack of resources. Perhaps they started in other fields such as graphic design, or business and find themselves scurrying along the surface of the language, learning in fits and starts as they go along.

Dynamic columns in the Silverlight DataGrid

almost 4 years ago | Jimmy Skowronski: jimmy skowronski

New job and new things to learn. How cool is that? I’ve been working on a Silverlight page that should display a grid. There is nothing exciting in that except the fact that the grid had to have dynamic columns depending on data that is coming to the grid. Let put some imaginary context into that. Assume you have sale summary to display and you want it to look like that: DynamicDataGrid0 You have rows that represents sale totals per year for various categories and columns for each year you have in your dataset. Those year columns can depend on some selection criteria and can be in any range between now and whenever. So the problem is how to make the DataGrid to display variable number of columns. The data set used in the example is very simple. Here is a single class that holds a category and a list of summary values per year. public class SaleData { public string Category { get; set; } public List<YearSummary> Summary { get; set; } } public class YearSummary { public int Year { get; set; } public double Total { get; set; } } Then, I will use two simple methods to generate some data. Goes without saying that in a real scenario this would be taken from some sort of data source. public static List<SaleData> GetData() { List<SaleData> data = new List<SaleData>(); data.Add(new SaleData() { Category = "Laptop", Summary = GetSummaryData() }); data.Add(new SaleData() { Category = "Tablet", Summary = GetSummaryData() }); data.Add(new SaleData() { Category = "Desktop", Summary = GetSummaryData() }); return data; } private static List<YearSummary> GetSummaryData() { List<YearSummary> data = new List<YearSummary>(); for (int i = 0; i < 5; i++) { var summary = new YearSummary() { Total = rnd.Next(-5000, 10000), Year = 2008 + i }; data.Add(summary); } return data; } Having all things done I can now add the grid to my XAML. The Category column is not changing and appears in each row so I can add it in XAML to make my life a bit easier. Important is to set AutoGenerateColumns property to false as we will take control over what columns will be created. <sdk:DataGrid x:Name="SalesGrid" AutoGenerateColumns="False"> <sdk:DataGrid.Columns> <sdk:DataGridTemplateColumn HeaderStyle="{StaticResource headerStyle}" CellStyle="{StaticResource cellStyle}"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Category}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> </sdk:DataGrid.Columns> </sdk:DataGrid> Dynamic columns for each year will be added in the code behind. Do to so I’ve added a simple method that creates a template column using a string containing XAML and XamlReader. private DataGridTemplateColumn CreateColumn(int index, string header) { string cellTemp = string.Format(@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <TextBlock Text=""{{Binding Summary[{0}].Total}}"" /> </DataTemplate>", index); DataGridTemplateColumn column = new DataGridTemplateColumn(); column.Header = header; column.CellTemplate = (DataTemplate)XamlReader.Load(cellTemp); return column; } This method is called from the page constructor in this way: public MainPage() { InitializeComponent(); var data = GetData(); SalesGrid.ItemsSource = data; var firstRow = data.First(); for (int i = 0; i < firstRow.Summary.Count; i++) { var monthlySummary = firstRow.Summary[i]; SalesGrid.Columns.Add(CreateColumn(i, monthlySummary.Year.ToString())); } } What is actually happening here? The whole point of this method is to get templates for each column and have bindings set right. If I would want to add columns manually in the XAML I would have to add something like that in my sdk:DataGrid.Columns: <sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Summary[0].Total}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Summary[0].Total}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> <!-- ...and so on... --> But because I don’t know in advance how many columns I will have I have to add them runtime. As you see the idea is really trivial here. I can design the whole template in Blend, make it perfect, set whatever styles I want and then just copy the whole thing to the code behind. Make it nice please So, to show how to apply styles, I’ve added two styles in my RootLayout grid just to show you the point: <Grid.Resources> <Converters:ColorToSolidBrushConverter x:Key="ColorToSolidBrushConverter"/> <Style x:Name="cellStyle" TargetType="sdk:DataGridCell"> <Setter Property="Padding" Value="5" /> </Style> <Style x:Name="headerStyle" TargetType="sdk:DataGridColumnHeader"> <Setter Property="Padding" Value="5" /> </Style> </Grid.Resources> Then I applied those styles to the category column I have in my XAML: <sdk:DataGridTemplateColumn HeaderStyle="{StaticResource headerStyle}" CellStyle="{StaticResource cellStyle}"> <sdk:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Category}" /> </DataTemplate> </sdk:DataGridTemplateColumn.CellTemplate> </sdk:DataGridTemplateColumn> and finally modified the CreateColumn method to apply those styles as well. private DataGridTemplateColumn CreateColumn(int index, string header) { string cellTemp = string.Format(@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <TextBlock Text=""{{Binding Summary[{0}].Total}}"" /> </DataTemplate>", index); DataGridTemplateColumn column = new DataGridTemplateColumn(); column.Header = header; column.CellTemplate = (DataTemplate)XamlReader.Load(cellTemp); column.HeaderStyle = LayoutRoot.Resources["headerStyle"] as Style; column.CellStyle = LayoutRoot.Resources["cellStyle"] as Style; return column; } You can of course use application resources or any other way you want. With all of that I’ve finally got my nice dynamic grid. DynamicDataGrid2 And that’s it. HTH

Dynamic Spotlight Effect Using CSS and JavaScript

almost 4 years ago | Mark Daggett: Mark Daggett's Blog

In casual gaming there is a convention whereby the player is introduced to the interface during the first play cycle. Typically, this involves a character from the game pointing out aspects of the interface and telling the player how to use it and why they should care. Ideally, you want to visually draw the attention of the player to the relevant component of the interface as the characters are explaining it. For this purpose I created a JavaScript class which will spotlight a portion of the screen using only CSS and JavaScript. Here is an example of it working. The class allows you to configure the following spotlight attributes: starting x,y (integer) destination x,y (integer) duration (0%-100%) callback when animation is complete (function) Below is the CSS and JavaScript you’ll need to use it in your own projects. If you improve this script please let me know. 1 <div id="spotLight"></div> 1 2 3 4 5 6 7 #spotLight { width:1024px; height:768px; z-index:9; position:absolute; display:none; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 function SpotLight(element) { this.element = element; this.x = element.width() / 2; this.y = element.height() / 2; this.show = function() { element.hide(); element.removeClass("hide"); return element.fadeIn('fast'); }; this.hide = function(callback) { element.fadeOut('fast', function() { if (callback) { return callback(); } }); return element.addClass("hide"); }; this.move = function(opts) { var endX, endY, obj; obj = $.extend({}, { start_x: this.x, start_y: this.y, x: this.x, y: this.y, aperture: "50%", duration: 1000, done: function() {} }, opts); endX = obj.x; endY = obj.y; obj.x = obj.start_x; obj.y = obj.start_y; return jQuery(obj).animate({ x: endX, y: endY }, { duration: obj.duration, step: function() { var style, _i, _len, _ref; _ref = ["-moz-radial-gradient(" + this.x + "px " + this.y + "px, ellipse cover, rgba(0,0,0,0) 0%, rgba(0,0,0,0.8) " + this.aperture + ", rgba(0,0,0,0.8) 100%)", "-webkit-gradient(radial, " + this.x + "px " + this.y + "px, 0px, " + this.x + "px " + this.y + "px, 100%, color-stop(0%,rgba(0,0,0,0)), color-stop(" + this.aperture + ",rgba(0,0,0,0.8)), color-stop(100%,rgba(0,0,0,0.8)))", "-webkit-radial-gradient(" + this.x + "px " + this.y + "px, ellipse cover, rgba(0,0,0,0) 0%,rgba(0,0,0,0.8) " + this.aperture + ",rgba(0,0,0,0.8) 100%)", "-o-radial-gradient(" + this.x + "px " + this.y + "px, ellipse cover, rgba(0,0,0,0) 0%,rgba(0,0,0,0.8) " + this.aperture + ",rgba(0,0,0,0.8) 100%)", "-ms-radial-gradient(" + this.x + "px " + this.y + "px, ellipse cover, rgba(0,0,0,0) 0%,rgba(0,0,0,0.8) " + this.aperture + ",rgba(0,0,0,0.8) 100%)", "radial-gradient(ellipse at " + this.x + "px " + this.y + "px, rgba(0,0,0,0) 0%,rgba(0,0,0,0.8) " + this.aperture + ",rgba(0,0,0,0.8) 100%)"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { style = _ref[_i]; element.css({ "background": style }); } return true; }, done: obj.done }); }; return this; } // Example Usage: var spotLight = new SpotLight($("#spotLight")) spotLight.show(); spotLight.move({ x: 150, y: 650 });

racing and profiling

almost 4 years ago | Mark Daggett: Mark Daggett's Blog

I’ve been experimenting with various ways to profile, and explore JavaScript as it executes in the runtime environment. Mostly I’ve been experimenting with the rKelly and rubyracer gems. Both gems are written by people much smarter than myself so there is lots to learn and explore inside their source. I was talking to the very friendly Charles Lowell, creator of the rubyracer and he shared this great snippet with me, which allows you to turn on the v8 profiler while the rubyracer is running. Because this is an undocumented hook I thought I’d share it here: 1 ruby -Ilib -Iext -rv8 -e 'V8::C::V8::SetFlagsFromString("--prof"); V8::Context.new() {|c| puts c.eval("5 + 1")}; V8::C::V8::PauseProfiler()' This will produce a v8.log file wherever you executed the script from. Inside the file there is a gluttonous amount of data, which will take some time to parse through but in general it looks a bit like this: code-creation,LoadIC,0x127fc3e29140,181,"A load IC from the snapshot" code-creation,KeyedLoadIC,0x127fc3e29200,181,"A keyed load IC from the snapshot" code-creation,StoreIC,0x127fc3e292c0,183,"A store IC from the snapshot" code-creation,KeyedStoreIC,0x127fc3e29380,183,"A keyed store IC from the snapshot" code-creation,Builtin,0x127fc3e29440,97,"A builtin from the snapshot" code-creation,Builtin,0x127fc3e294c0,137,"A builtin from the snapshot" code-creation,Script,0x127fc3e14e20,980,"native string.js",0x2e87cc50ec50, code-creation,LazyCompile,0x127fc3e15500,1616,"SetUpString native string.js:940",0x2e87cc5129c8, code-creation,LazyCompile,0x127fc3e15be0,472," native string.js:36",0x2e87cc512ab0, code-creation,Script,0x127fc3e15dc0,336,"native array.js",0x2e87cc512e00, code-creation,LazyCompile,0x127fc3e15f20,2544,"SetUpArray native array.js:1469",0x2e87cc5175b0, code-creation,LazyCompile,0x127fc3e16920,340,"SetUpArray.b native array.js:1482",0x2e87cc517668, code-creation,Script,0x127fc3e16b00,552,"native regexp.js",0x2e87cc5177f0, code-creation,LazyCompile,0x127fc3e16d40,388,"RegExpConstructor native regexp.js:86",0x2e87cc518a70, code-creation,LazyCompile,0x127fc3e16ee0,280,"RegExpMakeCaptureGetter native regexp.js:363",0x2e87cc519288, code-creation,LazyCompile,0x127fc3e17000,668," native regexp.js:364",0x2e87cc519340, code-creation,LazyCompile,0x127fc3e172a0,2304,"SetUpRegExp native regexp.js:403",0x2e87cc519488, code-creation,LazyCompile,0x127fc3e17ba0,292,"SetUpRegExp.a native regexp.js:422",0x2e87cc519540, code-creation,LazyCompile,0x127fc3e17ce0,256,"SetUpRegExp.c native regexp.js:426",0x2e87cc519658,