Categories

Get time from an external website

If you visit the link, you will see the following as an example

Jun. 25, 18:34:54 UTC Universal Time
Jun. 25, 02:34:54 PM EDT Eastern Time
Jun. 25, 01:34:54 PM CDT Central Time
Jun. 25, 12:34:54 PM MDT Mountain Time
Jun. 25, 11:34:54 AM PDT Pacific Time
Jun. 25, 10:34:54 AM AKDT Alaska Time
Jun. 25, 08:34:54 AM HAST Hawaii-Aleutian Time

By changing the code you can change the time you want to show

import urllib2
for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
     if 'UTC' in line:      # look for Universal Time
         print line
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

jQuery Selectors

“*”
Selects all elements.

:animated
Select all elements that are in the progress of an animation at the time the selector is run.

[name|=”value”]
Selects elements that have the specified attribute with a value either equal to a given string or starting with that string followed by a hyphen (-).

[name*=”value”]
Selects elements that have the specified attribute with a value containing the a given substring.

[name~=”value”]
Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

[name$=”value”]
Selects elements that have the specified attribute with a value ending exactly with a given string. The comparison is case sensitive.

[name=”value”]
Selects elements that have the specified attribute with a value exactly equal to a certain value.

[name!=”value”]
Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value.

[name^=”value”]
Selects elements that have the specified attribute with a value beginning exactly with a given string.

:button
Selects all button elements and elements of type button.

:checkbox
Selects all elements of type checkbox.

:checked
Matches all elements that are checked.

“parent > child”
Selects all direct child elements specified by “child” of elements specified by “parent”.

“.class”
Selects all elements with the given class.

:contains()
Select all elements that contain the specified text.

“ancestor descendant”
Selects all elements that are descendants of a given ancestor.

:disabled
Selects all elements that are disabled.

“element”
Selects all elements with the given tag name.

:empty
Select all elements that have no children (including text nodes).

:enabled
Selects all elements that are enabled.

:eq()
Select the element at index n within the matched set.

:even
Selects even elements, zero-indexed. See also odd.

:file
Selects all elements of type file.

:first-child
Selects all elements that are the first child of their parent.

:first
Selects the first matched element.

:focus
Selects element if it is currently focused.

:gt()
Select all elements at an index greater than index within the matched set.

[name]
Selects elements that have the specified attribute, with any value.

:has()
Selects elements which contain at least one element that matches the specified selector.

:header
Selects all elements that are headers, like h1, h2, h3 and so on.

:hidden
Selects all elements that are hidden.

“#id”
Selects a single element with the given id attribute.

:image
Selects all elements of type image.

:input
Selects all input, textarea, select and button elements.

:last-child
Selects all elements that are the last child of their parent.

:last
Selects the last matched element.

:lt()
Select all elements at an index less than index within the matched set.

[name=”value”][name2=”value2″]
Matches elements that match all of the specified attribute filters.

“selector1, selector2, selectorN”
Selects the combined results of all the specified selectors.

“prev + next”
Selects all next elements matching “next” that are immediately preceded by a sibling “prev”.

“prev ~ siblings”
Selects all sibling elements that follow after the “prev” element, have the same parent, and match the filtering “siblings” selector.

:not()
Selects all elements that do not match the given selector.

:nth-child()
Selects all elements that are the nth-child of their parent.

:odd
Selects odd elements, zero-indexed. See also even.

:only-child
Selects all elements that are the only child of their parent.

:parent
Select all elements that are the parent of another element, including text nodes.

:password
Selects all elements of type password.

:radio
Selects all elements of type radio.

:reset
Selects all elements of type reset.

:selected
Selects all elements that are selected.

:submit
Selects all elements of type submit.

:text
Selects all elements of type text.

:visible
Selects all elements that are visible.

FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

reverse lookup on the IP address

Look up a web address based on a IP address

Handy if you saw some strange IP addresses in your web logs

import sys, socket

try:
    result = socket.gethostbyaddr("127.0.0.1")
    print "Primary hostname:"
    print "  " + result[0]

    # Display the list of available addresses that is also returned
    print "\nAddresses:"
    for item in result[2]:
        print "  " + item
except socket.herror, e:
    print "Couldn't look up name:", e
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Open a web browser in Python

