Obfuscate.js: clean sensitive information out from web page screenshots

Obfuscate.js is a Javascript console tool which obfuscates the text on the web page hiding sensitive information. The purpose of this tool is to be able to make shareable screenshots for collaborative debugging, examples, demos and so on. You no longer need to manually blur parts of the screen shot in Photoshop, GIMP, etc. image manipulation program, saving your precious time and making sharing screenshots easier.

  • You invoke Obfuscate.js script from the Javascript console of your web browser
  • Obfuscate.js obfuscates the whole page or parts of it
  • Take a screenshot
  • Post to a public forum, blog or other media

I hacked it together in a day for my own purposes.

Demostration

Obfuscate.js can walk through the whole page (<body>) or arbitary page bits chosen by CSS selectors.

Open the page with sensitive information in your web browser.

Open Javascript console. Copy-paste line of text from obfuscate.min.js to your Javascript console.

https://github.com/miohtama/obfuscate.js/raw/master/media/console.png

In this point you have the orignal page still with sensitive information

https://github.com/miohtama/obfuscate.js/raw/master/media/sensitive.png

After this you can obfuscate a part of a page by writing the command in the console targeting a specific CSS selector:

obfuscate("#waffle-grid-container"); // Obfuscate contents of Google Spreadsheet

https://github.com/miohtama/obfuscate.js/raw/master/media/part.png

Or simply obfuscate all text the whole page:

obfuscate(); // Obfuscate all the text on the page

https://raw.github.com/miohtama/obfuscate.js/master/media/full.png

More information

Go to Obfuscate.js Github project page.

\"\" Subscribe to RSS feed Image Follow me on Twitter Image Follow me on Facebook Image Follow me Google+

Create complex form field showing and hiding rules with jQuery Interdependencies library

jQuery Interdependencies is a library to create rules for showing and hiding form fields dynamically on your HTML form. It’s use case are the situations where the form filling can take different decision tree paths and the field choices and values affect other fields. The most common scenario is that you have  a “please specify” style text field which becomes available if the user marks a certain checkbox choice.

Image

Test the simple demo above online. This is what the rule code for the above form looks like (see the orignal blog post for syntax highlighting):

// Start creating a new ruleset
var ruleset = $.deps.createRuleset();

// Show diet text input option only when special diet option is selected
var dietRule = ruleset.createRule("#diet", "==", "special");
dietRule.include("#special-diet");

// Make these fields visible when user checks hotel accomodation
var hotelRule = ruleset.createRule("#accomodation", "==", true);
hotelRule.include("#adults");
hotelRule.include("#children");

// Make the ruleset effective on the whole page
ruleset.install();

However, jQuery Interdependecies can do much more. Using the jQuery Interdependecies library simplifies the process of creating form logic rules over vanilla Javascript / jQuery a lot.

  • Your code does become a spaghetti of ifs, elses and Javascript callback functions
  • It is not limited to an input type, but works with all HTML controls: text, checkbox, radio button, select dropdown, etc.
  • It correctly handles nested decision trees, where your form 1st level choice reveals 2nd level choices which in turn reveal 3rd level choices and so on
  • It works well with dynamically generated forms and situations where there are multiple forms on a single page
  • It has API documentation based on JSDuck. Everyone loves good documentation.
  • It is independent from any HTML markup or form framework: you can use it in any project

So, let’s a have little more complex example what we can do:

Image

The example above is from real life system, but you can try the simplified demo version online.

Enjoy – jQuery Interdependencies Github.

\"\" Subscribe to RSS feed Image Follow me on Twitter Image Follow me on Facebook Image Follow me Google+

True lies and falsy values in Python and Javascript

In Python and Javascript programming you can compare different values against true or false even if they are not boolean values as is.  By knowing this, writing some code paths become simpler.

The most used example is None in Python (None would be null in other programming languages):

>>> spoon = False
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon

>>> spoon = None
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon

None is not same as False in Python, but if truth comparison treats it is as were.

In Python, the values which have falsy comparison include, but are not excluded to

  • empty string
  • empty lists and tuples
  • number zero

Further examples:

>>> spoon = ()
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon
>>> spoon = []
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon
>>> spoon = ""
>>> print "Porridge time" if spoon else "There is no spoon"
There is no spoon

