Skip to content

Instantly share code, notes, and snippets.

View janaSunrise's full-sized avatar
🍊
life gave me oranges

Sunrit Jana janaSunrise

🍊
life gave me oranges
View GitHub Profile
@janaSunrise
janaSunrise / check_sudo.py
Created November 8, 2025 08:12
Check if the current program is running as root user. `euid` is the effective user ID of the current process. The `euid` for the root user is 0.
import os
def check_sudo():
return os.geteuid() == 0
#!/bin/bash
set -e
# colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
@janaSunrise
janaSunrise / event-emitter.py
Created October 21, 2022 05:41
Event emitter in python
from collections import defaultdict
from typing import Callable, Optional
HandlerFunction = Callable[..., None]
class EventHandler:
def __init__(self):
self.handlers = defaultdict(list)
@janaSunrise
janaSunrise / get-pytorch-device.py
Last active June 13, 2023 05:25
Function to get the device to run the code on so it's device-agnostic and accelerated if any device other than CPU is available.
# We don't check if `rocm` is available as it uses the same CUDA semantics for AMD GPUs
def get_device():
if torch.cuda.is_available():
return 'cuda'
elif torch.backends.mps.is_available():
return 'mps'
else:
return 'cpu'
@janaSunrise
janaSunrise / runtime-checker.ts
Created September 27, 2022 06:03
Check which Javascript runtime is being used (Browser, Node, Deno or Bun).
function isNodeRuntime() {
// The reason we check for both `v8` instead of `node` is because when running `process.versions` under
// Bun, it returns `node` and `bun` version, but it doesn't use v8 engine, hence not a Node.js runtime.
return (
typeof process !== 'undefined' &&
process.versions &&
process.versions.v8
);
}
@janaSunrise
janaSunrise / event-emitter.ts
Created September 25, 2022 11:37
Lightweight event emitter for typescript/javascript.
export class EventEmitter {
public events: Map<string, Set<Function>>;
constructor() {
this.events = new Map();
}
public on(event: string, listener: Function) {
if (!this.events.has(event)) this.events.set(event, new Set());
@janaSunrise
janaSunrise / from_dict_meta.py
Created March 13, 2022 06:28
Ensuring the class implementing this metaclass has `from_dict` method, to load data from dictionary. This is usually common for dataclasses to load data into them and return an object of the class.
import typing as t
class FromDictMeta(type):
"""Metaclass to ensure inherited classes have `from_dict` class method."""
def __new__(
cls,
name: str,
bases: t.Tuple[type, ...],
attrs: t.Dict[str, t.Any],
@janaSunrise
janaSunrise / gradient_centralization.py
Created November 15, 2021 17:04
Gradient centralization in Tensorflow to easily boost the stats of Deep neural networks. It helps to achieve better accuracy and lower loss. This operates directly on the gradients to centralize the vectors to have zero mean.
# Imports
import tensorflow as tf
from keras import backend as K
# Define function for centralizing the gradients
def centralize_gradients(optimizer, loss, params):
grads = [] # List to store the gradients
for grad in K.gradients(loss, params): # Iterate over gradients using the Keras Backend
@janaSunrise
janaSunrise / fix-django-csrf-error.js
Created July 28, 2021 15:49
Easiest way to fix the error of `CSRF Failed` when building a fullstack App with Django and JS framework. This is an example to fix it with Axios library, when being used to make requests to backend. Since Django and DRF requires a CSRF token to verify in Session Authentication, When using Axios, this simple axios config fixes the error.
// Fix CSRF error in django using this.
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.xsrfHeaderName = "X-CSRFToken";
@janaSunrise
janaSunrise / jupyter-setup.sh
Last active September 27, 2021 12:59
A quick bash script to setup Jupyter notebooks on your server.
sudo pip3 install jupyter
export PASSWD=$(ipython -c "from IPython.lib import passwd; print(passwd('sudo123'))") # Change with your password here between quotes.
jupyter notebook --generate-config
cd ~
mkdir certs
cd certs
sudo openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem