Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Tuesday, December 7, 2010

OpenLayers map + markers + cool info box

I made a little project for my father (in return he pays for my piano lessons).
My father is one of the managers of the folk dance society in Israel. They have a website, where all dancing clubs are listed, including relevant information such as place, time, price, type of music, ...
He wanted a map where someone could see all dancing places near his/her home.
Google Maps would have been a natural choice hadn't they forbidden access to their API specifically for Israel.
I found a great alternative: OpenLayes, which uses data from OpenStreetMap.
I'm all excited because I know nothing about JavaScript and CSS but eventually it worked!
Well, here it is:


Things to notice:
  • The info box is half transparent
  • It has round corners
  • When you click a place, the info box sticks, so you can follow the links

Monday, June 7, 2010

Get IMDB movie rating using JavaScript (Cross domain AJAX solution)

UPDATE: I modified my script to use imdbparser.appspot.com that I built, so the information is always accurate and it works fast.
This query:
https://imdbparser.appspot.com/?callback=foo&context=bar&action=rating&id=tt0411008
Gives this result: foo('bar', '8.7')
So you can write something like that:

<script type="text/javascript">
function foo(context, rating)
{
  alert("The rating is: " + rating);
}
</script>
<script src="https://imdbparser.appspot.com/?callback=foo&context=bar&action=rating&id=tt0411008" type="text/javascript">
</script>

Original Post:



Solution to what exactly?

In JavaScript you aren't suppose to communicate with other sites, such as IMDB. As a result, you can't get the rating of a movie just like that.
For more information:
http://en.wikipedia.org/wiki/Same_origin_policy

Example: Vicky Cristina Barcelona

How to use it in your website?

Put this code in the top of the page:
<script src="http://sites.google.com/site/ycouriel/files/imdbrating.js" type="text/javascript"> </script>
Put this code each time you want to get rating:
<script type="text/javascript"> IMDBRATING.registerTitle("tt0068646");</script>
Finally, put this code in the bottom of the page: 
<script type="text/javascript"> IMDBRATING.processTitles();</script>
You also need to put this CSS if you want the nice stars: imdbrating.css


How it's done?

The trick is to use Google. Consider the following query:
You get in return:
IMDBRATING.ratingCallback( <search results here> );
This wonderful feature of Google allows you to write a query as the source of JavaScript: 
<script src=" <the query above here> " type="text/javascript"> </script>
By parsing the search results, you can easily find the rating.

Notes:
  • This is a JavaScript solution; if you have a server running PHP or something you can put some page like Google's, only instead of search results you return the ratings. This could be wonderful, but all the websites on the Internet that do exactly that didn't work for me or were very slow.
  • The rating you get is sometimes not updated, it entirely depends on how often Google database is updated.

Saturday, February 20, 2010

Use JavaScript to Format C# Code to HTML

To format C# code online go here.
To add it as a widget go to this post.
To get the most recent source code go here.

Example of how it looks:
using System.Xml.Serialization;

namespace foo
{
    public partial class Form1<AAA> : Form
    {
        void bar<T, R, L>(int k, Form1 f)
            where T : ISerializable
            where R : Dictionary<string, List<Form1>>, ISerializable
        {
            Form1 Form1 = new Form1();
        }
    }
}

I wrote a script in JavaScript to format C# Code.
I needed such a script because I didn't like the old way of copying the code to Microsoft Word, then to Blogger, and then looking for and removing all the <META> and <LINK> tags that Blogger doesn't accept.
Before I did that, I looked on the Internet, and I found this wonderful site: http://www.manoli.net/csharpformat
But it doesn't handle strings very well, and doesn't recognize types.

For example, the expression 'string path = @"c:\";' returns:
<span class="kwrd">string</span> path = @"c:\";
Which means the string is black instead of red.
About types, I think it's not supported at all.
I downloaded their source code and I found some useful things for my code.

I used more accurate regular expressions to identify strings:
// backslash slash before the end using @
string path = @"c:\";
// even number of backslashes means no backslash
string x = " \" \\\" \\\\";
/* support for multi line
   comments and strings
*/
string y = @" begin
                end";
/// <summary> This kind is also supported
/// </summary>

Formatting strings, comments and keywords is no big deal, but what about types?
Sometimes you don't know if something is a type or a variable, for example:
Something.DoIt();
(There is a way of telling the script that "Something" is a type, and it will be explained later)
It could be a field or a property called "Something", or it could be a class called "Something" and in that case "DoIt" would be a static function.
But sometimes you do know that something is a type, and it worth remembering it for the future:
class Something { } // here the script identifies "Something" as a type
Something.DoIt(); // here it uses the information from earlier

But what about "Application.DoEvents()" ?
In that case the script has a list of common types:
Application.DoEvents();

I compiled this list using this code:
static string GetAllTypes()
{
    string regex = "";
    foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
    {
        foreach (Type type in asm.GetTypes())
        {
            string name = new Regex("(`.*)").Replace(type.Name, "");
            if (new Regex("^[A-Za-z0-9]+$").IsMatch(name))
            {
                regex += name + "|";
                Match match = new Regex("^(.+)Attribute$").Match(name);
                if (match.Success){
                    regex += match.Groups[1].Value + "|";
                }
            }
        }
    }
    return regex;
}

Sometimes the long list affects the loading time of the blog, so I have another manually written list that has the most commonly used types like: List, EventArgs, ...
Note that the shorter list doesn't necessarily mean the script wont recognize any types, that is because it learns the types from the code itself (as shown in the example above).

In order to use the script you need to write the following code:
<pre formatcs=1>
your code here
</pre>

If the script doesn't recognize a type from some reason, like in the in example of "Something.DoIt()" case, then you can instruct the script to recognize it by adding a new attribute called "types":
<pre formatcs=1 types="Something">
Something.DoIt();
</pre>
And the result:
Something.DoIt();
The types attribute accepts a list of type names, and it can be separated by comma, white space, anything.

The script can handle generics - means it doesn't paint it like in here:
class MyClass<T>
{
    List<T> x = new List<T>();
}

However, there might be cases where the class definition is missing, and then T might be mistaken for type:
x = new T();

Another issue with generics and more specifically with the "<" sign is that you have to write "&lt;", otherwise Blogger is going crazy adding all sorts of strange ending tags to the posts. This behavior is not caused by the script, but it does keep it from working correctly. I don't know how it behaves on other blogging sites, but I tested the script offline on my computer it works with normal "<" too.

I plan to make a gadget that adds this functionality to a blog. I will call it "C# Code Formatter".
But in the meantime the script can be used from here:
jscsharpformatter.googlecode.com

I added a new "HTML/JavaScript" gadget on the bottom of the page with the following code:
<script type="text/javascript" src="http://sites.google.com/site/ycouriel/files/csharp_formatter_normal.js">
</script>
<script type="text/javascript">
var howmany = findAndFormatCSharp();
document.write(howmany + " c# code elements were formatted");
</script>

Feedback is very welcome!

Thursday, February 18, 2010

Blogger like search box

I copied the Blogger search box and added the following features:
  • It shows the current search keywords after you invoked the search (by parsing the URL)
  • It has a border that becomes gray when mouse is on the box
  • It has a faded string when not in focus, and it disappears when in focus
Take a look:
http://ycouriel-archive.blogspot.com/
(It's on the sidebar)

This is actually the first time I'm using HTML, JavaScript and CSS.
So I hope the code won't be that embarrassing:

<div id="b-navbar2">
<form style="display: inline;" method="get" action="http://ycouriel-archive.blogspot.com/search" id="searchthis">
<div id="b-query-box" style="width: 193.7px;" >
<table cellspacing="0" cellpadding="0">
<tbody>
<tr>
<style type="text/css">
#b-navbar2{
white-space:nowrap;color:#fff;height:29px;border-bottom:1px solid #024;background:transparent;font-size:13px;font-family:Arial,Sans-serif
}
#b-navbar2 #b-query-box{
background-color:#fff;margin:0 .5em 0 0;border:1px solid transparent;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px;padding:0 .3em
}
#b-navbar2 #b-query-box:hover{
border:1px solid #999999;
}
#b-navbar2 #b-query-icon{
display:block;width:13px;height:13px;cursor:pointer;cursor:hand;background:url(http://img1.blogblog.com/img/navbar/icons_orange.png) no-repeat 0 0
}
#b-navbar2 #b-query-icon:hover{
background:url(http://img1.blogblog.com/img/navbar/icons_orange.png) no-repeat -13px 0
}
#b-navbar2 #b-query{
font-size:13px;color:#000;background-color:transparent;border:none;margin:0
}
</style>
<td valign="middle">
<input type="text" title="Search" style="width: 180px; color: #999999;" tabindex="3" name="q" id="b-query" onblur="if (this.value == '') {this.value = 'Search...'; this.style.color='#999999';}" onfocus="if(this.value == 'Search...') {this.style.color='#000000';this.value = '';}" value="Search...">
</td>
<td valign="right" style="width: 15px;">
<a title="Search this blog" onclick="document.getElementById(&quot;searchthis&quot;).submit();" id="b-query-icon"></a></td></tr></tbody></table></div></form>
<script language="JavaScript">
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function decode(encoded) {
    return decodeURIComponent(encoded.replace(/\+/g, " "));
}

var q = gup("q");
if (q != "") {
    var lmnt = document.getElementById("b-query");
    lmnt.value = decode(q);
    lmnt.style.color = "#000000";
}
</script>

Monday, December 7, 2009

How to grab Google autocomplete list

We all know this wonderful feature:

Automation of grabbing that list can be helpful for instance if you want to know what people are looking for.

While typing in the search box, somewhere there is a Javascript code that makes the following HTTP GET request:
http://www.google.com/complete/search?hl=en&q=QUERY&cp=LEN(QUERY)

For example, the following query gives the same results as in the picture:
http://www.google.com/complete/search?hl=en&q=how%20to%20be%20better%20at%20&cp=20

window.google.ac.h(["how to be better at ",[
["how to be better at halo 3","43,100,000 results","0"],
["how to be better at basketball","87,500,000 results","1"],
["how to be better at math","52,900,000 results","2"],
["how to be better at soccer","88,300,000 results","3"],
["how to be better at football","207,000,000 results","4"],
["how to be better at beer pong","2,760,000 results","5"],
["how to be better at call of duty 4","72,600,000 results","6"],
["how to be better at madden","25,900,000 results","7"],
["how to be better at volleyball","9,370,000 results","8"],
["how to be better at chess","15,300,000 results","9"]]])