So it actually doesn’t make then sense to test both for None or empty string as you could get away with one condition.

>>> banana = ""
>>> print "I am banana" if (banana != '' and banana is not None) else "Muttia miehelle"
Muttia miehelle

The above if could have been written just as if banana.

As a word of warning, some framework classes may implement their own __eq__() and related method causing surprising when doing “if something:” and then expecting it to check for None values only. In these cases, you need to explicitly use is operator to compare against None. is tests if the values point to the same object (a reference comparison) and there exists only one None object in Python. Example:

>>> banana = ""
>>> print "I am banana" if (banana is not None) else \
    "Should not be reached as we explicitly used is comparator"
I am banana

Sometimes you need to process the values which can be string or None, depending on what your favorite form framework have spit out. Then you can use the following or comparison trick to shorten the code not to have extra if: If the left side of or evaluates to false like value (None) then the right side is used. We can use this to force falsy values to be empty string always. Example:

>>> string_like_value = None
>>> print string_like_value.strip()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'strip'

>>> string_like_value = None
>>> print (string_like_value or "").strip()

>>> string_like_value = "  foobar  "
>>> print (string_like_value or "").strip()
foobar

Unlike Python, Javascript does not raise error when accessing a missing attribute on an object. Instead, accessing an undefined variable gives you back undefined value which equals to false in boolean comparisons.

undefined values result to hilarious debugging sessions as a mistyped variable does not cause error or stack trace where it is being accessed, but somewhere deeper in the code not related to the place of an actual error. You can mitigate the risk of this by spreading asserts all around your code to check possible bad function arguments in your own code.

However, undefined as a perverted language feature can be exploited for creating a configurator design pattern (not sure if this pattern has any better name?) as shown below. In Javascript, this pattern is commonly used to give configuration parameters to library functions. Several values are read from layered configuration objects and the highest set value is used – falling back to the defaults if no value is given.

var globalConfig = { x : 3 }
var foobar = function(config) { 
    this.x = config.x || globalConfig.x || "some default value if even global config is missing"; 
    console.log(this.x); 
}
// No x given, so function above should use 
// the default x value from globalConfig
foobar({y:4});
3

Javascript also features === and !== comparisons which equals to Python is comparison. This can be used to check against undefined explicitly.

>> foobar = "";
>> if(!foobar) console.log("Has no foo");
Has no foo

>> foobar = undefined;
>> if(!foobar) console.log("Has no foo");
Has no foo

>> foobar = "";
>> if(foobar !== undefined) console.log("Has no undefined foo");
Has no undefined foo

To make things even more hilarious, undefined could be redefined before ECMAScript 5…

Please share your favorite boolean like comparison trick 🙂

Then, True Lies (1994):

\"\" Subscribe to RSS feed Image Follow me on Twitter Image Follow me on Facebook Image Follow me Google+

Sublime Text 2 tips for Python and web developers

Update 2014-03: Please see updated blog post for Sublime Text 3.

[toc]

Sublime Text 2 is a very powerful text editor which has gained popularity recently – for good reasons. It is commercial (59 USD). Plenty of power comes from the fact that Sublime has a plug-in framework built in Python. Even though the core app remains closed there exist a vibrant plug-in ecosystem around the editor.

Note: You can try Sublime for free. It simply gives nagging dialog “Please buy” now and then.

Here is my collection of tips how I squeezed more power out of the editor. The tips are written from OSX perspective, but should work fine on Linux and Windows too.

I used to be Aptana Studio (Eclipse) junkie. Even though Sublime does not have all the GUI power of Aptana (e.g. see the end of post here) I have found the current versions of Sublime serving my needs better. The biggest reason for the switch is that Aptana / Eclipse forces folders and files to be encapsulated inside “Eclipse space” to work well.

Sublime is more suitable for work where you work with various open source components which do not follow such rigid order you might find in in-house corporate software. When you need to integrate different tools and projects, Sublime scripting opportunities are more straightforward versus building thousands of lines Java code what could be need with Eclipse.

Note: Don’t write anything about Vim or Eclipse in this paragraph.

Unofficial manual

There exist a third-party maintained manual for Sublime. Especially parts for settings and keyboard shortcuts come very handy.

