Categories

Python 2.7 Regular Expressions

\       Escape special char or start a sequence.
.       Match any char except newline, see re.DOTALL
^       Match start of the string, see re.MULTILINE
$       Match end of the string, see re.MULTILINE
[]      Enclose a set of matchable chars
R|S     Match either regex R or regex S.
()      Create capture group, & indicate precedence

After ‘[‘, enclose a set, the only special chars are:

]   End the set, if not the 1st char
-   A range, eg. a-c matches a, b or c
^   Negate the set only if it is the 1st char

Quantifiers (append ‘?‘ for non-greedy):

{m}     Exactly m repetitions
{m,n}   From m (default 0) to n (default infinity)
*       0 or more. Same as {,}
+       1 or more. Same as {1,}
?       0 or 1. Same as {,1}

Special sequences:

\A  Start of string
\b  Match empty string at word (\w+) boundary
\B  Match empty string not at word boundary
\d  Digit
\D  Non-digit
\s  Whitespace [ \t\n\r\f\v], see LOCALE,UNICODE
\S  Non-whitespace
\w  Alphanumeric: [0-9a-zA-Z_], see LOCALE
\W  Non-alphanumeric
\Z  End of string
\g<id>  Match prev named or numbered group,
        '<' & '>' are literal, e.g. \g<0>
        or \g<name> (not \g0 or \gname)

Special character escapes are much like those already escaped in Python string literals. Hence regex ‘\n‘ is same as regex ‘\\n‘:

\a  ASCII Bell (BEL)
\f  ASCII Formfeed
\n  ASCII Linefeed
\r  ASCII Carriage return
\t  ASCII Tab
\v  ASCII Vertical tab
\\  A single backslash
\xHH   Two digit hexadecimal character goes here
\OOO   Three digit octal char (or just use an
       initial zero, e.g. \0, \09)
\DD    Decimal number 1 to 99, match
       previous numbered group

Extensions. Do not cause grouping, except ‘P<name>‘:

