teleren/devto huggingface dataset:
Mini guide, access your k8s service local development
Tags: kubernetes, learn
Published: 2022-09-22 19:47:33

In a kind/minikube/etc. cluster, start a deployment (a workload resource that manages a pod replicaset)

```shell
kubectl create deployment home --image=b4bz/homer
```

expose the deployment, i.e. make it receive comms from other containers or the outside.

```shell
kubectl expose deploy/home --port 8080
```

> -> make sure the port exposed is actually the one the container exposes, e.g. for postgres this would 5432, for b4bz/homer it is 8080. There is no default here.

The command above creates a service of the type ClusterIP, which makes it accessible to other services only within cluster.

To make it accessible outside the cluster, the service has to be of type `NodePort`, like so

```
kubectl expose deploy/home --type=NodePort --port 8080
```

Now, how to you open it in a browser using ~~kind~~, k8s? Well, you can port-forward from the localhost to the container port using `kubectl port-forward` - checking out `kubectl port-forward --help` clarifies a lot.

```
kubectl port-forward services/home :8080
# assigns a random localhost port to the port 8080 of the container
```
How to get visitor's location (country) using geolocation in JavaScript?
Tags: javascript, webdev, beginners
Published: 2022-09-22 17:23:47

I wanted to localize client side pricing for few countries without using any external API, so I used local Date object to fetch the country using new Date()).toString().split('(')[1].split(" ")[0]

```js
document.write((new Date()).toString().split('(')[1].split(" ")[0])
```

Basically this small code snippet extracts the first word from the Date object. To check for various time zone, you can change the time of your local machine.

In my case, our service only included three countries, so I was able to get the location using the following code.

```js
const countries = ["India", "Australia", "Singapore"]
const countryTimeZoneCodes = {
  "IND": 0,
  "IST": 0,
  "AUS": 1,
  "AES": 1,
  "ACS": 1,
  "AWS": 1,
  "SGT": 2,
  "SIN": 2,
  "SST": 2
} // Probable three characters from timezone part of Date object
let index = 0
try {
  const codeToCheck = (new Date()).toString().split('(')[1].split(" ")[0].toUpperCase().substring(0, 3)
  index = countryTimeZoneCodes[codeToCheck]

} catch (e) {

  document.write(e)
  index = 0
}

document.write(countries[index])
```

This was just to improve user experience. It's not a full proof solution to detect location. As a fallback for not detecting correctly, I added a dropdown in the menubar for selecting the country.

----------

Another solution:

You can look their IP address up in any IP-to-location service (like maxmind, ipregistry or ip2location). This will be accurate most of the time.

Here is a client-side example with Ipregistry:

```js
fetch('https://api.ipregistry.co/?key=tryout')
    .then(function (response) {
        return response.json();
    })
    .then(function (payload) {
        console.log(payload.location.country.name + ', ' + payload.location.city);
    });
```
"Object.assign". It's easier than you think
Tags: javascript, beginners
Published: 2022-09-22 19:24:26

## 💎 What is Object.assign
normally it is used when merge multiple objects

```javascript
const target = {city: 'japan', capital: 'tokyo'}
const source = {food: 'sushi', history: 'samurai'}

const result = Object.assign(target, source)

console.log(target)
/**
{
 city: 'japan', 
 capital: 'tokyo',
 food: 'sushi',
 history: 'samurai'
}
**/

console.log(source)
// {food: 'sushi', history: 'samurai'}

console.log(result)
/**
{
 city: 'japan', 
 capital: 'tokyo',
 food: 'sushi',
 history: 'samurai'
}
**/
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kcc6brr6zk9cdhdxbug3.png)



## 💎 Object.assign in real life
Contrary to this way of merge, according to my experience, it's often used when wants to **copy object**

```javascript
let animal = {name: 'pikachu', type: 'kawaii'}
let copy_animal = Object.assign({}, animal)

console.log(copy_animal)
// {name: 'pikachu', type: 'kawaii'}
```

## 🔥 Warning (reference)
Now give you a quiz, is this true or false ??
```javascript
animal === copy_animal
```
・
・
・
The answer is **false**
▼ proof
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e125hjeq9howo4cw5nsa.png)

▼ There is my other article, which explains about it.
{% link https://dev.to/kaziusan/-is-false-what-let-me-explain-it-with-image-58ef %}

## 🔥 Warning2 (shallow copy)
```javascript
let animal = {name: {first: 'pikachu', last: 'honda'}, type: 'kawaii'}
copy_animal = Object.assign({}, animal)