Add-on manager

Install Sublime Package Control. You need run this in order to install any Sublime Text plug-ins. It magically pulls plug-ins from thin air (or GitHub).

Image

After Package Control has been installed you can add new packages with CMD + SHIFT + P, search Package Install. It has context sensitive search and you can find all packages by name.

Favorite plug-ins list

Based on the feedback from the blog friends you might want to install the following plug-ins through Sublime Package Control

More about specific plug-ins later.

Open files from command-line

I have the following in my shell .rc file, so I can open files directly from the terminal:

alias subl="'/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'"
alias nano="subl"
export EDITOR="subl"

Note: nice fallback for nano command which comes from the muscle memory sometimes.

Open folders as projects from command-line

You can also open folders in Sublime Text.

Just type e.g.

subl src

… and the whole src/ folder is opened in the Sublime Text project explorer (right hand).

Image

Note: One folder = one project = one window? I am not sure if there are ways to have multiple projects in the same window.

Searching multiple files

First open a folder as a project in Sublime Text 2. You can do this from the command line, as instructed above, or from File > Open menu.

Then right click the folder in the sidebar to search it:

Image

You can also specify a file extension mask as a comma separated in the Where: field.

Image

Configure sane tab and whitespace policy and other settings

Never save your files with hard tabs characters in them. The same goes for trailing whitespaces which are against policy of many programming language style guides.

In the menu Sublime Text 2 > Preferences > File Settings – User drop in this snippet:

// Place user-specific overrides in this file, to ensure they're preserved
// when upgrading. See
// http://docs.sublimetext.info/en/latest/customization/settings.html
// for more info
{

    // Tab and whitespace handling.
    // Indent using spaces, 4 spaces ber indent by default, clean up extra whitespaces on save
    "tab_size": 4,
    "translate_tabs_to_spaces": true,
    "trim_automatic_white_space": true,
    "trim_trailing_white_space_on_save": true,

    // Do not try to detect the tab size from the opened file
    "detect_indentation" : false,

     // Don't do any VIM keybindings or other VIM fanatic sugar
    "ignored_packages": ["Vintage"],

    // Don't complain about plug-in responsive
    // (Too verbose when you have slow computer)
    "detect_slow_plugins": false,

    // http://www.granneman.com/webdev/editors/sublime-text/top-features-of-sublime-text/auto-completion-in-sublime-text/
    // The delay, in ms, before the auto complete window is shown after typing
    "auto_complete_delay": 500,

    // Install better them
    // (You can get this from the package control)
    // https://github.com/buymeasoda/soda-theme/
    "theme": "Soda Dark.sublime-theme",

    // Download better font
    // https://github.com/adobe/Source-Code-Pro

    "font_face" : "Source Code Pro",
     // Don't show hidden (dotted) directories and binary files in the sidebar
    // (You are not going to edit them in any case)
    "file_exclude_patterns": [".*", "*.pyc", "*.pyo", "*.exe", "*.dll", "*.obj","*.o", "*.a", "*.lib", "*.so", "*.dylib", "*.ncb", "*.sdf", "*.suo", "*.pdb", "*.idb", ".DS_Store", "*.class", "*.psd", "*.db"]
}

See more about the settings.

Note: Don’t confuse File Settings – User with Global Settings – User in Preferences menu. The latter doesn’t seem to work.

Note: Even though you configure this policy, Sublime Text 2 may auto-detect another tab_size policy when you open a file. See the explanation below.

Converting existing files to use spaces instead of tabs

Sublime tries to autodetect tab settings settings for every opened file and may fail, so keep your eye on this when working with uncleaned files. You might want to use git pre-commit to prevent committing files with tabs in them.

Do View > Indentation > Convert Indentation to Spaces and make sure Indent using spaces is turned on in the same menu. The new versions of Sublime should remember this setting on file type basis.

There are also config files which you can access from Preferences menu, but after many failed attempts and hacking several config files it did me no good. Maybe autodetect was overriding my simply attempt of never use tab.

Map file formats to syntax highlighting

If you a have a file format you want to recognize under a certain highlighter e.g. map ZCML files to XML highlighter.

Open any file of the format.

Then: View > Syntax > Open all with current extension as… ->[your syntax choice].

Image

ZCML, now with full color

More info.

Disable automatic loading of the last session

By default, Sublime Text re-opens all files and folders you had when you closed the editor last time. Some people don’t like this.

Instructions to disable automatic session restore for Sublime Text.

Lint and validate your files while typing

SublimeLinter scans your files on the background when typing using validators and linters for various errors. Please see Configuration section in README as you might need to install additional software, like Node.js, to run some of the linters.

Image

Detect mistypes CSS, yay!

SublimeLinter comes with built-in pylint and has Node’s jshint and csslint packages includes

Add CodeIntel autocompletion support

Install CodeIntel from Package Control.

If you are working with Python projects, using buildout, this recipe comes to handy.

[codeintel]
recipe = corneti.recipes.codeintel
eggs = ${instance:eggs}
extra-paths =
    ${omelette:location}

This will generate .codeintel file inside your buildout folder.

CodeIntel plug-in assumes .codeintel file is in your project root. Simply type

subl .

to open your buildout folder as Sublime project folder.

Now Sublime should support auto-completion. E.g. start typing

from zope.interface import <--- Auto completion pops up here

Image

Also, with CodeIntel, ALT + mouse click takes you the source code of import, or the declaration of any function you click.

CodeIntel also supports PHP, Ruby and Javascript, to name few.

Note: If you are not using buildout, or Python, you can always create CodeIntel configuration file in old-fashioned way.

Go to anywhere shortcut

CMD + P. Type in a part of a filename and a part of a function / rule name. You are there. Very powerful, yet so simple feature.

Image

Go to line shortcut

Use Go To Line functionality CTRL+G for more traditional jumps.

Context sensitive in-file search shortcut

Handy for Javascript, CSS, Python, etc. CMD + R. Type your method or rule name and Sublime automatically jumps into its declaration.

Image

… or in Python …

Image

Edit multiple words or lines simultaneously using multi cursor

This trick is handy if you need to wrap / unwrap stuff in quotes, add commas, add parenthesis etc. on multiple lines or items simulatenously.

First select lines or items. You can select multiple individual words by holding down CMD and double clicking words. For lines you can do just the normal SHIFT selection.

Press SHIFT + CMD + L to activate the multi cursor mode.

Image

Then edit all the entries simultaneously. Use CMD + left and CMD + right etc. to move al the cursors to the beginning or the end of the linen and so on.

Open OS file browser for the currently opened file or any of its parent directories

CTRL + mouse click filename in the title bar of the edit window to show the full path to the file and open any of its parent folder.

Note: This is OSX’s Finder file browser standard behavior and might not work on other platforms.

Image

More powerful sidebar

Install SideBarEnhanchements package to get more menu entries to sidebar which you can use to manage your source folder.

Image

Theme and font

To further enhance readability of your text editing environment

See the results below.

Image

Syncing and back-uping Sublime Text 2 settings and plug-ins with Dropbox

You may want to

  • Save your Sublime Text 2 configuration for which you have spend so many tears to tune it up
  • Sync your Sublime Text 2 configuration across different computers

Here are instructions for syncing and saving Sublime Text 2 settings with Dropbox.

HTML / XML tag tools

No one loves XML sit-ups. XML’ish languages where not intended to be written by hand. Sublime Text provides some pain killers on the matter.

Install Tag from Package Control. It comes handy when you are cleaning up those hard tabs….

Image

Select text and then search from Command Palette (CMD + SHIFT + P): Tag: Auto Format Tags on Selection. Your HTML indent and other weirdness will be cleaned up. You can also configure it for different tag writing style preferences.

There is also built-in HTML: Wrap selection with tag command to insert parent or middle level tags in your HTML source.

Git

Though Sublime’s file explorer doesn’t support fiel state coloring or context sensitive menu  shortcuts like in Eclipse, you still get some Git commands thru kemayo’s git plug-in (from Package Control, again).

Image

Still unresolved

More tips

Translations

This article is translated to Serbo-Croatian language by Vera Djuraskovic from Webhostinggeeks.com.

\"\" Subscribe to RSS feed Image Follow me on Twitter Image Follow me on Facebook Image Follow me Google+