(?iLmsux)     Match empty string, sets re.X flags
(?:...)       Non-capturing version of regular parens
(?P<name>...) Create a named capturing group.
(?P=name)     Match whatever matched prev named group
(?#...)       A comment; ignored.
(?=...)       Lookahead assertion, match without consuming
(?!...)       Negative lookahead assertion
(?<=...)      Lookbehind assertion, match if preceded
(?<!...)      Negative lookbehind assertion
(?(id)y|n)    Match 'y' if group 'id' matched, else 'n'

Flags for re.compile(), etc. Combine with '|':

re.I == re.IGNORECASE   Ignore case
re.L == re.LOCALE       Make \w, \b, and \s locale dependent
re.M == re.MULTILINE    Multiline
re.S == re.DOTALL       Dot matches all (including newline)
re.U == re.UNICODE      Make \w, \b, \d, and \s unicode dependent
re.X == re.VERBOSE      Verbose (unescaped whitespace in pattern
                        is ignored, and '#' marks comment lines)

Module level functions:

compile(pattern[, flags]) -> RegexObject
match(pattern, string[, flags]) -> MatchObject
search(pattner, string[, flags]) -> MatchObject
findall(pattern, string[, flags]) -> list of strings
finditer(pattern, string[, flags]) -> iter of MatchObjects
split(pattern, string[, maxsplit, flags]) -> list of strings
sub(pattern, repl, string[, count, flags]) -> string
subn(pattern, repl, string[, count, flags]) -> (string, int)
escape(string) -> string
purge() # the re cache

RegexObjects (returned from compile()):

.match(string[, pos, endpos]) -> MatchObject
.search(string[, pos, endpos]) -> MatchObject
.findall(string[, pos, endpos]) -> list of strings
.finditer(string[, pos, endpos]) -> iter of MatchObjects
.split(string[, maxsplit]) -> list of strings
.sub(repl, string[, count]) -> string
.subn(repl, string[, count]) -> (string, int)
.flags      # int, Passed to compile()
.groups     # int, Number of capturing groups
.groupindex # {}, Maps group names to ints
.pattern    # string, Passed to compile()

MatchObjects (returned from match() and search()):

.expand(template) -> string, Backslash & group expansion
.group([group1...]) -> string or tuple of strings, 1 per arg
.groups([default]) -> tuple of all groups, non-matching=default
.groupdict([default]) -> {}, Named groups, non-matching=default
.start([group]) -> int, Start/end of substring match by group
.end([group]) -> int, Group defaults to 0, the whole match
.span([group]) -> tuple (match.start(group), match.end(group))
.pos       int, Passed to search() or match()
.endpos    int, "
.lastindex int, Index of last matched capturing group
.lastgroup string, Name of last matched capturing group
.re        regex, As passed to search() or match()
.string    string, "
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

AngularJS hello world example

<!DOCTYPE html>
<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js">
</script>
</head>
<body>
     <input  ng-model="name" type="text"  placeholder="Your name">
     <h1>Hello  {{  name  }}</h1>
</body>
</html>
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

jQuery Utilities

.clearQueue()  Remove from the queue all items that have not yet been run.
.dequeue()  Execute the next function on the queue for the matched elements.
jQuery.boxModel  States if the current page, in the user’s browser, is being rendered using the W3C CSS Box Model. This property was removed in jQuery 1.8. Please try to use feature detection instead.
jQuery.browser  Contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin. Please try to use feature detection instead.
jQuery.contains()  Check to see if a DOM element is a descendant of another DOM element.
jQuery.data()  Store arbitrary data associated with the specified element and/or return the value that was set.
jQuery.dequeue()  Execute the next function on the queue for the matched element.
jQuery.each()  A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function’s arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
jQuery.extend()  Merge the contents of two or more objects together into the first object.
jQuery.fn.extend()  Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.
jQuery.globalEval()  Execute some JavaScript code globally.
jQuery.grep()  Finds the elements of an array which satisfy a filter function. The original array is not affected.
jQuery.inArray()  Search for a specified value within an array and return its index (or -1 if not found).
jQuery.isArray()  Determine whether the argument is an array.
jQuery.isEmptyObject()  Check to see if an object is empty (contains no enumerable properties).
jQuery.isFunction()  Determine if the argument passed is a Javascript function object.
jQuery.isNumeric()  Determines whether its argument is a number.
jQuery.isPlainObject()  Check to see if an object is a plain object (created using “{}” or “new Object”).
jQuery.isWindow()  Determine whether the argument is a window.
jQuery.isXMLDoc()  Check to see if a DOM node is within an XML document (or is an XML document).
jQuery.makeArray()  Convert an array-like object into a true JavaScript array.
jQuery.map()  Translate all items in an array or object to new array of items.
jQuery.merge()  Merge the contents of two arrays together into the first array.
jQuery.noop()  An empty function.
jQuery.now()  Return a number representing the current time.
jQuery.parseHTML()  Parses a string into an array of DOM nodes.
jQuery.parseJSON()  Takes a well-formed JSON string and returns the resulting JavaScript value.
jQuery.parseXML()  Parses a string into an XML document.
jQuery.proxy()  Takes a function and returns a new one that will always have a particular context.
jQuery.queue()  Show or manipulate the queue of functions to be executed on the matched element.
jQuery.removeData()  Remove a previously-stored piece of data.
jQuery.support  A collection of properties that represent the presence of different browser features or bugs. Intended for jQuery’s internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance. For your own project’s feature-detection needs, we strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support.
jQuery.trim()  Remove the whitespace from the beginning and end of a string.
jQuery.type()  Determine the internal JavaScript [[Class]] of an object.
jQuery.unique()  Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
.queue()  Show or manipulate the queue of functions to be executed on the matched elements.
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Ascii to hex in python

A basic example showing how to convert from ascii to hex

#!/usr/bin/python
import sys

if len(sys.argv) == 1:
    print "[*] Usage: ./script <ascii>"
    sys.exit(1)

first = True
for arg in sys.argv:
    if first:
        first = False
    else:
        print arg + ' -> ' + arg.encode('hex')
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Get CPU type and speed from registry

This snippet shows how to get the current CPU and speed from the registry

 

using System;
using Microsoft.Win32;

namespace Examples
{
 class Program
 {

 static void Main(string[] args)
 {
 RegistryKey RegKey = Registry.LocalMachine;
 RegKey = RegKey.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
 Object cpuSpeed = RegKey.GetValue("~MHz");
 Object cpuType = RegKey.GetValue("VendorIdentifier");
 Console.WriteLine("You have a {0} running at {1} MHz.", cpuType, cpuSpeed);
 Console.ReadLine();
 }

 }
}
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare

Get installed applications in a system using the registry


using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using System;
using Microsoft.Win32;

namespace Examples
{
 class Program
 {

 static void Main(string[] args)
 {

 string registry_key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
 using (Microsoft.Win32.RegistryKey key = Registry.LocalMachine.OpenSubKey(registry_key))
 {
 foreach (string subkey_name in key.GetSubKeyNames())
 {
 using (RegistryKey subkey = key.OpenSubKey(subkey_name))
 {
 Console.WriteLine(subkey.GetValue("DisplayName"));
 }
 }
 Console.ReadLine();
 }
 }

 }
}
FacebookTwitterGoogle+TumblrPinterestStumbleUponRedditLinkedInWhatsAppBlogger PostWordPressBaiduDeliciousDiggFarkKindle ItPlurkPrintFriendlyShare