// change value
copy_animal.type = 'dirty'

console.log(animal)
// {name: {first: 'pikachu', last: 'honda'}, type: 'kawaii'}
// ⭐ still pikachu is kawaii !!
```
Because these objects are on different references

### BUT

```javascript
// change value of second hierarchy 
copy_animal.name.last = 'suzuki'

console.log(animal)
// {name: {first: 'pikachu', last: 'suzuki'}, type: 'kawaii'}
// ⭐ changed 'honda' => 'suzuki' !!!!!!!!!!!
```

> 😠 How this result come ?? You said these objects are on different references !!

Yup, but actually this is only 1 hierarchy of object, over 2 hierarchy objects are on same reference and this is called **Shallow copy**

### Yup Object.assign is shallow copy

▼ just log
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kgla9ijj9sdro4kiu75.png)


## 💎 Spread operator
By the way spread operator is the same as Object.assign
```javascript
let animal = {name: 'pikachu', type: 'kawaii'}
let copy_animal = {...animal}

console.log(copy_animal)
// {name: 'pikachu', type: 'kawaii'}
```
But also **shallow copy** !!!!!
I Was Told There Would Be No Math
Tags: adventofcode, algorithms, programming, javascript
Published: 2022-09-22 19:17:21

## [Advent of Code 2015 Day 2](https://adventofcode.com/2015/day/2)

## Part 1
1. Oh, there will be plenty of math.
2. Using several familiar tools in my toolbox

### Oh, there will be plenty of math.
Much to my delight, a majority of the math throughout Advent of Code was in celebration of patterns underlying various scientific, arithmetic or algorithmic formulas and proofs.

### Using several familiar tools in my toolbox
- `reduce()` to accumulate a total
- `split()` to turn a string into an array
- `map()` to coerce or manipulate data
- `array destructuring` to concisely extract and store multiple values
- `sort()` to, well, sort numbers
- `slice()` to extract a subset of items from an array

My algorithm in JavaScript:
```js
input.reduce(
  (sqft, box) => {
    let [l, w, h] = box.split('x').map(Number)
    let smallestArea = [l, w, h]
      .sort((a, b) => a - b)
      .slice(0, 2)
      .reduce((a, c) => a * c)
    return sqft += 2*l*w + 2*w*h + 2*h*l + smallestArea
  }
, 0)
```

## Part 2
### A minor mathematical tweak
- A shorter equation
- And a relatively unchanged algorithm

My algorithm in JavaScript:
```js
input.reduce(
  (sqft, box) => {
    let [l, w, h] = box.split('x').map(Number)
    let smallestPerimeter = [l, w, h]
      .sort((a, b) => a - b)
      .slice(0, 2)
      .map(el => el * 2)
      .reduce((a, c) => a + c)
    return sqft += l*w*h + smallestPerimeter
  }
, 0)
```

## Both parts, a year ago
This was my working algorithm in JavaScript when I first solved this puzzle:
```js
function dayTwoPart1(input) {
  return input.map(box => wrappingPaperFor(box))
              .reduce((acc, curr) => { return acc + curr }, 0)
}

function dayTwoPart2(input) {
  return input.map(box => ribbonFor(box))
              .reduce((acc, curr) => { return acc + curr }, 0)
}

function wrappingPaperFor(box) {
  return surfaceAreaFor(box) + slackFor(box)
}

function surfaceAreaFor(box) {
  let [l, w, h] = box.split("x").map(i => +i)
  return (2 * l * w) + (2 * w * h) + (2 * h * l)
}

function slackFor(box) {
  let sortedBox = box.split("x").map(i => +i).sort((a,b) => a - b)
  return sortedBox[0] * sortedBox[1]
}
function ribbonFor(box) {
    let [s1, s2, s3] = box.split("x").map(i => +i).sort((a,b) => a - b)
    return (s1 + s1 + s2 + s2) + (s1 * s2 * s3)
}
```

- It's all very straightforward
- Almost to its detriment
- Then again, this puzzle did require a lot of straightforward math
- Much like with Day 3, I'm very proud of the code I wrote my second time around

## I did it!!
- I solved both parts!
- At first in a very separated, functional approach...then again in a more chained-together, eloquent approach!

While the math in this puzzle wasn't too intriguing, it served as a callback to all of the other puzzles that featured wonderfully-intriguing math.

One day left!
Remove local stale branches
Tags: git, terminal, powershell, tip
Published: 2022-09-22 15:49:11

It's no secret that we end up with tons of unused, stale branches (either merged or not) in local git repository. 

You might want to clean-up unused branches for both organization and storage purposes. But you don't want to delete branches one-by-one which would literally take hours (sometimes). 

Here is how to remove local branch **in bulk**.

#### 1. Remove git branches on `*nix terminal`.
```sh
# this will delete only merged branches
git branch --merged | grep -v \* | xargs git branch -D

# this will delete all branches except the current one checked out
git branch | grep -v \* | xargs git branch -D
```

#### 2. Remove git branches on `Windows Powershell/Terminal`.
```sh
# this will magically all branches except dev, main, master and develop.
git branch | Select-String -Pattern '^(?!.*(dev|main|master|develop)).*$' | ForEach-Object { git branch -D $_.ToString().Trim() }

# this will only delete merged branches.
git branch --merged | Select-String -Pattern '^(?!.*(dev|main)).*$' | ForEach-Object { git branch -D $_.ToString().Trim() }
```


#### Yeah, it's that easy. Go ahead and give your local git some breathe 🙂.
Moving Intellij to VSCode by keeping these shortened keys
Tags: vscode, intellij, webstorm
Published: 2022-09-22 19:10:03

I am basically an IntelliJ user, but sometimes I use _VScode_. And one of the few reasons I don't like _VSCode_ too much is the **lack of space and visibility for debugging** and **my keyboard shortcuts**.

In this post, I can solve from an extension the second problem. 

## Install the extension on VSCode

I found how I can achieve my wish with **[IntelliJ IDEA Keybindings](https://marketplace.visualstudio.com/items?itemName=k--kato.intellij-idea-keybindings)**.

![Preview of the process to this extension](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bqotbs37i5ndqlzxe1l0.gif)

> IntelliJ IDEA Key Bindings for Visual Studio Code
> Build Status License: MIT Marketplace Version Install

Port of IntelliJ IDEA key bindings for VS Code. Includes keymaps for popular JetBrains products like IntelliJ Ultimate, WebStorm, PyCharm, PHP Storm, etc.

## Export settings of your Jetbrains IDE

Go to **File** 👉🏼 **Manage IDE Settings** 👉🏼 **Export Settings**, and select just **Keymaps (schemes)**. Unzip that. And you're done!


![Export settings from Jetbrains IDE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dl2dmfl8neia3geta88f.png)
 
## Usage

- Launch Code
- Open command pallet _Ctrl-Shift-P_ (Windows) or _Cmd-Shift-P_ (macOS)
- Choose **Import IntelliJ Keybindngs** (XML)
- Copy & Paste it into `keybindings.json`
Reading the latest Whatsapp messages using python and pyautogui
Published: 2023-06-12 17:13:15

---
title: Reading the latest Whatsapp messages using python and pyautogui
published: true
date: 2022-09-22 18:42:33 UTC
tags: 
canonical_url: 
---

> This post was originaly posted on my [medium](https://tiagorangel2011.medium.com/reading-the-latest-whatsapp-messages-with-python-79d7f754b36)

# Introduction

Hi everyone! I had built this some time ago this code and now I want to share it with everyone. My idea was to open WhatsApp, select the phone number, and read the messages, but then I needed to do this:

- Open WhatsApp using WhatsApp's web protocol

- Wait 10 seconds

- Focus on WhatsApp's window

- Drag the cursor to select the latest messages (unfortunatly, can't use ctrl+a to select everything)

- Copy everything

- Get the clipboards content

In the full code, the coordinates below may not be correct in your case, so remember to update them:

```
import pyautogui  
import time  
time.sleep(5)  
print(pyautogui.position())

```

But first, you need to install the pyautogui (for automating) and the webbrowser (to open whatsapp) libraries:

```
$ pip3 install webbrowser  
$ pip3 install pyautogui

```

# The code

Finally, heres the full code:

```
import webbrowser
import pyautogui
import time
import pyperclip
phone = pyautogui.prompt('Telephone number')
webbrowser.open("whatsapp://send?phone=" + phone)
time.sleep(10)
pyautogui.click(1803, 916)
time.sleep(0.2)
pyautogui.dragTo(587, 127, 0.2, button='left')
pyautogui.hotkey('ctrl', 'c')
ret = pyperclip.paste()
pyautogui.alert(ret, "results")
print("\n\n ******************* \n\n" + ret + "\n\n")
pyautogui.click(1900, 4)

```

Thank you for reading!
Sending WhatsApp messages with Python and PyAutoGUI
Published: 2023-06-12 17:13:11

---
title: Sending WhatsApp messages with Python and PyAutoGUI
published: true
date: 2022-09-22 18:39:15 UTC
tags: 
canonical_url: 
---

> This post was originaly posted on my [medium](https://tiagorangel2011.medium.com/how-to-send-a-whatsapp-message-with-python-75a69eb695c6)

# The project

Hi everyone! Today Im building a text-to-whatsapp python app

Bellow, I have the code, and I will explain everything in the comments.

Oh, but first run the following commands:

```
$ pip3 install web-browser
$ pip3 install pyautogui

```

And here we have our code:

```
import webbrowser # import the webbrowser library, see line bellow
import pyautogui #import the library that will simulate clicks
import time # for sleep
msg = input("Message: ")
phone = input("Telephone number: +")
sim = input("Press enter to send") # Verify
webbrowser.open("whatsapp://send?text=" + msg + "&phone=" + phone) # Open whatsapp's URL protocol. This will open the Whatsapp app and open the send dialog
time.sleep(9) #Give time for the program to execute
pyautogui.click(1870, 984) # Send message (simulate click on send button)
time.sleep(1) # wait 1 sec
pyautogui.click(1900, 4) # simulate click to close whatsapp

```

To use this code, you must have Whatsapp installed and a 1536x864 (width x height screen. If you dont have a screen of that dimensions, open WhatsApp, execute the following code, and immediately position your mouse over the close button and the send button of WhatsApp. The program sleeps 5 seconds after execution. Then, change the X and Y coordinates of the _pyautogui.click()_ functions to the results.

```
import pyautoguiimport
timetime.sleep(5)
print(pyautogui.position()) # Gives you: _Point(x=XXX, y=XXX)_

```

Thanks for reading!
Intelligence Competition
Published: 2022-09-22 18:29:14

Sometimes I get comments on here about that really wind me up.

It's taken me 30 years to realise that simplicity is what works for most people, I used to value and build a volcabulry including some old English which would often lead to me being referred to as an eloquent child.. but as I can't spell for suger, I'm also in the post 30 club aging and getting dummer by the year I'd prefer the simple life, I just can't be bothered with a competition about who is right or wrong, life's to short.

I'd ponder about humility and what drives people to fight hard for correctness online particularly programmers but I just don't know, I will never be a 10x 60 year old programmer with everything figured out, and I'm blessed to know that.
{} === {} is false... 😳WHaT?? Let me explain it with image 🖼
Tags: javascript, beginners
Published: 2022-09-22 18:15:48

In javascript
```javascript
const obj1 = {}
const obj2 = {}
obj1 === obj2 // false
```

# WHaT ?????
If you react like this, keep reading this article.

At first I need to explain about **memory life cycle**.
Don't worry, I'll show you simple way with image.

```javascript
const name  = 'kaziu' // string
let isShame = true    // boolean
let age     = 101     // number 
```
in Javascript **string, number, boolean, null, undefined, symbol** calls **primitive type**
When declare like this in javascript primitive type, datas store on space which is called **stack** in memory.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yp4c8psvqvck7tyk6jfj.png)

On the other hand, object is **reference type** include function, array (actually function is one of objects)

```javascript
const obj1 = {}
const obj2 = {}
```
When declare object, computer does not directly store that data type in that variable. property stores in **heap**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shezscmo4x2ylbp8bo4s.png)

As you can see, each objects has different addresses. And `obj1 === obj2` compares these addresses, that's why return false.

### conclusion
This is normally called **reference**, but I used **address** because it's easy to understand. You could imagine there are two same looking houses in different places 🏠🏠

personally I take care of it as frontend engineer, specially when I use **useMemo** in React.
Spark Is a DIY Athena - Or SQL Over Python Dataframes
Published: 2022-09-22 18:15:25

am new to Spark, but so far I would say: it is the code libraries for a DIY Athena, which lets you write SQL against a file system (eg S3) like it was a database. 

Some rather dense documentation discusses a Python Dataframe API (multidimensional arrays - aka matrices) through which SQL accesses these files. So SQL over Dataframes, essentially.
How to remove specific element occurrence from an Array.
Tags: javascript, array, beginners
Published: 2022-09-22 18:09:54

**QUESTION**
Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The relative order of the elements may be changed.

**STEP**
Since we want to remove all occurrences of a particular value from the array, we can use this approach 


- 
Loop through the array

`while(condition){}`

The while method reiterates sets of action within the curly braces until conditions are met or becomes false.

For the condition to remain true, the while loop checks if the integer value can be found in the array, otherwise the condition becomes false and the loop is exited. So I used the [includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method on the array to achieve this.

- 
Remove the specific integer val that occurs in array

`array.splice("start", "deleteCount")`

To remove ocurrences of the specific value, i used the splice array method and indexOf method to create the logic to remove the values.

The [splice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) takes in a first argument(start) which in this case would be the index of the integer value I want to remove and a second value(deleteCount) which I specified to be "1" so just a single element is remove from the array begining from (start)

To determine the (start) value, I used the [indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) method. `indexOf` returns the index of the first occurrence of a specific value within the array.

**How the Code Runs**
The while loop checks if the integer value can be found in the array nums. If true, it go ahead to remove the first occurrence of the integer value from the array using splice and indexOf logic, this process repeats itself until the while condition is false.

Final code.

```
var removeElement = function(nums,
val){ 
    //loop through array 
   while (condition){ 
   //remove element from the array using splice method.
  nums.splice("start",1); } 
    return nums.length; 
};
```

**BONUS**
If you ever wonder how this can be applied to a real project.

You can use this approach to filter out specific genre from a list of movie genre on a movie website. Allowing user to remove specific genre they no longer want to see on movies page.
Rancher Desktop on Mac 🚀
Tags: rancherdesktop, docker, mac, volumes
Published: 2022-09-22 18:06:07

> Note:
 This is going to be purely technical short post focusing on getting Rancher desktop to work on Mac with Volume fixes!!

**Setup Docker tools**
```
brew install docker docker-compose
```

After running above commands you will get following commands. Simply execute them:

```
Compose is now a Docker plugin. For Docker to find this plugin, symlink it:
  mkdir -p ~/.docker/cli-plugins
  ln -sfn /opt/homebrew/opt/docker-compose/bin/docker-compose ~/.docker/cli-plugins/docker-compose
```

**Setup Rancher Desktop**
```
brew install --cask rancher
```

Once setup is done open it & it will look like this:

![Rancher Desktop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnmvv02z06l1qpmm3y02.png)


A sample docker-compose:
```
version: '3'
services:
  db:
    image: postgres:14.4-alpine
    ports:
      - '9432:5432'
    environment:
      POSTGRES_PASSWORD: docker
      POSTGRES_USER: docker
      POSTGRES_DB: postgres
      PGDATA: /var/lib/pg_data
    volumes:
      - ./data:/var/lib/pg_data
```

It will fail with following error:


![Rancher Postgres permission error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x4f353p9fv0tlz6u2x8b.png)



**Fixing Volume Permissions in Lima Config**
Run
```
touch /Users/${USER}/Library/Application\ Support/rancher-desktop/lima/_config/override.yaml
```
```
echo 'mountType: "9p"' >> /Users/${USER}/Library/Application\ Support/rancher-desktop/lima/_config/override.yaml
```

![Rancher Lima Fix Volume Permissions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fju58ul7g9ohrdrn2b2j.png)


**Quit and Reopen Rancher Desktop**
Run:
```
docker-compose up
```

![Rancher+Docker+Postgres](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rz58bf1t2xxgq0rf158k.png)


**And, congratulation!! you have it running. 🎉🎉🚀**
Im developing a android web browser
Published: 2022-09-22 18:02:55

I look up to google play store and search for browser. I've seen quite a lot of them. But most of them having the same data collection. Theyre collecting personal info, activity, logs, location, device, ids etc.

And since my own web browser doesn't collect any kindof data i found it to be cool to be use when i launch my 400kb android web browser to play store...

My app is published on 3rd party store (amazon app store, samsung galaxy store, uptodown, getjar) and on my website also. Im halfway through in finishing the 25$ fee hahah..

if you have a time please come and try my web browser https://mrepol742.github.io/webvium/
the dev apk can be found here https://mrepol742.github.io/webviumdev/
Moving from Medium!
Published: 2023-06-12 17:13:08

---
title: Moving from Medium!
published: true
date: 2022-09-22 17:56:41 UTC
tags: 
canonical_url: 
---

Ahoy there, fellow bloggers!

I've made the leap from Medium to a new platform and I'm ready to have some fun! No offense to Medium, it's a great platform and has served me well, but this new space is where the real adventures lie. With multiple reactions and endless possibilities, I'm ready to explore and have a blast!

So, I'll be moving all my Medium posts to this new home and I can't wait to see what the future holds. Join me on this journey and let's make some memories!