2.12.2017

Angular Cheat Sheet


Creating Components

import { Component } from '@angular/core'
@Component({
 selector: 'courses',
 template: '<h2>Courses</h2>'
})
export class Component { }

Then, register them in AppModule (or the module the belong to):

@NgModule({
 declarations: [CoursesComponent]
})
export class AppModule { … }

Using Components

import { CoursesComponent } from './courses.component'
@Component({
 template: '<courses></courses>'
})

Templates
Interpolation syntax:
{{ title }}

Displaying lists:
<ul>
 <li *ngFor=“let course of courses”>
 {{ course }}
 </li>
</ul>

Services

import { Injectable } from '@angular/core';
@Injectable()
export class CourseService {
}

Dependency Injection

Register a service as a provider in AppModule (or the module it belongs to):

@NgModule({
 providers: [CourseService]
})
export class AppModule { … }

Then, inject it into the constructor of the components that need it:

export class CourseComponent {
 constructor(courseService: CourseService) {}
}

Directives
Basic structure
import { Directive } from '@angular/core'

@Directive({
 selector: '[autoGrow]',
 host: {
 '(focus)': 'onFocus()',
 '(blur)': 'onBlur()'
 }
})
export class AutoGrowDirective {
 onFocus() { … }
 onBlur() { … }
}

To access and modify DOM elements

import { ElementRef, Renderer } from '@angular/core'

export class AutoGrowDirective {
 constructor(
 private el: ElementRef,
 private renderer: Renderer) {
 }
 onFocus(){
 this.renderer.setElementStyle(this.el.nativeElement,
 'width', '200');
 }
}

Registration

Once you implement a directive, you should register it in AppModule (or the module it belong to):

@NgModule({
 declarations: [AutoGrowDirective]
})
export class AppModule { }

Angular Bindings

Interpolation
<h1>{{ title }}</h1>

Property binding
<img [src]="imageUrl" />
<img bind-src="imageUrl" />

Class binding
<li [class.active]="isActive" />

Style binding
<button [style.backgroundColor]="isActive ? 'blue' : 'gray'">

Event binding
<button (click)="onClick($event)">
<button on-click="onClick($event)">

Two-way binding
<input type="text" [(ngModel)]="firstName">
<input type="text" bindon-ngModel="firstName">

Input Properties
Using @Input annotation
import { Input } from ‘@angular/core’;
@Component(…)
export class FavoriteComponent {
 @Input(‘is-favorite’) isFavorite = false;
}

Using component metadata
@Component({
 inputs: [‘isFavorite:is-favorite’]
})
export class FavoriteComponent {
 isFavorite = false;
}

In the host component
<favorite [is-favorite]=“post.isFavorite”></favorite>


Output Properties
Using @Output annotation
import { Output } from ‘@angular/core’;
@Component(…)
export class FavoriteComponent {
 @Output(‘favorite-change’) change = new EventEmitter();

 onClick() {
 this.change.emit({ newValue: this.isFavorite });
 }
}


Using component metadata
@Component({
 outputs: [‘change:favoriteChange’]
})
export class FavoriteComponent {
 change = new EventEmitter();

 onClick() {
 this.change.emit({ newValue: this.isFavorite });
 }
}


In the host component
<favorite (favoriteChange)=“onChange()”></favorite>


Templates
@Component({
 template: ‘…’, // or
 templateUrl: ‘app/template.template.html’
})


Styles
@Component({
 styles: [‘…’],
 styleUrls: [‘…’, ‘…’];
})


Getting Ready for Angular Development


On Ubuntu:

Install nodejs 1. $ sudo apt-get install nodejs 2. $ sudo ln -s /usr/bin/nodejs /usr/bin/node 3. $ sudo apt-get install npm Install typescript 1. $ sudo npm install -g typescript 2. $ sudo npm install -g typings Install angular cli 1. $ sudo npm install -g @angular/cli

On Debian:

$ curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh -o install_nvm.sh $ bash install_nvm.sh $ source ~/.profile $ nvm ls-remote $ nvm install 8.5.0 $ nvm use 8.5.0 $ node -v v8.5.0 $ npm -v 5.3.0 $ npm install -g yarn $ yarn global add @angular/cli $ vi ~/.profile # yarn export PATH="$PATH:`yarn global bin`" $ ng set --global packageManager=yarn $ ng --version @angular/cli: 1.4.3 node: 8.5.0 os: linux x64

On Mac:

I followed this and this Install nodejs 1. Install xcode $ xcode-select --install 2. Install nvm $ curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash 3. Open another bash session to get settings from nvm install 4. List installed node versions $ nvm list 5. Or list from the cloud (last 9 versions) $ nvm ls-remote | tail -n9 6. Install latest $ nvm install 8.2.1 7. Setup this version as default $ nvm use 8.2.1 $ nvm alias default 8.2.1 8. Check node version $ node -v v8.2.1 9. Update npm $ npm install -g npm 10. Check npm version $ npm -v 5.3.0 Install yarn package manager 1. $ npm install -g yarn Install angular cli 1. $ yarn global add @angular/cli@1.2.7 2. Check version $ ng --version @angular/cli: 1.2.7 node: 8.2.1 os: darwin x64 3. Globally config angular-cli to use yarn $ ng set --global packageManager=yarn Test scaffold first angular app 1. $ ng new hello-world-app 2. Start server $ cd hello-world-app $ ng serve 3. Browse http://localhost:4200 Setup IDE 1. Install Visual Studio Code

12.21.2016

Get VirtualBox VM to use host's DNS

From here and here

1. Find out vm name:
c:\Program Files\Oracle\VirtualBox> VBoxManage list runningvms

2. Turn on resolver:
c:\Program Files\Oracle\VirtualBox> VBoxManage modifyvm "VM name" --natdnshostresolver1 on

11.03.2016

Install Python 2.7 and Python 3.5 alongside Python 2.6 on CentOS 6.5

I got mostly from this post.
Install Python 2.7 and Python 3.5 alongside Python 2.6 on CentOS 6.5

1. Prep
# yum groupinstall "Development tools"
# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel

2. Compile as shared library - add /usr/local/lib on /etc/ld.so.conf
# vi /etc/ld.so.conf
include ld.so.conf.d/*.conf
/usr/local/lib
# ldconfig

3.  Install python on  /usr/local
# Python 2.7.12:
wget http://python.org/ftp/python/2.7.12/Python-2.7.12.tar.xz
tar xf Python-2.7.12.tar.xz
cd Python-2.7.12
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared 
make && make altinstall

# Python 3.5.2:
wget http://python.org/ftp/python/3.5.2/Python-3.5.2.tar.xz
tar xf Python-3.5.2.tar.xz
cd Python-3.5.2
./configure --prefix=/usr/local --enable-shared
make && make altinstall

4. Run ldconfig again
# ldconfig

5. Install python virtualenv
# yum install python-virtualenv

6. Create virtualenv for python2.7
$ mkdir project_home
$ cd project_home
$ virtualenv -p /usr/local/bin/python2.7 .venv2.7

7. Create virtualenv for python3.5
$ mkdir project_home
$ cd project_home
$ pyvenv-3.5 .venv3.5
(this seems to work even though I get an error message:
Unable to symlink '/usr/local/bin/python3.5' to '/auto/home/delacs/python_projects_on_perf_utils/test_project/.venv3.5/bin/python3.5')

10.26.2016

DRF JWT Authentication

i.e., Django REST Framework with JSON Web Token Authentication. Got the solution from here: http://getblimp.github.io/django-rest-framework-jwt/ http://zqpythonic.qiniucdn.com/data/20141006233346/index.html
$ pip install djangorestframework-jwt

In settings.py:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

In urls.py:
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token

urlpatterns = patterns(
    # ...
    url(r'^api-token-auth/', obtain_jwt_token),
    url(r'^api-token-refresh/', refresh_jwt_token)
)

To test:
$ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/
$ curl -H "Authorization: JWT " http://localhost:8000/protected-url/

10.25.2016

Django LDAP Integration

These posts helped me: http://kacperdziubek.pl/python/django-ldap-open-directory-integration/ https://pythonhosted.org/django-auth-ldap/
Install:
$ pip install django-auth-ldap

Then in settings.py, add:
import ldap
from django_auth_ldap.config import LDAPSearch

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'django_auth_ldap.backend.LDAPBackend',
)

AUTH_LDAP_SERVER_URI = "ldap://my.appauth.com" # ip or host name of Open Directory server
AUTH_LDAP_BIND_DN = "CN=Accounts,OU=US Security,DC=corp,DC=com"
AUTH_LDAP_BIND_PASSWORD = "MySecurePassword"
AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=US Users,dc=corp,dc=com",
    ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)")
AUTH_LDAP_CONNECTION_OPTIONS = {
    # make search fast
    ldap.OPT_REFERRALS: 0
}

AUTH_LDAP_USER_ATTR_MAP = {
    "username": "sAMAccountName",
    "first_name": "givenName",
    "last_name": "sn",
    "email": "mail"
}
The mapping above would result into automatically saving the information to the users table.

10.20.2016

Django Notes

1. Backup and seed data using fixtures
# Save data
$ python manage.py dumpdata --format=json myapp > myapp/fixtures/initial_data.json
# Load data
$ python manage.py loaddata vlanapi/fixtures/initial_data.json

2. Open python shell - interactive console
$ python manage.py shell
Python 2.7.12 (default, Jul  1 2016, 15:12:24) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>

3. Start a project
$ django-admin startproject mysite

4. Start initial migration
$ python manage.py migrate

5. Start server
$ python manage.py runserver

6. Create an app
$ python manage.py startapp newapp

7. Create and run a migration
$ python manage.py makemigrations
$ python manage.py migrate