Please enable JavaScript.
Coggle requires JavaScript to display documents.
Programming (PHP (form (<form action="folderA/aphpfile.php"..…
Programming
PHP
form
<form action="folderA/aphpfile.php"...
Encrypt pass:
$x = password_hash('123',PASSWORD_DEFAULT);
Decrypt: password_verify('123', $x);//1 or 0
Send mail(NOT Gmail):
mail('recei@abc.com
',$subject, $content, 'From: xyz')
Redirect:
header("Location: ../index.php?signup=error")
exit();
if(empty($first_name) || empty($last_name)){...}
Validate:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
//Invalid email address
}
Perform Regex:
if(preg_match_all('/Hoang/', $input_string, $array_result)) {...}
$output_string = preg_match('/Hoang/', $input_string);//1 or 0
/D{2, }/ => Eg: DD, DDD, DDDD,...
/I.*fine/ => Ex: I am fine
/D.*/ => Ex: Daniel, Danish, Duck,...
/[^abc]/ => "NOT" /[abc]/
/[abc]/ => String contains "a" or "b" or "c"
Replace using Regex:
$output_string = preg_replace('/Hoang/', 'John', $input_text);
//Replace 'Hoang' by 'John'
Upload file:
<form enctype="multipart/form-data"...
Button "Choose file":
<input type="file" name="file"... Add more button below: <button name="submit"...>
$file = $_FILES["file"];
print_r($file);
Convert string to array:
explode('.', $file_name);
Last element in an array:
end($names)
Convert string to lowercase:
strtolower($full_name)
Generate a string:
uniqid('', true);
uniqid('Hoang'); //Hoang2a3xjhee...
Shuffle(hoán vị) characters:
$str = "1234abcd!)(";
$random_str = str_shuffle($str);
Find an element in an array:
in_array("Hoang", $names)
Delete a file:
if(unlink('uploads/a.jpg')){...success}
Check: file_exists('uploads/a.jpg')
Find multiple files:
glob('uploads/cat*');
Upload:
move_uploaded_file($tmp, 'uploads/ab.png')
Detail link:
http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI
]
$x = array("Daniel", "Hoang");
$x[0];
Append elements:
$names = array();
array_push($names, "Hoang");
array_push($names, 12, 33);
Associative Array:
$person = array("name"=>"Hoang", "age" => 25);
$person["email"] = "....";
Print an array:
print_r($arrayA);
foreach($persons as person) {...}
mysqli = mysql improved
$result = msqli_query($conn, $sql);
mysqli_num_rows($result) >= 0
Iterate:
while($row=mysqli_fetch_assoc($result)) {...}
Class & Object
class Person {
public $name="";
protected $email;//only access in child class
private salary;
}
class Engineer extends Person {
//Can access $email, $name
}
Define a method/function:
class Engineer... {
public function get_name(){
return $this->name
}
}
Getter:
class...{
public function get_email(){
return $this->name;
}
}
Setter:
class...{
public function set_email($new_email) {
$this->email = $new_email;
}
}
Static property:
class Employee...{
public static $base_salary=10;
}
Access property:
echo Employee::$base_salary;
Static method:
class Employee..{
public static function a_static_method() {
return self::$base_salary * 85/100;
}
}
Call a static method:
Employee::a_static_method();
Print an object:
$person = new Person();
var_dump($person);
Print a property:
echo $person->name;
echo $person->email;//Error access "protected"
Call a method:
$person->get_email();//OR
echo $person->get_email();
Convert an Object to JSON:
$jsonPerson = json_encode($person);
echo $jsonPerson;
Initiate an Object with Contructor:
class Employee {
public function __contruct() {...}
}
Constructor with params:
public function __construct($email, $name) {
$this->email = $email;
$this->name = $name;
}
call a Constructor:
$employee = new
Employee('abc@gmail.com
', "Hoang");
Remove an Object:
unset($objectA);
When an object is removed, this is called:
public function __destructor() {...}
Session: In abc.php
<?php
session_start();
?>
<?php
$_SESSION['isLoggedIn'] = 1;
?>
Remove all sessions:
session_unset();
session_destroy();
Programming
jsp
<jsp:include page="...jsp" />
Cookies
Firefox,menu,preferences,privacy,remove cookies
Ex: select Programming Lang, save Cookies
new Cookie("name", "Hoang");response.addCookie
<a href="file.asp">
request.getCookies(); eachCookie.getName()
Form
Email = ${param.email} or
request.getParameter("email")
Dropdown: <select name="country">
Expression: <%= 3*2 %> :
Scriptlets: <% for(int i=0; i<...) %>
Define functions and variables
<%! int add2Numbers()...%>
<%! int x=50; %>
<%= "x is:"+x%>
Expression Language, no <%%>
xx = ${1+2};${param.email};
Call class:<%= com.abc.ClassA.funcA(); %>
Import: <%@ page import="com.ab;com.xy" %>
JSP Standard Tag Library-JSTL
Add JSTL's .jar to lib
Core: <%@ taglib prefix="c" uri="..."%>
Show string: <c:out value="aa"/>
Fetch Website: <c:import url="http..."/>
<c:forEach items="${persons} var="p">....</c:forEach>
sql: <%@ taglib prefix="sql" uri="..."%>
<sql:setDataSource url="..." var=".."/>
<sql:query ...>select * from ...</sql:query>
function: <%@ taglib prefix="fn" uri="..."%>
Redirect Servlet => .jsp
rd=request.getRequestDispatcher("..jsp");rd.forward(req,res);
Passing params:Servlet=>jsp
Define class, getter, setter
In Servlet: req.setAttribute(person, new Person..)
List: req.setAttribute(persons, new ArrayList...)
Java Beans
public JavaClass, have no-args+custom constructor
implements Serialize, have getter, setter
Use Bean in .jsp file:
First line:
<jsp:useBean id='person' class='example.PersonBean'/>
<%
out.print("person's name is: "+person.getName());
%>
getProperty
First line:
<jsp:useBean id='person'...
Name = <jsp:getProperty property="name" name="person" /><br>
setProperty
In tr, td:
<jsp: setProperty name='person' property='email' value=...>
Servlet
doGet, doPost
PrintWriter out = response.getWriter()
out.println(...)
String email = request.getParameter('email');
Use Bean in "Servlet"
PersonBean personBean = new PersonBean();
personBean.setEmail("hoang@gmail.com
");
Send Bean from Servlet1 => Servlet 2
in Sevlet1:
request.setAttribute("personBean", personBean);
In Servlet2:
PersonBean personBean = (PersonBean)request.getAttribute("personBean");
Link:
http:../projectName/ServletName
<form action="servletName">.., not have .java
Connect MySQL in doPost
Class.forName(com.mysql.jdbc.Driver)
connection = DriverManager.getConnection('jdbc:mysql://localhost:3306/test')
CRUD
Query
ps = connection.prepareStatement("SELECT * FROM...");
rs = ps.executeQuery();
while(rs.next()) {
String name = rs.getString(2);
String email = rs.getString(3);
}
Insert
ps = connection.prepareStatement("INSERT INTO...VALUES(?,?,?)");
ps.setString(1, "hoang");
ps.setString(2,
"hoang@gmail.com
");
status=ps.executeUpdate();
Update, Delete
The same as "Insert":
"UPDATE ...SET name=?, email=?..."
catch(SQLException | ClassNotFoundException e)
Servlet releases 1997
JSP: 1999
Servlets => business logic
JSP => presentation view
JSP Implicit objects
String name=request.getParameter("uname");
response.sendRedirect("
http://www.google.com
");
session.setAttribute("name","Hoang");
Exception page:error.jsp:
<%@ page isErrorPage="true" %>
The exception is: <%= exception %>
SQL Server 2017
Grant Permissions
Security,Login, RC,New Login
Type login name, password
Choose UserMapping, check DB, DB Roles
Set Permissions for a Table:
Choose Table, RC, Properties, Search "users"
Check grant or deny
Login and test permissions
Permissions for columns:
Choose Table, RC, Properties, Search "users"
Open Column Permissions
CRUD = Create Read Update Delete
Insert
INSERT INTO Customers(CustomerName,Address,...) VALUES('Thomas Hardy', '120 Hanover Sq',...);
Insert multiple records(bundle)
INSERT INTO Customers(CustomerName,Address,...) VALUES
('Thomas Hardy', '120 Hanover Sq',...),
('John abc', '334 Xyz Sq',...),
.....;
Create
CREATE DATABASE dbName;
Switch to current Database:
USE dbName;
CREATE TABLE Customers (
CustomerID int NOT NULL IDENTITY PRIMARY KEY,
CustomerName nvarchar(300),
Address varchar(1000));
Create a View
Concatenate a String:
SELECT FirstName+' '+LastName AS 'Full Name'
FROM tblUsers;
SELECT * FROM DbName.viewA;
CREATE VIEW DbName.viewA AS
SELECT * FROM ...
Update
UPDATE Categories
SET Categories.counts=0
WHERE Categories.counts is NULL;
Delete
DELETE FROM Products
WHERE ProductID=15;
DROP TABLE Products;
DROP DATABASE dbName;
Query(Select)
SELECT * FROM Customers;
SELECT TOP 4 * FROM Customers;
How to paging ?
SELECT TOP 10
FROM Customers OFFSET 0 ROWS;
SELECT TOP 10
FROM Customers OFFSET 10 ROWS;
SELECT TOP 10 * FROM Customers OFFSET 20 ROWS;
...
SELECT * from Customers WHERE CustomerName LIKE 'm%';
...WHERE CustomerName LIKE '%john%'
...WHERE CustomerName NOT LIKE '[a-e]%';
...WHERE Country IN ('Brazil', 'Sweden');
"GROUP BY" must have COUNT
SELECT COUNT(ProductID), CategoryID
FROM Products GROUP BY CategoryID
HAVING CategoryID < 7;
Show all tables in your DB:
SELECT * FROM Sys.Tables;
Database's functions
SELECT MAX(Price) as "Highest price" FROM Products;
as "Highest price" => called "Alias"
select Average value
SELECT AVG(Price) as "Average Price" FROM Products;
Calculate total = select SUM
SELECT SUM(Price) as "Sum", COUNT(*) as "Number of Products"
FROM Products;
Join Tables
Categories - Products: 1 - n
SELECT Products.*, Categories.* FROM Products
INNER JOIN Categories
ON Products.CategoryID=Categories.CategoryID
ORDER BY Products.ProductID;
Join many tables
SELECT Table1.*, Table2.*, Table3.* FROM Table1
INNER JOIN Table2 ON Table1.id1=Table2.id1
INNER JOIN Table3 ON Table2.id2=Table3.id2
ORDER BY...;
Backup some data to another Table
SELECT Products.* INTO ProductsBackup FROM Products;
Return JSON values
Copy Result to Notepad and see
Data as "text":
SELECT * FROM Products
FOR JSON AUTO;
Data as "Row":
SELECT ...
FOR JSON PATH;
Constraints
PrimaryKey => ForeignKey
OR 1 => n
ALTER TABLE Products
ADD CONSTRAINT FK_CategoryProduct
FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID);
ALTER TABLE Products
DROP CONSTRAINT contraintName;
Check(Validate value)
ALTER TABLE Products
ADD CONSTRAINT Check_Product
CHECK (Price>=0 AND Price<=2000);
Unique
ALTER TABLE Products
ADD CONSTRAINT UN_Product
UNIQUE (ProductName, Price);
Default value
ALTER TABLE Orders
ADD CONSTRAINT DF_OrderDate
DEFAULT GETDATE() FOR OrderDate;
Trigger
1.After Insert
2.After Update
3.After Delete
CREATE TRIGGER trg_UpdateProduct
ON Products AFTER UPDATE AS
DECLARE @Price AS FLOAT SET @Price = (SELECT TOP 1 Price FROM Products WHERE Price<0)
IF @Price < 0
BEGIN RAISERROR ('Cannot update negative Price',16,10);
ROLLBACK
END
CREATE TRIGGER ....
...select CategoryID from deleted
....select CategoryID from inserted
....select CategoryID from updated
Delete a trigger:
DROP TRIGGER triggerName;
Procedure
Procedure is a "function"
error
Procedure with "output" parameters
CREATE PROCEDURE procedureName
@countX int OUTPUT AS
SELECT @countX = count(*) FROM Products...
Print value ?
PRINT 'Hello world'
Casting values
DECLARE @x as INT;
SET @x = 100;
PRINT 'x = '+cast(@x as VARCHAR);
Error Handling
BEGIN TRY
UPDATE Products SET....;
END TRY
BEGIN CATCH
IF
@@ERROR...
END CATCH;
Do not like
@@ERROR
?
1 more item...
Error number, eg: 5/0
BEGIN TRY
SELECT 5 / 0;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
Call a Procedure ?
EXECUTE searchProducts N'japanese';
EXECUTE procudureName 2,3;
Transaction
A unit of work
BEGIN TRANSACTION transactionName;
INSERT INTO...
INSERT INTO...
COMMIT;
Mark/describe a Transaction
BEGIN TRANSACTION transactionName
MARK N'This will do something...'
...
Rollback
BEGIN TRANSACTION...
INSERT INTO...
ROLLBACK;
--Nothing change !
After commit:
...
COMMIT;
@@TRANCOUNT
Synonyms
Applied for DB Objects:
1.Stored Procedure
2.Table
3.SQL Scalar function
3.View
Scalar functions
Has 1 param, 1 return value
Table-valued functions
Function return a Table:
CREATE FUNCTION TableA.functionA()
RETURN TABLE
AS
RETURN(SELECT ...INNER JOIN...);
ALTER FUNCTION functionB()
RETURN [datetime] AS....
CREATE SYNONYM personName
FOR Customers.name;
React Native
Redux
Libs: redux, react-redux,
Store = a global State
const store = redux.createStore(reducer);
Multi reducers:
const reducers = redux.combineReducers({reducer1, reducer2...})
Reducer:
1.Receive Actions
2.Change oldState => newState
const reducer = (state, action) => {...if(action.type==...)...return newState;}
Dispatcher = someone send an Action
Subscribe: Listen to "State changed"
Provider
<Provider store=...>
<ContainerA />
</Provider>
ContainerA is from ComponentA:
mapStateToProps(stateOfComponentA) {return propOfComponentA}
react-redux.connect(mapStateToProps, mapDispatchToProps)(ComponentA)
Dispatch "Action" => then call Reducer:
mapDispatchToProps(dispatch) {
funcA: () => dispatch({type: 'INCREASE_COUNTER'}),
funcB: () => ...
}
Call actions:
<TouchableOpacity onPress={() => this.props.funcA()} />
<TouchableOpacity onPress={() => this.props.funcB()} />
Init state in Component:
state = {counter: 0}
Flutter/Dart
Installation
Windows
Download SDK, unzip save.Eg: C:\flutterSDK
Set environment variables: ....flutter\bin
MacOS
Download SDK, unzip save.Eg: ~/Documents/flutterSDK
nano ~/.bash_profile
Add path:
export PATH="$PATH: ..../flutter/bin"
flutter doctor
Install and open Android Studio,
New Flutter Project
Fill Flutter SDK Path
Enter your project name, Eg:myapp
Firstly, app runs this file:
lib/main.dart
MyApp is "root widget":
void main() => runApp(MyApp());
MyApp overrides build() function:
class MyApp extends StatelessWidget {
override
Widget build(BuildContext context) {
return MaterialApp(...);
}
}
...return MaterialApp(title:..,home: Scaffold(...))
2 more items...
Install External Packages
Open pubspec.yaml, move below dependencies:
english_words: ^3.1.0
Install package:
flutter packages get
Load images: Open pubspec.yaml
-assets/my_icon.png
Include all:
-assets/
TextAsset
import 'package:flutter/services.dart' show rootBundle;
...
Future<String> x = await rootBundle.loadString('assets/config.json');
Install Xcode and Command-Line tools:
sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
Agree the license:
sudo xcodebuild -license
Python 3
Basic python
Search, filter in a text => Regex = Regular Expression
import re
array_result = re.findall("^The.*Spain<head>quot;, 'The rain is in Spain'))
if(re.search("^The.*Spain<head>quot;, 'The rain is in Spain')):
Dictionaries
Python JSON
Javascript Object Notation
import json
Convert Dictionary to JSON text
json.dumps(person)
Convert JSON Text to Dictionary
person = json.loads('{"name": "Hoang", "age": 30}')
person is now a Dictionary
Mutable
person = {
"name": "Hoang",
"age": 30
}
person["name"] = "Daniel"
check a dictionary has value:
if(len(person) > 0)
Check a key is exists:
if "name" in person:
....
for key, value in person.items():
print(key, value)
Variables, numbers...
for x in range(2,6):
Will print 2 to 5
Show strA[2] to strA[4]:
print(strA[2:5])
Lowercase a string:
print(strA.lower())
strA = " Hello "
print(strA.strip()) #Hello
String's length
len("Hello")
print(strA.replace("H", "J"))
Casting:
x = float("12.35")
Complex:
z = 5 + 10j
Lists, Tuples, Sets
List
fruits = ["apple","banana","orange"]
for fruit in fruits:
print(fruit)
Create a List from tuple
fruits = list(("apple", "banana", "cherry"))
List of Object(Dictionary)
cars = [
{'name': 'Ford', 'year': 2005},
{'name': 'Mitsubishi', 'year': 2000},
]
Sort by "name"
Sort "reverse":
cars.sort(reverse=True,key=lambda eachCar: eachCar['name'])
"void" sort:
cars.sort(key=lambda eachCar: eachCar['name'])
Delete an object
cars = [car for car in cars if car['name'] != 'Ford']
Check "item is in the list"
if "apple" in fruits:
Insert item
fruits.append("cherry")
Remove 1 item:
del fruits[0]
...
fruits.pop()
Remove all items:
fruits.clear()
fruits.insert(1, "kiwi")
"""fruits[1] = "kiwi" """
Tuple
Unmutable
fruits = ("orange","kiwi", "mango")
fruits[0] = "banaba" => not run
Set
Set is "unordered", donot use pop()
fruits = {"orange","kiwi", "mango"}
Remove an item, may raise error:
fruits.remove("kiwi")
Remove an item, NOT raise error:
fruits.discard("kiwi")
Add new Item:
fruits.add("cherry")
Install packages
Windows:
...python_path\python.exe -m pip install package_name
MacOS:
pip install package_name
pip3 install package_name
Custom packages
We have folder PackA
PackA/file1.py
PackA/file2.py
PackA/__init__.py
main.py
__init__.py:
from file1 import f1
from file2 import f2
main.py:
from PackA import *
Class & Object
Definition
class Person:
"""constructor"""
def __init__(self, name):
self.name = name
"Private" variable:
class Person:
__x = 10
Static variable:
class Person:
base_salary = 10
Static method:
class Database:
staticmethod
def get_instance():
instance method:
class Person:
def walk(self, km):
...
Inheritance
class HybridCar(ElectricCar,GasolineCar ):
PostgresDB
After installing, set superuser's password
Superuser's name = postgres
Select Locale
Open SQLShell(or psql),
login with postgres account
CREATE DATABASE ...
List DBs : \l
Connect DB:
\c DBName
"Master" DB = postgres
Exit psql: \q
Display tables:
\d
ALTER TABLE
"description" has NO values
ALTER TABLE Products
DROP COLUMN description;
ALTER TABLE Products
ADD COLUMN description VARCHAR(200);
Constraints
CREATE TABLE Products(
productId INTEGER NOT NULL PRIMARY KEY,
//productId SERIAL PRIMARY KEY, //auto increment
categoryId INTEGER REFERENCES Categories(categoryId ),
....);
ALTER TABLE Products
ADD CONSTRAINT PK_ProductId
PRIMARY KEY(productId);
ALTER TABLE
DROP CONSTRAINT PK_ProductId;
In 1-n relationship, delete (1), (n) is DELETED:
...ON DELETE CASCADE
In 1-n relationship, delete (1), (n) NOT delete if exist data
CREATE TABLE Products(...
categoryId INTEGER REREFENCES Categories(CategoryId) ON DELETE RESTRICT
CREATE TABLE Products(..
,UNIQUE(productName, price));
CREATE TABLE Products(...
,price NUMERIC NOT NULL CHECK(price > 0));
Paging with LIMIT & OFFSET:
SELECT * FROM Products LIMIT 5 OFFSET 1 x 5;
Table with JSON data:
CREATE TABLE jsonPersons(
id INTEGER,
personDetail JSON);
Insert JSON data:
INSERT INTO jsonPersons
VALUES(1, '{"name": "Hoang", "address": {"city": "Ha noi", "pinCode": "123"}}')
SELECT personDetail
FROM jsonPersons->'address'->>'city'
WHERE ...
Open PgAdmin, RC, connect, enter password
Python DB API, connect Postgres Version 2
psycopg2
Connect DB:
connection_string = "dbname='..' user=...host..password...port='5432'"
connection = psycopg2.connect(connection_string)
cursor = connection.cursor()
CRUD
(Create, Read, Update, Delete)
Prevent "SQL Injection"
sql = """INSERT INTO Products(productName, price, description)
VALUES(%s, %s, %s);"""
cursor.execute(sql, ("iphone X", 732.3, "This is good"))
connection.commit()
Query:
sql = "SELECT * FROM Products WHERE productName LIKE %s"
cursor.execute(sql, ('ipho', ))
cursor.fetchall() #an array
What about UPDATE, DELETE ?
A Class with Database methods:
Let's use Singleton Pattern:
One Class -> one Object
class DBManagement:
instance = None
staticmethod
def get_instance():
if DBManagement.
instance == None:
DBManagement.
instance = DBManagement()
return DBManagement.
instance
def
init
(self):
self.connection = ...
...
PyQt5 - Python for GUI Application
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
QWidget is a "window":
self.window = QWidget()
Methods:
1.resize(w, h)
2.setWindowTitle('Abc App')
3.show()
4.setLayout(layoutX)
1 "window" has 1 "layout"
Layout vertically, horizontally:
QVBoxLayout, QHBoxLayout
1.setSpacing(10)
2.setAlignment(..)
3.addLayout(vbox1)
4.addWidget(txtEmail)
5.addStretch(9) => add more space
Basic widgets
QComboBox:
1.addItem('Java')
2.activated["Java"].connect(a_function)
3.currentText()
QLabel
1.QLabel('Hello')
2.resize(w,h)
3.setPixmap(..)
4.setAlignment(..)
Qt.AlignCenter
Qt.AlignLeft
Qt.AlignRight
Show image => QPixmap
1.QPixmap('./logo.jpeg')
2.scaledToWidth(64)
QLineEdit
1.setPlaceholderText('Enter name')
2.setText('abc')
3.text()
4.setEchoMode(QLineEdit.Password)
Strip a text:
...txtEmail.text().strip()
QPushButton
1.QPushButton('Login')
2.setText('abc')
2.clicked.connect(functionA)
3.setFixedSize(QSize(50,50))
If functionA has params, eg: (x,y)
What's happened ?
from functools import partial
...
buttonA.clicked.connect(partial(functionA, x,y))
Alert using QMessageBox
1.setText(''Please enter...)
2.exec_()
Yes/No Question:
reply= QMessageBox.question(self, 'abc',
'Do you love me?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
if reply == QMessageBox.Yes:
QTableWidget
1.setHorizontalHeaderLabels(["Name", "Year"])
2.horizontalHeader().setFixedHeight(40)
3.setRowCount(10)
4.setColumnCount()
5.setColumnWidth(0, 120.0)
6.setItem(rowId,0, QTableWidgetItem('iphone 7')
7.setCellWidget(row,column, a_widget)
QGridLayout
1.setSpacing(10)
2.addWidget(txtEmail, row, column)
Show "root" widget in App:
app = QApplication([])
login = LoginScreen()
app.exec_()
Style sheets
Inline QSS(Qt StyleSheet):
app.setStyleSheet('QPushButton: {margin: 10ex;}')
External QSS:
app.setStyleSheet(open("style.qss", "r").read())
RestFul API => Use Flask
Create somes classes, extends Resource
Each class in a separated .py file
"Global" objects:
app = Flask(__name__)
api = Api(app)
...
"""Start server in port - 5000"""
app.run(port='5000', debug=True)
class ProductApi(Resource):
def get(self, param1):
....
return jsonify(an_object)
def get...
def post...
def put...
def delete...
Routes:
api.add_resource(ProductApi,'/products')
api.add_resource...
Assume param1 = 2
http://localhost
: 5000/products/2
Test Routes using Postman(Chrome)
from flask import *
from flask_restful import *
from flask.ext.jsonpify import jsonify
Odoo
odoo-bin scaffold modelName projectPath
0.0.0.0:8069, create Database
Search ModelName in 0.0.0.0: 8069,Apps,
views
customer.xml
models
models.py
Config pycharm: script: odoo-bin,
script params: odoo.conf,
Project interpreter: python 3.5
Create odoo.conf
Dart
Variables
Divide and get integer result:
final x = y ~/ 2;
int x = 0;
var y = 100;
Convert string to double:
double.parse('1.3')
Convert double to String:
3.1416.toStringAsFixed(2);
String template
int x = 10;
'sum = $x';
strA.toUpperCase()
Multiline:
"""This is line1
and line2"""
Raw string:
var s = r'abc \n aaa'
print('x = ${await functionA()}');
try {x = await doSomething();} catch(e) {....}
List
_persons.add(...)
Add many object:
_persons.addAll(...);
Generate a List
var products = List<Product>.generate(30, (i) => Product(name:"", year:...))
print(products.length)
A list of Object:
final _persons = <Person>[];
Maps
var person = <String, String>{'name': 'Hoang', 'email':
'hoang@gmail.com
'};
var views = Map<int, Widget>();
Packages and Libraries
Import everything in a file:
import 'package:...libA.dart' as libA
libA.Person
import something:
import 'package:..libA.dart' show functionA;
Lazy(import when using) loading:
import '...' deferred as functionA;
Functions
Function as a variable
"No params" function:
final VoidCallback onPressed;
Function with params:
typedef void AddNewProductCallback(Product product);
final AddNewProductCallback onAddProduct;
...
void onAddProduct(...) {...}