import secrets
jwt_secret_key = secrets.token_hex(32)
423c984f59fff65efcbb055cdcac8f32162db4d8561b3007a6cb80703f86d702
14.17.020.9.02.6.83.2.21.9.41.15.63.7.103.11.6
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counter';
import authReducer from './auth';
const store = configureStore({
reducer: { counter: counterReducer, auth: authReducer },
});
export default store;
store/counter.js:
import { createSlice } from '@reduxjs/toolkit';
const initialCounterState = { counter: 0, showCounter: true };
const counterSlice = createSlice({
name: 'counter',
initialState: initialCounterState,
reducers: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
increase(state, action) {
state.counter = state.counter + action.payload;
},
toggleCounter(state) {
state.showCounter = !state.showCounter;
},
},
});
export const counterActions = counterSlice.actions;
export default counterSlice.reducer;
Component:
import { useSelector, useDispatch } from 'react-redux';
import { counterActions } from '../store/counter';
const Counter = () => {
const dispatch = useDispatch();
const counter = useSelector((state) => state.counter.counter);
const show = useSelector((state) => state.counter.showCounter);
const incrementHandler = () => {
dispatch(counterActions.increment());
};
const increaseHandler = () => {
dispatch(counterActions.increase(10)); // { type: SOME_UNIQUE_IDENTIFIER, payload: 10 }
};
const decrementHandler = () => {
dispatch(counterActions.decrement());
};
const toggleCounterHandler = () => {
dispatch(counterActions.toggleCounter());
};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
{show && <div className={classes.value}>{counter}</div>}
<div>
<button onClick={incrementHandler}>Increment</button>
<button onClick={increaseHandler}>Increase by 10</button>
<button onClick={decrementHandler}>Decrement</button>
</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;
index.js:
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store/index';
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(
<Provider store={store}>
<App />
</Provider>
);
import { createStore } from 'redux';
const initialState = { counter: 0, showCounter: true };
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'increment':
return {
...state,
counter: state.counter + 1
}
case 'increase':
return {
...state,
counter: state.counter + action.amount
}
case 'decrement':
return {
...state,
counter: state.counter - 1
}
case 'toggle':
return {
...state,
showCounter: !state.showCounter
}
default:
return state;
}
};
const store = createStore(counterReducer);
export default store;
Component:
import { useSelector, useDispatch } from 'react-redux';
const Counter = () => {
const dispatch = useDispatch();
const counter = useSelector((state) => state.counter);
const show = useSelector((state) => state.showCounter);
const incrementHandler = () => {
dispatch({ type: 'increment' });
};
const increaseHandler = () => {
dispatch({ type: 'increase', amount: 10 });
};
const decrementHandler = () => {
dispatch({ type: 'decrement' });
};
const toggleCounterHandler = () => {
dispatch({ type: 'toggle' });
};
return (
<main className={classes.counter}>
<h1>Redux Counter</h1>
{show && <div className={classes.value}>{counter}</div>}
<div>
<button onClick={incrementHandler}>Increment</button>
<button onClick={increaseHandler}>Increase by 10</button>
<button onClick={decrementHandler}>Decrement</button>
</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
</main>
);
};
export default Counter;
index.js:
import ReactDOM from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import store from './store/index';
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(
<Provider store={store}>
<App />
</Provider>
);
// shallow clone/copy:
let arr2 = [].concat(arr1);
let arr3 = [...arr1];
let obj2 = Object.assign({}, obj1);
let obj3 = {...obj1};
// deep clone/copy
let obj2 = JSON.parse(JSON.stringify(obj1)); // old approach
let obj3 = structuredClone(obj1); // new approach
When using two equals signs for JavaScript equality testing, some funky conversions take place.
| {{ keys[index1] }} |
|
| {{key}} |
When using three equals signs for JavaScript equality testing, everything is as is. Nothing gets converted before being evaluated.
| {{ keys[index1] }} |
|
| {{key}} |
Note: This row does not match up with any of the rows in the other table.
| {{ key }} |
|
if ({{ key }}) { /* {{ values1[index] ? 'executes' : 'does not execute' }} */ } |
The Free plan lets you run a single non-highly available Redis database with up to 30MB and 30 connections, forever (or as long as you use it)! It lets you run Redis Enterprise Cloud in a selected region across all three major public clouds (Amazon Web Services, Microsoft Azure, and Google Cloud). You can use all available Redis modules: RediSearch, RedisJSON, RedisGraph, RedisTimeSeries, and RedisBloom. Best of all, it’s totally free, no credit card required.
https://redis.com/blog/new-pricing-for-redis-enterprise-cloud/
ssh -i your-key.pem username@(public-ip-address)
sudo vi /etc/ssh/sshd_config
PasswordAuthentication yes
sudo passwd ubuntu
sudo service sshd restart
ssh ubuntu@35.162.225.240
| Heroku | Render | |
|---|---|---|
| Sleeps after | 30 minutes of inactivity | 15 minutes of inactivity |
| Free Tier | 550 dyno hours/month | 750 hours of running time |
| No of apps/services in free tier | 5 | no limitations |
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !store.getters.isAuthenticated) {
next("/login'):
} else if (to.meta.requiresUnauth && store.getters.isAuthenticated) {
next("/home");
} else {
next():
}
});
{
"rules": {
"coaches": {
".read": true,
".write": "auth != null"
},
"requests" : {
"•read": "auth != null",
".write": true
}
}
}
$ composer create-project drupal/recommended-project:9.3.1 my_site_name_dir
This will create a project in 'my_site_name_dir' and automatically executes composer install to download the latest stable version of Drupal and all its dependencies.
Your 'my_site_name_dir' will contain files that should be outside of your web root and not accessible by the web server. The web root will be 'my_site_name_dir/web'.
$ composer require. drupal/php
Clone the below repo
https://github.com/apfromiit/drupal9
and run $ composer install
$ sudo chmod +777 web/sites/default/files
Copy default.settings.php to settings.php
$ sudo chmod +777 web/sites/default/settings.php
Open in browser to complete the setup.
$ sudo chmod 755 web/sites/default/settings.php
Now, adding tags to article will render the article in corresponding page.
We can remove the unwanted blocks by deleting them on the context menu provided on top right corner of every blocks.
import redux from 'redux';
const reducer = (state = { counter: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { counter: state.counter + 1 };
case 'DECREMENT':
return { counter: state.counter - 1 };
default:
return state;
}
};
const subscriber = () => {
const latestState = store.getState();
console.log(latestState);
};
const store = redux.createStore(reducer);
store.subscribe(subscriber);
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
store.dispatch({ type: 'DECREMENT' });
Output:
{ counter: 1 }
{ counter: 2 }
{ counter: 1 }
{ counter: 0 }
I use Angular 4 at work for building a single page application. Today, I faced the problem where I had to use different base paths for router and static assets. Angular makes use of the base href to tell router how to compose navigation URLs. If your application exists at the root, then you can use / as the href value as shown below.
<base href="/">
I wanted to use /users as my application base for router and /public as base for my assets.
If you build the project the Angular project for the production environment using the default values you will get the following index.html generated.
ng build -prod
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SampleNgApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="styles.xxxx.bundle.css" rel="stylesheet"/>
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>
This generated page will not work as it router will use / as base for composing
navigation URLs and static assets will be looked in the current directory.
To solve my problem, I used —-base-href and —-deploy-url options as shown below.
ng build -prod --base-href /users --deploy-url /public
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>SampleNgApp</title>
<base href="/users">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="/public/styles.xxxx.bundle.css" rel="stylesheet"/>
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>
This way I solved my problem.
pip install vulture
vulture --ignore-decorators @app.route <path>
<script src="https://unpkg.com/vue@latest"></script>
<script src="https://unpkg.com/axios@latest"></script>
<div id="app">
{{ message }}
</div>
<script>
App = {
data() {
return {
message: "Hello world!"
}
}
}
Vue.createApp(App).mount('#app');
</script>
web/ with your static website.composer.json with {}composer.lock<app-name>| Category | Problems |
|---|---|
| Peer | 13053 |
| Beginner | 434 |
| Easy | 1359 |
| Medium | 1057 |
| Hard | 469 |
| Challenge | 147 |
| Total | 16519 |
fetch(url)
.then(data => data.json())
.then(data => { console.log(data); })
.catch(error => alert(error));
import hashlib
str2hash = "test"
result = hashlib.sha256(str2hash.encode()).hexdigest()
print("sha256", len(result), result)
str2hash = "test"
result = hashlib.md5(str2hash.encode()).hexdigest()
print("md5", len(result), result)
sha256 64 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
md5 32 098f6bcd4621d373cade4e832627b4f6
Running scripts on your computer is great. Running them automatically is even greater. If you are on a Mac (or
Linux), you can use our good friend crontab, which is a scheduling tool that will run jobs
(scripts) at regular intervals.
You add a job to crontab by editing the job list. A job is specified in the following format (first line):
* * * * * command to execute │ │ │ │ │ │ │ │ │ └─── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0) │ │ │ └──────── month (1 - 12) │ │ └───────────── day of month (1 - 31) │ └────────────────── hour (0 - 23) └─────────────────────── min (0 - 59)
Let's make an example job. I personally use cronjobs to make regular backups of my MySQL databases, so I will show how to set this up to run once a day.
My script is called backup.sh,
and will dump my MySQL database to a zip file. We'll set it to run as a cronjob by editing the job list (with
the nano editor):
env EDITOR=nano crontab -e
Now enter the following and press CTRL+O and CTRL+X to save and exit.
0 12 * * * cd ~/my/backup/folder && ./backup.sh
This will execute the command every day at 12:00, which changes to the folder of the script and runs it. The
double ampersand && allows you to specify multiple commands that will run after each other.
Notice that if your computer is shut down or sleeping at the time, the script will not run until the next day at the specified time.
To see a list of your active crontab jobs, use the following command:
crontab -l
You might get a weird "command not found" error when running your crontab jobs for the first time, even though the script works fine when you run it yourself. That's because crontab executes commands without any of the normal environment variables set up.
To fix this, you can add the PATH in the beginning of your script, so it knows how to find programs like
mysqldump:
#!/bin/sh
PATH=/usr/local/bin:/usr/local/sbin:~/bin:/usr/bin:/bin:/usr/sbin:/sbin
So after you've set up your scripts and everything is honky dory, you might notice that the Terminal suddenly have started sending you e-mails.
If being pen pals with your Terminal isn't your thing, you can disable this behavior by inserting this line at the very top of your crontab file:
MAILTO=""
Presto. Now your jobs will run silent.
Here's a few small snippets which might come in handy:
| Description | Script |
|---|---|
| Execute on workdays 1AM | 0 1 * * 1-5 /bin/execute/this/script.sh |
| Execute every 10 minutes | */10 * * * * /bin/execute/this/script.sh |
| Log output to file | */10 * * * * /bin/execute/this/script.sh >> /var/log/script_output.log 2>&1
|
db.json and commitNote: Changes to db are non persistent. Heroku free dyno would become idle if no api request for 30 minutes. Heroku loads original db on next cold start.
import pandas as pd
df = pd.read_csv("data.csv", low_memory=False)
df.to_json("data.json", orient="records")
print("Done")
JSONPlaceholder is a free online REST API that you can use whenever you need some fake data. It can be in a README on GitHub, for a demo on CodeSandbox, in code examples on Stack Overflow, ...or simply to test things locally.
JSONPlaceholder comes with a set of 6 common resources:
| /posts | 100 posts |
| /comments | 500 comments |
| /albums | 100 albums |
| /photos | 5000 photos |
| /todos | 200 todos |
| /users | 10 users |
Note: resources have relations. For example: posts have many comments, albums have many photos, ... see guide for the full list.
All HTTP methods are supported. You can use http or https for your requests.
| GET | /posts |
| GET | /posts/1 |
| GET | /posts/1/comments |
| GET | /comments?postId=1 |
pip install firebase-admin
Goto Project Settings -> Service Accounts -> Click Generate new private key and save the file as credentials.json
import firebase_admin, json
from firebase_admin import credentials, db
cred = credentials.Certificate("credentials.json")
firebase_app = firebase_admin.initialize_app(cred, {
'databaseURL': 'https://<projectid>-default-rtdb.firebaseio.com'
})
with open("data.json") as json_file:
data = json.load(json_file)
ref = db.reference("sample_key")
ref.set(data)
firebase_admin.delete_app(firebase_app)
import firebase_admin
from firebase_admin import credentials, db
cred = credentials.Certificate("credentials.json")
firebase_app = firebase_admin.initialize_app(cred, {
'databaseURL': 'https://<projectid>-default-rtdb.firebaseio.com'
})
ref = db.reference("sample_key")
data = ref.get()
firebase_admin.delete_app(firebase_app)
{
"rules": {
".read": false,
".write": false
}
}
<picture>
<source media="(min-width: 650px)" srcset="img1.jpg">
<source media="(min-width: 465px)" srcset="img2.jpg">
<img src="img3.jpg">
</picture>
{
"glob": "**/*",
"input": "node_modules/ngx-monaco-editor/assets/monaco",
"output": "./assets/monaco/"
}
app.module.ts:
import { MonacoEditorModule, NgxMonacoEditorConfig } from 'ngx-monaco-editor';
const defaultEditorConfig: NgxMonacoEditorConfig = {
defaultOptions: {
theme: 'vs-dark',
automaticLayout: true,
minimap: {
enabled: false
},
scrollBeyondLastLine: false,
scrollbar: {
vertical: "hidden",
horizontal: "hidden"
}
}
};
Add below to imports:MonacoEditorModule.forRoot(defaultEditorConfig)
Typescript:editorOptions = { language: 'python' };
Template:<ngx-monaco-editor [options]="editorOptions" [(ngModel)]="html"></ngx-monaco-editor>
2. Click on the (+) icon to add an item to the list. Press command+shift+G to open the Go to Folder… dialog, type /usr/sbin/cron and press Enter:
3. Select the cron file and click Open:
That’s it!
Reference: ESLint
| Original Value |
Converted to Number |
Converted to String |
Converted to Boolean |
|---|---|---|---|
| false | 0 | "false" | false |
| true | 1 | "true" | true |
| 0 | 0 | "0" | false |
| 1 | 1 | "1" | true |
| "0" | 0 | "0" | true |
| "000" | 0 | "000" | true |
| "1" | 1 | "1" | true |
| NaN | NaN | "NaN" | false |
| Infinity | Infinity | "Infinity" | true |
| -Infinity | -Infinity | "-Infinity" | true |
| "" | 0 | "" | false |
| "20" | 20 | "20" | true |
| "twenty" | NaN | "twenty" | true |
| [ ] | 0 | "" | true |
| [20] | 20 | "20" | true |
| [10,20] | NaN | "10,20" | true |
| ["twenty"] | NaN | "twenty" | true |
| ["ten","twenty"] | NaN | "ten,twenty" | true |
| function(){} | NaN | "function(){}" | true |
| { } | NaN | "[object Object]" | true |
| null | 0 | "null" | false |
| undefined | NaN | "undefined" | false |
| EC2 - CodeStar | Lambda - CodeStar | Lambda - Chalice | Lambda - Serverless | Lambda - Zappa |
|---|---|---|---|---|
| Uses EC2 instances | Uses AWS Lambda and API Gateway | Uses S3, AWS Lambda and API Gateway | ||
| Can run in local environment | Cannot run in local environment | Can run in local environment | Cannot run in local environment | Can run in local environment |
| Cheapest config: Free tier - t2.micro - 1 vCPU - 1 GB Memory - 8 GB EBS | Cheapest config: 128 MB Memory | |||
| Based on Servers installed in EC2. For Eg: Python Flask or Node | Serverless. Based on lambda functions and layers | Serverless. Based on lambda functions and layers. Uses Chalice micro framework | Serverless. Based on lambda functions and layers. Uses Serverless framework | Serverless. Based on lambda functions and layers. Uses Zappa micro framework |
| Supports Python, Nodejs, etc | Supports Python | Supports Python, Nodejs, etc | Supports Python | |
| Supports Flask and Flask-Restful | No support for Flask | Flask like routing | No support for Flask. | Supports Flask. Seems not supporting Flask-Restful |
| Flask file structure | No specific file structure | Multi file structure using blueprints | Single file structure | |
| 1 EC2 + 1 Code Pipeline | 1 Lambda Function + 1 Code Pipeline | 1 Lambda Function | 1 Lambda Function for each route | 1 Lambda Function |
| t2.micro: 1GB | Default Memory: 128MB | Default Memory: 128MB | Default Memory: 1024MB | Default Memory: 512MB |
| Dependency added using pip and build scripts | Dependency added using pip and lambda layers | Dependency added using requirements.txt and lambda layers | Dependency added using yml | Dependency added using virtual env |
| Available when EC2 is on | 24x7 | |||
| Dynamic IP or URL. Static IP is billed. |
No dynamic IP or URL. Free Static URL. |
|||
| 750 EC2 hours/month free. 30 GB EBS free. |
1 Million request/month free. 3.2 Million exec seconds/month free. |
|||
| Free tier for 1 year. | Lambda: Free tier for ever. API Gateway: Free tier for 1 year. |
|||
| Suitable for complex REST based Web Services and Web Apps. | Suitable for simple web services and static Web Apps. Best for demo or hobby use. Not suitable for apis with low level dependencies. |
|||
| No limitation on api execution time | Lambda time limit: 15 minutes API Gateway time limit: 30 seconds |
|||
| Runs over http | Runs over https | |||
| Restful APIs. Flask routing. | Functions mapped as APIs | Restful APIs. Flask like routing. | Restful APIs. Routing in yml | Restful APIs. Flask routing |
| Trivial stand alone APIs are not recommened. | Advanced or complex or low level implementations are not recommended. | |||
declare const PR: any;
ngAfterViewChecked() {
PR.prettyPrint();
}
Styles:
li.L0, li.L1, li.L2, li.L3,
li.L5, li.L6, li.L7, li.L8 {
list-style-type: decimal !important;
}
pre.prettyprint {
border-radius: 0;
white-space: pre;
}
Template:
<pre class="prettyprint linenums lang-cpp">
...
Place the code here
...
</pre>