over 2 years ago

Use Jquery to get DOM elements

React.js injects code into HTML block like this:

React.render(
    <EditorForm />,
    document.getElementById('content)
);

To use Jquery to accomplish the samething:

React.render(
    <EditorForm />,
    $("#content")[0]
);

$("#content") along is not enough, because it returns a jquery object instead of a DOM object.

Why does React.js render function's return statement is surrounded by a parenthese?

This is because JavaScript does automatic semicolon insertion

When the following line is entered:

var test = 'str1'
           'str2'
           'str3';

The output is not an error, but instead str1 is assigned to variable test. This is because a semicolon has been inserted by js automatically like this:

var test = 'str1';

When working with React.js, this is what a typical render() looks like:

    return (
        <div className="form-group hovering-textarea-container">
            <input className="form-control input-lg" type="text" />
        </div>
    );

To make sure the entire div block is returned as a whole instead of just the first line, the parenthese are needed.

 
over 2 years ago

The following ST3 plugins are need for React development:

  1. babel - for jsx syntax highlighting
  2. sublime-jshint - for linting your js code
  3. sublime-jsxhint - for linting your jsx code

Install babel

This one is very straight forward, just find babel in package control and install it. To use the Babel's JSX syntax highlight whenever a .jsx file is opened:

  • open up a .jsx file in ST3
  • Goto 'View -> Syntax -> Open all current extention as ... > Babel > Javascript (Babel)'

Linting JSX

I have written a blog about Linting react code here. Follow the instructions in that blog, it will give you real time linting as you code in sublime.

Install React Chrome plugin

Install this plugin if you use Chrome for development, go to this link and install.

Once installed, open up Extensions find the React plugin and check the Allow access to file URLS. This is important if you want to test React files locally.

If you have a webpage using React opened, such as this page, an extra tab named React should appear in your Developer Tools

Convert JSX files to JS files

React uses a syntax called JSX. To use it in your webpage, you have to convert it to regular JS format first. There are two ways to do it:

  1. Use the 'JSXTransformer.js' (which comes with React.js download) to do the conversion
  2. Use the 'react-tools' npm package to perform the conversion

Which one should you choose?

If you want to write your JSX code inside the HTML page, then use JSXTransformer.js like this:

<html>
<body>
    <script src="js/vendor/react.min.js"></script>
    <script src="js/vendor/JSXTransformer.js"></script>

    <script type="text/jsx">
            ...React code inside...
    </script>
</body>
</html>

This is good for debugging but not good for production. Because compiling from .jsx to .js takes time, you want to precompile the .jsx files to regular .js files before serving them to your customers.

So, how to compile .jsx files?

Install the 'react-tools' package via npm:

npm install -g react-tools

Once finished, go into your dev directory and use this command:

Assuming this is the structure of your dev directory

dev_dir/
    js/ 
        src/
        build/
cd dev_dir/js
jsx -w src/ build/

This command means watching all .js files inside the src folder and compile them if modified to regular .js files and save them to the build folder.

WARNING: This command works only if you saved the JSX files with .js extension, if you saved your JSX files with the .jsx extension, then you need to use this command:

jsx -x jsx -w src/ build/

If the command has been executed successfully, you should see a message like this:

built Module("your_js_or_jsx_filename")
["your_js_or_jsx_filename"]

You can import the compiled js files like this (without the need of JSXTransformer.js):

<html>
<body>
    <script src="js/vendor/react.min.js"></script>
    <script type="text/javascript" scr="js/build/precompiled.js"></script>
</body>
</html>

XMLHttpRequest cannot load

Just when you thought you can import a .jsx file like regular .js file locally like this:

<html>
<body>
    <script src="js/react.min.js"></script>
    <script src="js/JSXTransformer.js"></script>

    <script type="text/jsx" src="react_module.jsx"></script>
</body>
</html>

You will see an error in Chrome's console: XMLHttpRequest cannot load, this is because the JSXTransformer.js loads jsx files via XHR which is prohibited for local files.

There are a few ways to overcome this problem which is explained in the StackOverflow link above, but the easiest way to deal with it is to precompile your .jsx files into regular .js files and import them. (which has been explained in the previous section)

A very good React tutorial link

Reactjs Introduction for People Who Know Just Enough JQuery to Get by

This is about it to kickstart your React project using ST3.

 
over 2 years ago

There are a few services that enable you to create responsive HTML email if you don't know how (with a price tag):

If you know how to write HTML & CSS, you might think writing a responsive HTML email would be simple. WRONG !!! There is reason why such services exists. How to make sure your email look the same on ALL email clients is the first & most difficult problem you will run into. Have a look at this test page provided by Email on Acid

I attempted to write a simple responsive HTML email with the following feature:

  1. Have an banner image on the top
  2. The rest of the body is just text

I found this tutorial and followed it, the first thing I noticed is that:

Everything should be inside a table tag

Because mail clients like outlook would ignore a few important CSS properties: background-image, float, margin and display.reference here

CSS Style in the header section will be ignored

You have to use inline style for all of the elements. MailChimp is really nice because they provides a tool to convert all styles inside the header section to inline style.

I don't know how to reference image files

You can add the image as attachment but I have no idea how to get a reference id to that attachment. So I had to upload the image to a web server (or to your dropbox and make it public).

Outlook makes my image unresponsive

Depending on how you send the email, outlook may add the width and height of the image file to the image tag's style. This makes the image unresponsive. To overcome this problem, do this:

<head>
    <style type="text/css" media="screen">
        body.outlook img {
          width: 100% !important;
          max-width: 100% !important;
        }
    </style>
</head>

Then, in your body tag:

<body class="outlook">
    ...

Once the fix is applied, Outlook will not ignore the style in the head section anymore.

Validate your HTML using W3C's validator

Link to W3C's HTMl validator

How to send HTML mail using Mac's Mail app?

  1. Open your HTML file locally in Safari
  2. Press 'command + i' (now the Mail app should pop up with the HTML content in it)
  3. Send it

DO NOT use 'command + a' to select the entire HTML page and copy and paste it into the Mail app. This works, but during this process, certain css attribute will be changed and you are likely to lose the responsiveness of your site!

This is only the beginning of the headaches. After you overcome the compatibility issure, you have to think about spam. Will your mass email pass the spam filter is another tricky topic.

I can see why you may want to pay for those email services now.

 
over 2 years ago

When you have large number of models, it is eaiser to understand their relationships by looking at a graph, Django extensions has a handy command to convert these relationships into an image file:

  1. Install Django extension by:
pip install django-extensions

 2. Enable Django extensions in your settings.py:

  INSTALLED_APPS = (
    ...
    'django_extensions',
  )

 3. Install graph packages that Django extensions relies on for drawing:

pip install pyparsing==1.5.7 pydot

 4. Use this command to draw:

./manage.py graph_models -a -g -o my_project_visualized.png

For more drawing options, please refer to the offical doc.

 
over 2 years ago

To writing Markdown in Sublime Text 3, two plugins are needed to:

  1. Enable Markdown syntax highlighting
  2. Convert Markdown document to HTML and preview it in a web browser

To accomplish these, install these two plugins:

  1. Markdown Editing: This plugin enables syntax highlighting for standard Markdown, Github Flavoured Markdown(GFM) and MultiMarkdown

  2. Markdown Preview: as the name suggests, it converts your MD file to HTML and opens it in your system default browser

  3. LiveReload(optional): This is a standalone plugin (i.e. has nothing to do with Sublime Text 3) that automatically refreshes a webpage if its source (HTML,CSS,JS, etc.) has changed. With this plugin, you don't have to click on refresh or F5 everytime you make changes in the Markdown document.

How to use these plugins:

  • Markdown Editing: once installed, open a Markdown document, set the syntax to either Markdown, GFM, or MultiMarkdown by either click at the bottom right corner and select or use command + shift + p > Set Syntax: Markdown

  • Markdown Preview: once installed, open a Markdown document, press ** Command + Shift + p ** > Preview in browser > select the markdown option (You will see two options presented here. GitHub or Mardown. The github option means to use Github's online API for parsing the MD file, this can take sometime due to your connection speed. It also has a 60 calls/day limitaion. But the upside is you get a GFM with syntax highlighting and EMOJI support for free)

If selecting parser becomes anonying everytime you preview a MD file, you can always set a hotkey in your Keybindings - User file:

{ "keys": ["alt+m"], "command": "markdown_preview", "args": {"target": "browser", "parser":"markdown"} },


A "better" alternative: Github has released a text editor named Atom. It looks and works almost exactly like Sublime Text (most of the hotkeys are the same too). The best part is that it is FREE.

The reason I mentioned it is because Atom offers default Markdown support. It can open a split window with your MD file on the left and a live HTML preview on the right all in the text editor. There is no need to install any plugins or opening the web browser.

 
over 2 years ago

To following up on my previous post on the essential settings for Sublime Text 3, I would like to layout a few non-essential but useful settings:

Change cursor style

Set the caret_style property to change cursor style:

"caret_style": "phase", // change cursor's blink style from on -> off to fade in -> fade out

Other caret styles can be used:

  • smooth (this is the default)
  • blink (I cannot tell the difference between this and smooth)
  • wide (the cursor width is wider and it does not blink)
  • solid (the cursor does not blink and stays "solid")
  • phase (fade in / fase out effect, very subtle)
Make cursor wider

If you just want the cursor to be wider but still blinks, use this

"wide_caret": true,
"caret_style": "blink",
Show ruler

To display a vertial ruler:

"rulers": [80, 120] // this will display two vertical rulers at 80 and 120 character count

You can word wrap at specific character count:

"wrap_width": 80 // default is 0

Read more here

Highlight the line where cursor is at
"highlight_line": true
Save all files when tab out to another Window

When you alt+tab to another window, saves all the files opened in Sublime:

"save_on_focus_lost": true,
Turn on spell checker
"spell_check": true, 
Visualize all whitespace characters
"draw_white_space": "all"

Available options are:

  • none
  • all
  • selection
Antialiasing Font for Retina Display

Try this option if you are on a retina display:

"font_options": ["gray_antialias"],
Always show code folding icon

The folding icon is only shown on hover by default, you can change it to always appear:

"fade_fold_buttons": false,
A handy website for generating setting file

http://eduardolopes.github.io/sublime-config/

 
over 2 years ago

Sublime Text is great, but a few settings should be enabled as default to make the experience even better. Open your user setting file by pressing command + , on Mac or ctrl + , on windows. Or go to Preferences -> Settings - User:

TL;DR: just copy and paste the following chunk into your user setting file:

"always_show_minimap_viewport": true,
"indent_guide_options": [ "draw_normal", "draw_active" ],
"line_padding_bottom": 3,
"line_padding_top": 3,
"highlight_modified_tabs": true,
"scroll_past_end": true,
"translate_tabs_to_spaces": true,
"find_selected_text": true,
"word_wrap": true,
"ensure_newline_at_eof_on_save": true,
"bold_folder_labels": true,

and the following to Preferences -> Key Bindings - User:

{ "keys": ["command+v"], "command": "paste_and_indent",},
{ "keys": ["command+shift+v"], "command": "paste",},


Got 5 mintues to read?

Show current location on minimap

By default, the minimap does not highlight your current location. Use this setting to turn it on:

"always_show_minimap_viewport": true,
Convert tabs to spaces

It is import to convert tabs to white spaces when coding in Python, Ruby, YAML etc. To do that:

"translate_tabs_to_spaces": true,

Indentation by 4 spaces or 2 spaces depend on the language, it is better off to set the tab_size property separately for different file types. For instance, if I code in Python, I want the tab size to be 4 spaces. If I code in Ruby, I want it to be 2. To do this,

  1. Open a new document and click the bottom right corner (which says Plain Text) and set the language type to Python for instance
  2. Go to Preferences -> Settings - More -> Syntax Specific - User
  3. A file named ** Python.sublime-settings ** should be opened

Add the following lines:

{
    "tab_size": 4,
}
Enable word wrap
"word_wrap": true,
Find highlighted text

When you have a phrase highlighted and press command + f to look it up in the document, the highlighted word is not automatically copy and pasted to the Find dialog box. This can be fixed by:

"find_selected_text": true,
Scroll past the end of the document

It is sometimes awkward to look at lines at the bottom of the screen. You can actually scroll the windows pass the last line of the document:

"scroll_past_end": true,
Highlight indentation level

When writing in a language that requires multiple levels of indentations (like Python), highlighting the current indentation the cursor is in makes finding yourself within the nested code structure easier:

"indent_guide_options":
 [
     "draw_normal",
     "draw_active"
 ],

You can find a screenshot of this on Wes Bos' blog.

Adjust line height to increase readability

The default line height is too narrow for the eyes. Change it to a number that looks more comfortable:

"line_padding_bottom": 3, // adjust the number as you like
"line_padding_top": 3,
Highlight tabs with unsaved changes
"highlight_modified_tabs": true,
Ensure newline at end of file on save

UNIX/Linux convention is to have a newline at the end of the file. When collaboration with people using different OS, this is important:

"ensure_newline_at_eof_on_save": true,

WARNING:
You may attempt to set this as well:

"trim_trailing_white_space_on_save": true

But this can be hazardous if you write in Markdown. Because two trailing white spaces in Markdown means a newline character. A workaround proposed by this blog is to set the setting to True in the user setting file and set it to false in the Mardown syntax file.

Make folder name bold in the sidebar
"bold_folder_labels": true,


Paste code without having to fix indentation

This is definitely an annoying issue that everybody encounters all the time. When you copy and paste a block of indented code, the indentation on certain lines of the copied code is guaranteed to be messed up.

Sublime Text acutally has an Paste and Indent option which fix this issue but it is bind to command+shift+v instead of command+v. To fix this, Open Preferences -> Key Bindings - User and paste the following lines:

{ "keys": ["command+v"], "command": "paste_and_indent",},
{ "keys": ["command+shift+v"], "command": "paste",},
References:

http://stackoverflow.com/questions/25900954/80-characters-right-margin-line-in-sublime-text-3
https://www.sublimetext.com/forum/viewtopic.php?f=2&t=2478
http://wesbos.com/sublime-text-5-visual-tweaks/
http://sublime-text-unofficial-documentation.readthedocs.org/en/latest/reference/settings.html

 
over 2 years ago

Run the following command to copy the Packages and Installed Packages folder to your dropbox.

mkdir $HOME/Dropbox/sublime-text-3/
mv "$HOME/Library/Application Support/Sublime Text 3/Packages" "$HOME/Dropbox/sublime-text-3/"
mv "$HOME/Library/Application Support/Sublime Text 3/Installed Packages" "$HOME/Dropbox/sublime-text-3/"

Then, on a different computer, remove its Packages and Installed Packages folder and make a symbolic link to the copies in the Dropbox folder.

DSTPATH="$HOME/Library/Application Support/Sublime Text 3"
DROPBOX_PATH="$HOME/Dropbox/sublime-text-3"
rm -rf "$DSTPATH/Installed Packages"
rm -rf "$DSTPATH/Packages"
mkdir -p "$DSTPATH"
ln -s "$DROPBOX_PATH/Packages" "$DSTPATH/Packages"
ln -s "$DROPBOX_PATH/Installed Packages" "$DSTPATH/Installed Packages"

seen on: http://www.hongkiat.com/blog/sublime-text-tips/

 
over 2 years ago

After updating pip using pip install -U pip,

$ pip
/usr/bin/pip: No such file or directory

pip can no longer be found:

$ which pip
/usr/local/bin/pip

$ pip
-su: /usr/bin/pip: No such file or directory

$ type pip
pip is hashed (/usr/bin/pip)

So pip is definintely in /usr/local/bin/pip but it is been cached as in /usr/bin/pip, thanks to the Stackoverflow question, the solution is very simple:

$ hash -r

When the cache is clear, pip is working again.

 
over 2 years ago

Linters are used to highlight syntax and style errors in your source code. It is very useful to have when writing python, js, css, YAML, etc.

To enable linting in Sublime text 3, a few things need to be installed to get it working.

1) Install Sublime Linter first. This is a framework rather than an actual linter that can inspect your code. When we install other linters, they will depend on this framework. Thus, it is important to install this 'mother base' first.

  - open up package control, cmd+shift+p on Mac OS X, ctrl+shift+p on Linux/Windows
  - type 'install' and select 'Package Control: Install Packages' 
  - type 'SublimeLinter'

2) Install pep8 and pyflake. These python libraries will be used by the linters installed in the next step. Open up a console window, and install them by:

pip3 install pep8 pyflakes

The pep8 package is for style checking and pyflakes is for syntax error checking.

NOTE: make sure you are not installing these packages while using virtualenv. This is the mistake that I made. These pacakges need to be available system wide.

3) Install the actual linters: Sublime Linter-pyflakes, Sublime Linter-pep8:

  • open up package control, cmd+shift+p on Mac OS X, ctrl+shift+p on Linux/Windows
  • type 'install' and select 'Package Control: Install Packages'
  • type 'pep8' and find 'SublimeLinter-pep8'
  • type 'pyflakes' and find 'SublimeLinter-pyflakes'

4) After everything has been installed, restart sublime text 3

5) Now you should see error highlights in the gutter and around the code. To set when linting should be active, right click anywhere in Sublime Text 3 and select 'SublimeLinter' > 'Lint Mode'

6) It is very likely that pep8 will point out a few styling errors. It is anonying to fix them by hand. We can use another plugin to autoformat python code for us. Install Python PEP8 Autoformat via package control.

After this is installed, press 'ctrl + shift + r' to perform auto format.

7) pep8 linter is likely to complain about using 4 spaces instead of tabs when writing Python code. You can change this in Sublime's setting File. Go to 'Sublime Text > Preferences > Settings - User', add the following lines:

"tab_size": 4,
"translate_tabs_to_spaces": true,

Now, when the tab key is pressed, 4 spaces are inserted instead.