#! /usr/bin/env python

import sys, webbrowser

def main():
    args = sys.argv[1:]
    if not args:
        print "Usage: %s querystring" % sys.argv[0]
        return
    list = []
    for arg in args:
        if '+' in arg:
            arg = arg.replace('+', '%2B')
        if ' ' in arg:
            arg = '"%s"' % arg
        arg = arg.replace(' ', '+')
        list.append(arg)
    s = '+'.join(list)
    url = "http://www.google.com/search?q=%s" % s
    webbrowser.open(url)

if __name__ == '__main__':
    main()
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Image switch example in AngularJS

In a previous example we showed you a switch example in AngularJS, this is the same idea but a little more practical. You’ll need 3 images, when you type in the number you will see the corresponding image

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js"></script>
</head>

<body ng-app>
  <label>Type the number you want to show (1 to 3): <input type="text" ng-model="showNumber" /></label><br />
  <div ng-switch="showNumber">
    <div ng-switch-when="1"><img src="owl2.jpg"></div>
    <div ng-switch-when="2"><img src="owl3.jpg"></div>
    <div ng-switch-when="3"><img src="owl4.jpg"></div>
    <div ng-switch-default style="width: 50px; background-color: lightgray; text-align: center;">None</div>
  </div>
</body>
</html>
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Useful jQuery examples

change()

The change() method is an event handler, just like click() or hover(). The change event is for textareas, text inputs, and select boxes, and it will fire when the value of the target element is changed; note that this is different from the focusOut() or blur() event handlers, which fire when the element loses focus, whether its value has changed or not.

The change() event is perfect for client-side validation; it’s much better than blur(), because you won’t be re-validating fields if the user doesn’t change the value.

$(‘input[type=text]’).change(function () {
switch (this.id) {
/ some validation code here /
}
});​​​​​​​​​​

Context

Context is both a parameter and a property in jQuery. When collecting elements, you can pass in a second parameter to the jQuery function. This parameter, the context, will usually be a DOM element, and it limits the elements returned to item matching your selector that are children of the context element. That might sound a bit confusing, so check out this example:

<p class=”hello”>Hello World</p>
<div id=”wrap”>
<p class=”hello”>Hello World</p>
</div>

