module plugs must have two funcs: init, call
defmodule NothingPlug do
def init(opts) do
optsend
def call(conn, _opts) do
connend
end
go get -u ./...
Get methods
dir(
Get help
help(
identity - location in memory of an object
id() - location in memory
type()
mutable - dict,list
immutable - strings tuples, integers *reassignment changes identity
Dunder methods - Double UNDERscore methods “add” or magic methods
help(object.method)
File iterate through file
with open('somefile','r') as my_file:
for line in my_file:
print(line)
coerce booleans
ex.
bool(0) -> False
bool(4) -> True
singleton - one copy, example None
= None
a = None
b id(a)
id(b)
will be the same value
PEP8 prefer 4 spaces to indent code
define a list names = [‘Evee’,‘Harper’,‘Lily’,‘Linus’]
A for loop ccan have a else clause. Code in the else clause will execute if the for loop did not hit a break statement.
positive = False
for num in items:
if num < 0:
break
else:
postive = True
set default method
count = {}
for name in names:
count.setdefault(name,0)
count[name] += 1
def funcname(arg):
body
stride
every_other_name[0:4:2]
Files
fin = open('etc/passwd')
for line in fin:
print line
with open('/tmp/names.txt','w') as fout:
fout.write('Evee\n')
Using file as seq
def add_numbers(filename):
with open(filename) as fin:
return add_nums_to_seq(fin)
def add_nums_to_seq(seq):
results = []
for num, line in enumerate(seq):
enumerate(seq):
results.append('{0}-{1}'.format(num,line))
return results
Object - grouping together state and methods
Class - define objects
class Animal
generator example
xs = (x for x in range(4))
xs.__next__()
objects store their type in their class attr
type()
issubclass()
isinstance()
dir()
hasattr(
getattr(
prefer EAFP easier to as for forgiveness
globals() - introspect the global namespace
globals()[foo] = ‘bar’ <– globals dict IS the global namespace
locals() - introspect the local namespace
f-strings - PEP 498, ex. f”{name}”
inspect module :wqa
django-admin startproject myproject
python manage.py runserver
python manage.py startapp
python manage.py showmigrations
python manage.py migrate
python manage.py makemigrations
python manage.py sqlmigrate
python manage.py createsuperuser
settings.py - INSTALLED_APPS[] list of apps
urls.py - routing
rule of thumb: each layer powers of 2, decreasing
model performance/deal with over fitting:
use a dropout layer
start with 20 - 30%
will result in more epochs
make more data
for image data
```python
keras.preprocessing.image.ImageDataGenerator(....)
```
example of loading train a test data sets from tf data sets:
= tfds.load('mnist', split='train', as_supervised=True, with_info=True)
mnist_train, info
= tfds.load('mnist', split='test', as_supervised=True) mnist_test
use Keras to retrieve data:
=cache_dir, cache_sub_dir=cache_subdir) tf.keras.utils.get_file(fn, url, cache_dir
read csv using pandas:
import pandas as pd #<-- pd by convention
= ['col1','col2'] # assuming first row in csv is not col names
column_names = pd.read_csv(path_to_csv, name=column_names) some_dataframe
example model layers:
= tf.keras.models.Sequential([
new_model None, 1)),
tf.keras.layers.InputLayer((30,6,padding='casual', activation='relu'),
tf.keras.layers.Conv1D(68),
tf.keras.layers.LSTM(32, activation='relu'),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dense(1)
tf.keras.layers.Dense( ])
https://www.oauth.com/
Used for integrating applictions with other services.
Important ! register redirect url’s immediately.
Redirection attack where a access token can be interpreted by an attacker.
Dont register multiple redirect url’s to compensate for starting from multiple states in the app. Instead use the state parameter.
https://scrimba.com/learn/learnreact
global var ReactDOM
.render(<h1>Hello</h1>, document.getElementById("root")) ReactDOM
All React components must act like pure functions with respect to their props.
Pascal case component, not camel case
Wrap it in angle brackets in ReactDOM.render()
Components can have parent child relationship
function Navbar() {
return (
<div></div>
)
}
function MainContent() {
return (
<div></div>
)
}
.render(
ReactDOM<div>
<Navbar />
<MainContent />
</div>,
document.getElementById("root")
)
Like html with some differences.
html => JSX
class => className
create a react project
-react-app hello npx create
add a router
npm install react-router-dom@6
install material ui: https://mui.com/getting-started/installation/
Use mustache syntax
import React from "react"
import ReactDOM from "react-dom"
function App() {
const userName = "me"
return (
<h1>Hello {userName} !</h1>
)
}
.render(<App />, document.getElementById("root")) ReactDOM
// Somewhat bogus example
export default function Contact(props) {
return (
<div className="contact-card">
<img src={props.image}/>
<h3>{props.name}</h3>
<div className="info-group">
<p>{props.phone}</p>
</div>
<div className="info-group">
<img src="./images/mail-icon.png" />
<p>{props.email}</p>
</div>
</div>
)
}
function App() {
return (
<div className="contacts">
<Contact
image="./images/mr-whiskerson.png"
name="Mr. Whiskerson"
phone="(212) 555-1234"
email="mr.whiskaz@catnap.meow"
/>
<Contact
img="./images/fluffykins.png"
name="Fluffykins"
phone="(212) 555-2345"
email="fluff@me.com"
/>
</div>
)
}
// contrived example from scrimba
= [
jokesData
{setup: "I got my daughter a fridge for her birthday.",
punchline: "I can't wait to see her face light up when she opens it."
,
}
{setup: "How did the hacker escape the police?",
punchline: "He just ransomware!"
}
]
export default function Joke(props) {
return (
<div>
.setup && <h3>Setup: {props.setup}</h3>}
{props<p>Punchline: {props.punchline}</p>
<hr />
</div>
)
}
export default function App() {
const jokeElements = jokesData.map(joke => {
return <Joke setup={joke.setup} punchline={joke.punchline} />
})return (
<div>
{jokeElements}</div>
) }
Do not use the “()” for function call in the JSX
import React from "react"
export default function App() {
function handleClick() {
console.log("I was clicked!")
}
function handleOnMouseOver() {
console.log("MouseOver")
}
return (
<div className="container">
<img
="https://picsum.photos/640/360"
src={handleOnMouseOver}
onMouseOver/>
<button onClick={handleClick}>Click me</button>
</div>
)
}
React.useState()
const [someval,setterFunc] = React.useState(someInitVal)
Converting a Function to a Class
You can convert a function component like Clock to a class in five steps:
1) Create an ES6 class, with the same name, that extends React.Component.
2) Add a single empty method to it called render().
3) Move the body of the function into the render() method.
4) Replace props with this.props in the render() body.
5) Delete the remaining empty function declaration.
In applications with many components, it’s very important to free up resources taken by the components when they are destroyed.
We want to set up a timer whenever the Clock is rendered to the DOM for the first time. This is called “mounting” in React.
We also want to clear that timer whenever the DOM produced by the Clock is removed. This is called “unmounting” in React.
used for side effects ie API calls
https://github.com/pmndrs/react-three-fiber
https://threejs.org/docs/index.html#manual/en/introduction/Creating-a-scene
scene -> camera -> renderer -> attach to canvas
geometry -> mesh -> scene.add()
frustum - A frustum is the name of a 3d shape that is like a pyramid with the tip sliced off. In other words think of the word “frustum” as another 3D shape like sphere, cube, prism, frustum.
mesh = geometry + material + orientation
Example set camera width to canvas
function render(time) {
*= 0.001;
time
const canvas = renderer.domElement;
.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
camera
...
npx create-react-app my-app
cd my-app
npm install three @react-three/fiber
npm install --save husky lint-staged prettier
npm run start
## initialize minimum node project with a minimal package.json
npm init -y
## install a package
npm i <some package>
npm i express
https://datatracker.ietf.org/doc/html/rfc7519
https://www.bezkoder.com/jwt-json-web-token/
https://www.bezkoder.com/react-express-authentication-jwt/
https://blog.galmalachi.com/react-nodejs-and-jwt-authentication-the-right-way
https://jwt.io/introduction/
JWT is typically in header
x-access-token: [header].[payload].[signature]
*** USE HTTPS ***
JWT does NOT secure your data. JWT does not hide, obscure, secure data at all.
The purpose of JWT is to prove that the data is generated by an authentic source.
So, what if there is a Man-in-the-middle attack that can get JWT, then decode user information? Yes, that is possible, so always make sure that your application has the HTTPS encryption.
Browser Server 1) send login(usr,pw) =>
2) create JWT with secret 3) <= return JWT 4) send request with JWT
in header => 5) validate JWT 6) <= return response
Browser: Local Storage
IOS: Keychain
Android: SharedPreferences
Header
Payload
Signature
{
"typ": "JWT",
"alg": "HS256"
}
What is stored in the token
iss: issuer
iat: time issued
exp: expiration
{
"userId": "some user",
"username": "anon",
"email": "anon@anon.io",
// standard fields
"iss": "zKoder, author of bezkoder.com",
"iat": 1570238918,
"exp": 1570238992
}
const data = Base64UrlEncode(header) + '.' + Base64UrlEncode(payload);
const hashedData = Hash(data, secret);
const signature = Base64UrlEncode(hashedData);
https://www.bezkoder.com/node-js-jwt-authentication-mysql/
User Registration
POST api/auth/signup => Check and sve user to db
<= Register successfully message
User Login
POST api/suth/sigin => Authenticate
<= Create JWT string with secret
return {token, user info, authorities}
Access Resource
JWT on x-access-token => Check JWT signature, get user info and authenticate header
<= return content based in authorization
User Login
POST api/suth/sigin => Authenticate
<= Create JWT string with secret
return {token, *refreshToken, user info, authorities}
Access Resources with Expired Token
Request data with JWT => Validate and throw TokenExpiredError in the header
<= Return Token Expired message
Token Refresh
POST api/auth/refreshToken => Verify Refresh Token
<= return {new token, resfreshToken}
program:
a) piece of code that lives on the blockchain
b) programs are stateless
c) programs interact with accounts for data
accounts
a) stores data
b) users can have 1,000s of accounts
Configuring Solana
Install rust
https://doc.rust-lang.org/book/ch01-01-installation.html
Install Solana: https://docs.solana.com/cli/install-solana-cli-tools#use-solanas-install-tool
set Solana network to localhost
```bash
solana config set –url localhost ```
start a local Solana node
solana-test-validator
Install mocha, anchor, npm anchor, npm solana/web3.js
npm install -g mocha
cargo install --git https://github.com/project-serum/anchor anchor-cli --locked
npm install @project-serum/anchor @solana/web3.js
Create a project
anchor init myproject --javascript
Generate local Solana wallet
solana-keygen new
Get public key for local wallet
solana address
```
airdrop sol
```bash
solana airdrop 5 93SAmhpBneKq6UybsFbn5gf9kzAcooCz732bGaGiBehg --url https://api.devnet.solana.com