Bunwich
Monday, November 25, 2024
Creating IAM Role and Assigning it to EC2 Instance requires four steps
Tuesday, October 1, 2024
Leetcode Binary Tree Array Format in Golang
In the Binary Tree section of leetcode, they provide an Input array with values used to create a binary tree.
It isn't necessary to reproduce the trees to solve the traversal problems as you can manually build a tree by adding Left and Right nodes manually.
Still using the input data helps to suss out bugs when it fails some tests. The difficulty I ran into was trying to implement a recursive solution when the approach was understanding (with some googling help) that a queue was needed.
Below are my comments and code.
Monday, August 22, 2022
Setting up Express and Typescript August 2022
To learn express and typescript, I wanted to convert the default express skeleton app into a typescript one. This uses the tutorial link below and only adds minimal changes to the express framework.
https://expressjs.com/en/starter/installing.html
and some help from this url too
https://blog.logrocket.com/how-to-set-up-node-typescript-express/
# sets up package.json
mkdir myexpress; cd myexpress
npm init -y
###
# express
npm install express
# creates an express project using pug templating instead of default jade
npx express-generator --view=pug
npm install
# to start http://localhost:3000/
DEBUG=myapp:* npm start
###
# typescript
# save-dev packages used only during dev and does not need to be deployed to prod
# ts-node is cli/repl for typescript
npm install typescript ts-node --save-dev
# https://devblogs.microsoft.com/typescript/writing-dts-files-for-types/
npm install @types/node @types/express --save-dev
npx tsc --init # creates tsconfig.json
###
# Problems
# 1. convert all the .js files into typescript
# 2. create new directory called dist or built to store the transpiled js
# 3. copy static files into dist
# 4. transpile ts into js
# 5. run the server using `node dist/index.js`
# 6. update package.json and tsconfig.json so that you can run `DEBUG=myapp:* npm start`
## 1. convert all the .js files into typescript
# adapt app.js into app.ts
npm install @types/http-errors @types/cookie-parser @types/morgan
# routes/index.ts
import express from "express";
const router = express.Router();
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
export default router;
# app.js
import createError from "http-errors";
import express from "express";
import path from "path";
import cookieParser from "cookie-parser";
import logger from "morgan";
import indexRouter from "./routes/index";
import usersRouter from "./routes/users";
import {NextFunction, Request, Response} from "express-serve-static-core";
const app = express();
// view engine setup
app.set('views', path.join(__dirname, '../views'));
//...
app.use(express.static(path.join(__dirname, '../public')));
//...
// error handler
app.use(function(err: any, req: Request, res: Response, next: NextFunction) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
app.listen(3000, '127.0.0.1');
export = app
## 3. Update the views/public paths used in app.js
# views and public need to be updated to ../ as app.js will be in ./dist and these two dirs will be one level up. This has been done in the above code snippet.
## 4. transpile cli
# this will search all ts files from the root directory and store the js files into the dist directory with the same hierarchy
npx tsc --outDir dist
## 5. run the server using `node dist/app.js`
With the addition of the last line above app.listen(//...), we can run node server using the `node` command.
## 6. update package.json and tsconfig.json so that you can run `DEBUG=myapp:* npm start`
# tsconfig.json
"outDir": "./dist", /* Specify an output folder for all emitted files. */
# package.json
# this exists
"scripts": {
"start": "node ./bin/www"
},
# edit ./bin/www
var app = require('../dist/app');
# Remove the app.listen line in app.ts as it's not needed any more
app.listen(3000, '127.0.0.1');
# and now it will work using the express way of starting the server
DEBUG=myapp:* npm start
## Bonus
# You can add a build to "scripts" in package.json
"build": "npx tsc"
# or use the cli
`npx tsc --watch`
Sunday, November 17, 2019
Fedora 30 Add another port for ssh'ing to get around some wifi filters
For Fedora 30
1) sudo vim /etc/ssh/sshd_config
Change
#Port 22
to
Port 22
Port 8080
# This allows two ports to connect to ssh
2) Update selinux to allow ssh on port 8080
sudo semanage port -m -t ssh_port_t -p tcp 8080
If you use -a you will get an error like
ValueError: Port tcp/8080 already defined
If you -d you will get another error like
ValueError: Port tcp/8080 is defined in policy, cannot be deleted
Use this to check:
sudo semanage port -l | grep 8080
http_cache_port_t tcp 8080, 8118, 8123, 10001-10010
ssh_port_t tcp 8080, 22
Saturday, August 17, 2019
Create an interface array consisting of a generic struct type in golang
var id int
var name string
err = rows.Scan(&id, &name)
// or
row = MyStruct{}
err = rows.Scan(&row.Id, &row.Name)
This seemed like a lot of repetition if every query required this logic. My next thought was to see if I could pass in a struct, use reflect to obtain the fields and return a slice of values.
Here are two examples, the first one uses uses append and requires type assertion to access the fields. The second example uses reflect.append and each field can be accessed directly from the element.
Note: Additional checks should be added, such as making sure the address of the object is passed in.
First
Second
Output (same for both)
Saturday, June 8, 2019
Learning middleware patterns in Golang
func (r *Request) Context() context.Context
Some useful links that helped guide me.
https://www.calhoun.io/why-cant-i-pass-this-function-as-an-http-handler/
https://www.alexedwards.net/blog/making-and-using-middleware
https://github.com/justinas/alice Ended with an implementation that resembles this. Thx!
Update July 2019: Middleware args changed to Handler instead of HandlerFunc
Thursday, November 16, 2017
Firefox 57 and lost some shortcuts on mac
Since I already use karabiner to remap some modifier keys for macos, it might be able to use it instead of waiting for a new firefox shortcut addon.
Note: If you're confused by the left_option/left_command it's cause I've first remap left_command to left_option.
1) Have a look at some of the examples for karabiner shortcuts
https://pqrs.org/osx/karabiner/complex_modifications/#key_specific
2) Create a json and take note of the path
{
"title": "Firefox command-d search location",
"rules": [
{
"description": "command-d search location",
"manipulators": [
{
"type": "basic",
"from": {
"key_code": "d",
"modifiers": {
"mandatory": ["left_option"],
"optional": ["any"]
}
},
"to": [
{
"key_code": "l",
"modifiers": [
"left_command"
]
}
],
"conditions": [
{
"type": "frontmost_application_if",
"bundle_identifiers": [
"^org\\.mozilla\\.firefox"
]
}
]
}
]
}
]
}
I saved this to my desktop with the name firefox-command-d.json
What is going on? frontmost_application_if only runs the above shortcuts if it's the app focused.
bundle_identifiers is your app id that you can find in the plist.
3) Now run enter this in the url bar in firefox: karabiner://karabiner/assets/complex_modifications/import?url=file:///Users/
Enable this and you have your remap.