var hi1 = $(‘.hello’),
hi2 = $(‘.hello’, $(‘#wrap’).get(0));

console.group(‘hi1′);
console.log(“Number of elements in collection:”, hi1.length);
console.log(“Context of the collection:”, hi1.context);
console.groupEnd();
console.group(‘hi2′);
console.log(“Number of elements in collection:”, hi2.length);
console.log(“Context of the collection:”, hi2.context);
console.groupEnd();
So where would this be useful? One place might be inside an event handler function. If you’d like to get an element within the one the event was fired on, you could pass this as the context:

$(‘ul#options li’).click(function () {
$(‘a’, this) . . .
});

data() / removeData()

Have you ever wanted to store some bit of information about an element? You can do that easily with the data() method. To set a value, you can pass in two parameters (a key and a value) or just one (an object).
$(‘#wrap’).data(‘myKey’, ‘myValue’);
$(‘#container’).data({ myOtherKey : ‘myOtherValue’, year : 2010 });
To get your data back, just call the method with the key of value you want.
$(‘#container’).data(‘myOtherKey’); //returns ‘myOtherValue’
$(‘#container’).data(‘year’); //returns 2010
To get all the data that corresponds with an element, call data without any parameters; you’ll get an object with all the keys and values you’ve given to that item.
If you want to delete a key/value pair after you’ve added it to an element, just call removeData(), passing in the correct key.

$(‘#container’).removeData(‘myOtherKey’);

queue() / dequeue()

The queue() and dequeue() functions deal with animations. A queue is list of animations to be executed on an element; be default, an element’s queue is named ‘fx.’

HTML
<ul>
<li id=”start”>Start Animating</li>
<li id=”reset”>Stop Animating</li>
<li id=”add”>Add to Queue</li>
</ul>
<div style=”width:150px; height:150px; background:#ececec;”></div>

JavaScript
$(‘#start’).click(animateBox);

$(‘#reset’).click(function() {
$(‘div’).queue(‘fx’, []);
});

$(‘#add’).click(function() {
$(‘div’).queue( function(){
$(this).animate({ height : ‘-=25′}, 2000);
$(this).dequeue();
});
});

function animateBox() {
$(‘div’).slideUp(2000)
.slideDown(2000)
.hide(2000)
.show(2000, animateBox);
}

delay()

When you’re queuing up a chain of animations, you can use the delay() method to pause the animation for a length of time; pass that time as a parameter in milliseconds.

$(‘div’).hide().delay(2000).show(); // div will stay hidden for 2 seconds before showing.

bind(), unbind(), live(), and die()

Did you know that when you add a click event to an element like this . . .

$(‘#el’).click(function () { /*******/ });
. . . you’re really just using a wrapper for the bind() method? To use the bind() method itself, you can pass the event type as the first parameter and then the function as the second.

If you use a lot of events, you can categorize them with namespacing; just add a period after the event name and add your namespace.

$(‘#el’).bind(‘click’, function () { /*******/ });
$(‘#el’).bind(‘click.toolbarEvents’, function () { /*******/ }); // namespaced
You can also assign the same function to multiple events at the same time, by separating them with spaces. So if you wanted to make a hover effect, you could start this way:
$(‘#el’).bind(‘mouseover mouseout’, function () { /*******/ });

eq()

If you’re looking for a specific element within a set of elements, you can pass the index of the element to the eq() method and get a single jQuery element. Pass in a negative index to count back from the end of the set.

var ps = $(‘p’);
console.log(ps.length); // logs 3;
ps.eq(1).addClass(’emphasis’); // just adds the class to the second item (index in zero-based)
You can also use :eq() in your selectors; so the previous example could have been done like this:

$(‘p:eq(1)’).addClass(’emphasis’);

get()

When getting a collection of element, jQuery returns them as a jQuery object, so you have access to all the methods. If you just want the raw DOM elements, you can use the get() method.

You can specify an index to get only one element.

alert( $(‘p’) ); // [object Object] – the jquery object
alert( $(‘p’).get(1) ); // [object HTMLParagraphElement]

grep()

If you’re not familiar with Unix/Linix shells, you might not have heard the term grep. In a terminal, it’s a text search utility; but here in jQuery, we use it to filter an array of elements. It’s not a method of a jQuery collection; you pass in the array as the first parameter and the filtering function as the second parameter. That filter function takes two parameters itself: an element from the array and its index. That filter function should perform its work and return a true or false value. Be default, all the items that return true will be kept. You can add a third parameter, a boolean, to invert the results and kept the items that return false.

Jeffrey Way did a great quick tip about the $.grep not long ago; check that out to see how to use it!
var nums = ‘1,2,3,4,5,6,7,8,9,10’.split(‘,’);

nums = $.grep(nums, function(num, index) {
// num = the current value for the item in the array
// index = the index of the item in the array
return num > 5; // returns a boolean
});

console.log(nums) // 6,7,8,9,10

Pseudo-Selectors

Sizzle, the CSS Selector engine inside jQuery, offers quite a few pseudo-selectors to make the job of selecting the elements you want easy. Check out these interesting ones:
$(‘:animated’); // returns all elements currently animating
$(‘:contains(me)’); // returns all elements with the text ‘me’
$(‘:empty’); // returns all elements with no child nodes or text
$(‘:parent’); // returns all elements with child nodes or text
$(‘li:even’); // returns all even-index elements (in this case, <li>s)
$(‘li:odd’); // can you guess?
$(‘:header’); // returns all h1 – h6s.
$(‘li:gt(4)’); // returns all elements with an (zero-based) index greater than the given number
$(‘li:lt(4)’); // returns all element with an index less than the given number
$(‘:only-child’); // returns all . . . well, it should be obvious
There are more, of course, but these are the unique ones.

isArray() / isEmptyObject() / isFunction() / isPlainObject()

Sometimes you want to make sure the parameter that was passed to a function was the corrent type; these functions make it easy to do. The first three are pretty self explanatory:

$.isArray([1, 2, 3]); // returns true
$.isEmptyObject({}); // returns true
$.isFunction(function () { /****/ }); // returns true
The next one isn’t as obvious; isPlainObject() will return true if the parameter passed in was created as an object literal, or with new Object().

function Person(name) {
this.name = name
return this;
}
$.isPlainObject({})); // returns true
$.isPlainObject(new Object()); // returns true
$.isPlainObject(new Person()); // returns false

makeArray()

When you create a collection of DOM elements with jQuery, you’re returned a jQuery object; in some situations, you might prefer that this be an array or regular DOM elements; the makeArray() function can do just that.

var ps = $(‘p’);
$.isArray(ps); //returns false;
ps = $.makeArray(ps);
$.isArray(ps); // returns true;

map()

The map() method is remotely similar to grep(). As you might expect, it takes one parameter, a function. That function can have two parameters: the index of the current element and the element itself. Here’s what happens: the function that you pass in will be run once for each item in the collection; whatever value is returned from that function takes the place of the item it was run for in the collection.

$(‘ul#nav li a’).map(function() {
return $(this).attr(‘title’);
}); // now the collection is the link titles
// this could be the beginning of a tooltip plugin.

parseJSON()

If you’re using $.post or $.get—and in other situations that you work with JSON strings—you’ll find the parseJSON function useful. It’s nice that this function uses the browsers built-in JSON parser if it has one (which will obviously be faster).

$.post(‘somePage.php’, function (data) {
/*****/
data = $.parseJSON(data);
/*****/
});

proxy()

If you have a function as a property of an object, and that function uses other properties of the object, you can’t call that function from within other functions and get the right results. I know that was confusing, so let’s look at a quick example:
var person = {
name : “Andrew”,
meet : function () {
alert(‘Hi! My name is ‘ + this.name);
}
};
person.meet();
$(‘#test’).click(person.meet);
By itself, person.meet() will alert correctly; but when it’s called by the event handler, it will alert “Hi! My name is undefined.” This is because the function is not being called in the right context. To fix this, we can use the proxy() function:

$(‘#test’).click($.proxy(person.meet, person));
// we could also do $.proxy(person, “meet”)
The first parameter of the proxy function is the method to run; the second is the context we should run it in. Alternatively, we can pass the context first, and the method name as a string second. Now you’ll find that the function alerts correctly.

replaceAll() / replaceWith()

If you’d like to replace DOM elements with other ones, here’s how to do it. We can call replaceAll() on elements we’ve collected or created, passing in a selector for the elements we’d like to replace. In this example, all elements with the error class will be replaced with the span we’ve created.

$(‘<span class=”fixed”>The error has been corrected</span>’).replaceAll(‘.error’);
The replaceWith() method just reverses the selectors; find the ones you want to replace first:

$(‘.error’).replaceWith(‘<span class=”fixed”>The error has been corrected</span>’);
You can also pass these two methods functions that will return elements or HTML strings.

serialize() / serializeArray()

The serialize() method is what to use for encoding the values in a form into a string.

HTML
<form>
<input type=”text” name=”name” value=”John Doe” />
<input type=”text” name=”url” value=”http://www.example.com” />
</form>
JavaScript

console.log($(‘form’).serialize());​​​ // logs : name=John+Doe&url=http%3A%2F%2Fwww.example.com
You can use serializeArray() to turn the form values into an array of objects instead of a string:

console.log($(‘form’).serializeArray());​​​
// logs : [{ name : ‘name’, value : ‘John Doe’} , { name : ‘url’, value : ‘http://www.example.com’ } ]

siblings()

You can probably guess what the siblings() method does; it will return a collection of the siblings of the whatever items are in your original collections:

<div> . . . </div>
<p> . . . </p>
<span> . . . </span>
$(‘p’).siblings(); // returns <div>, <span>

wrap() / wrapAll() / wrapInner()

These three functions make it easy to wrap elements in other elements. First off, I’ll mention that all three take one parameter: either an element (which is an HTML string, a CSS selctor, a jQuery object, or a DOM element) or a function that returns an element.
The wrap() method wraps each item in the collection with the assigned element:

$(‘p’).wrap(‘<div class=”warning” />’); // all paragraphs are now wrapped in a div.warning
The wrapAll() will wrap one element around all the elements in the collection; this means that the elements in the collection will be moved to a new spot in the DOM; they’ll line up at the place of the first element in the collection and be wrapped there:

FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare