teleren/devto huggingface dataset:
CKAD Exam Practice Exercise : Services and Networking
Tags: kubernetes, developer, devops, cloud
Published: 2020-06-07 13:31:20

# Services and Networking (13%)

## Practice questions based on these concepts

* Understand Services
* Demonstrate a basic understanding of NetworkPolicies

## Exercise


<details><summary>Create an nginx pod with a yaml file with label my-nginx and expose the port 80</summary>


```
kubectl run nginx --image=nginx --restart=Never --port=80 --dry-run -o yaml > nginx.yaml

// edit the label app: my-nginx and create the pod
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    app: my-nginx
  name: nginx
spec:
  containers:
  - image: nginx
    name: nginx
    ports:
    - containerPort: 80
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}

kubectl create -f nginx.yaml
```

</details>


<details><summary>Create the service for this nginx pod with the pod selector app: my-nginx</summary>


```
// create the below service
apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  selector:
    app: my-nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 9376

kubectl create -f nginx-svc.yaml
```

</details>


<details><summary>Find out the label of the pod and verify the service has the same label</summary>


```
// get the pod with labels
kubectl get po nginx --show-labels

// get the service and chekc the selector column
kubectl get svc my-service -o wide
```

</details>


<details><summary>Delete the service and create the service with kubectl expose command and verify the label</summary>


```
// delete the service
kubectl delete svc my-service

// create the service again
kubectl expose po nginx --port=80 --target-port=9376

// verify the label
kubectl get svc -l app=my-nginx
```

</details>


<details><summary>Delete the service and create the service again with type NodePort</summary>


```
// delete the service
kubectl delete svc nginx

// create service with expose command
kubectl expose po nginx --port=80 --type=NodePort
```

</details>


<details><summary>Create the temporary busybox pod and hit the service. Verify the service that it should return the nginx page index.html</summary>


```
// get the clusterIP from this command
kubectl get svc nginx -o wide

// create temporary busybox to check the nodeport
kubectl run busybox --image=busybox --restart=Never -it --rm -- wget -o- <Cluster IP>:80
```

</details>


<details><summary>Create a NetworkPolicy which denies all ingress traffic</summary>


```
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
spec:
  podSelector: {}
  policyTypes:
  - Ingress
```

</details>
Sync Forked Repository With Upstream 🔁✔️
Tags: developer, git, github, opensource
Published: 2020-06-08 00:51:08

---
title: Sync Forked Repository With Upstream 🔁✔️
published: true
date: 2020-06-07 13:24:00 UTC
tags: developer,git,github,oss
canonical_url: https://2kabhishek.blogspot.com/2020/06/sync-forked-repository-with-upstream.html
---

Here's the situation, You have forked a repository on GitHub, you have made your changes and sent a pull request and that request has been merged. 

  

  Now you want to make further changes, but the repository mentions that you are X commits ahead or/and X commits behind upstream repository. 

  

**So how do you sync it?**

  You can delete your fork and fork the original repository again, but that is a very tedious thing to do. 

  

Here's another way to do this:

  

1. Clone your fork

```
git clone https://github.com/yourname/repo.git
cd yourname/repo
```

2. Add upstream remote

```
git remote add upstream https://github.com/original-author/repo.git
git fetch upstream
```

3. Ignore all changes in fork and sync with upstream

```
git reset --hard upstream/master
git push -f origin master
```
Only do this if you have no changes on your fork that you will like to keep.  
This will set your fork's master to be the same as upstream's master.  
Now you are free to make any changes you wish to make.

  
  If you just want to get the changes from upstream you can do  

```
git pull upstream master 
git push origin master
```
  Just a word of caution: Always be extra careful when using the -f or --force option.

  
Thank you for reading, hope you found this useful, see you in the next one.
Beginner Python tips Day - 04 random
Tags: python, beginners, codenewbie, tips
Published: 2020-06-07 13:14:34

```python
# Python Day - 04 random

import random
my_list = ['Python', 'JavaScript', 'Dart', 'Golang', 'Rust']

# choice - get a random element from a list
print(random.choice(my_list))
# Prints a single element from the list e.g 'Dart'

# choices - get number of elements from a list with replacement
print(random.choices(my_list, k=2))
# Prints a list of two elements from a list e.g ['Rust', 'Golang']
# Note: choices returns the elements with replacement meaning,
# You might get the same element more than once e.g ['Rust', 'Rust']

# sample - get number of elements from a list without replacement
print(random.sample(my_list, k=2))
# Similar to choices but you will not get same element more than once

# shuffle - shuffle the elements in a list
random.shuffle(my_list)
print(my_list)
# Prints e.g ['Golang', 'Dart', 'JavaScript', 'Python', 'Rust']
# Randomize the original list
```
Learning to ️ switch statements
Tags: beginners, javascript
Published: 2020-06-07 13:08:35

For many years I used `if` because why not, it does everything I need. Then I met Rust, we where inseparable. Rust showed me the match statement and I started thinking about simplicity, code meaning, safety, minimal solutions and code correctness.

JavaScript says hey i've got 2 comparison statements, `if`is used for expressions `1 × 1 === 5`where the answer is potentially unknown without computation and switch compares cases in branches, I feel it fits known cases. 

## When to use switch?
- do you have multiple things to compare?
- Is the set of answers known to you.

I'm saying that switch is best for enums, a finite set of know answers. An e what? An enum is like a multiple choice question, you have a finite set of possible answers, all are stored in some sort of object.

```js
const favColour = { answer1: 'red', answer2: 'blue' }
```
Then later on..

``` js
const getAnswer = (userInput) => {
    switch (userInput) {
        case favColour.answer1:
           return "red rocks";
        case favColour.answer2:
           return "blue beloved";
        default
           return `${userInput} is a colour I don't really know or like.`
    }
}

getAnswer("red");
```
 But Adam, default is catching all those unknown answers so that part is infinite? So it's no different to an if statements else. Ahhh I thought you might say that, yes it's true you can use default if you want but notice there is still no expressions, it's all about intent, I know the intention of this block of switch was meant to be finite. If I asked you what your favorite food is and you said airplanes, I know something has gone a bit wrong here.

The above is like a match statement in rust. Anyways it's cool hope you can see the difference between if and switch now.
Rails efficient way to check if data exists 
Tags: mysql, ruby, rails
Published: 2020-06-07 13:02:01

---
title: Rails efficient way to check if data exists 
published: true
description: Rails check if data exists
tags: Mysql, Ruby, Rails

---

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7k1j5jhfz8xqw3emuvsy.jpg)

What the ways to determine whether a record exists in the database in rails? `any?`, `present?`, `empty?`, `exist?` All of the above methods can achieve the goal but which method is more efficient? let's compare one by one below:

### any?

```mysql
Build.where(:created_at => 7.days.ago..1.day.ago).passed.any?

// SELECT COUNT(*) FROM "builds" 
WHERE ("builds"."created_at" BETWEEN '2017-02-22 21:22:16.885942' AND '2017-02-28 21:22:16.886077') 
AND "builds"."result" = $1 [["result", "passed"]]
```

This method will load COUNT(*****) into memory. COUNT(*****) database query is good for performance it can handle some performance problems and there are no major side effects

### present?

``` mysql
Build.where(:created_at => 7.days.ago..1.day.ago).passed.present?

// SELECT "builds".* FROM "builds" 
WHERE ("builds"."created_at" BETWEEN '2017-02-22 21:22:27.133402' AND '2017-02-28 21:22:27.133529') 
AND "builds"."result" = $1 [["result", "passed"]]
```

This method will be the least efficient because it will load all data records into memory and use the instance as an AR object to determine whether the array is empty. If it is a large data table it will occupy a lot of memory in one query

### empty?

```mysql
Build.where(:created_at => 7.days.ago..1.day.ago).passed.empty?

//  SELECT COUNT(*) FROM "builds" 
WHERE ("builds"."created_at" BETWEEN '2017-02-22 21:22:16.885942' AND '2017-02-28 21:22:16.886077') 
AND "builds"."result" = $1 [["result", "passed"]]
```

This method is the same as any?

### exists?

```mysql
Build.where(:created_at => 7.days.ago..1.day.ago).passed.exists?

// SELECT 1 AS one FROM "builds" 
WHERE ("builds"."created_at" BETWEEN '2017-02-22 21:23:04.066301' AND '2017-02-28 21:23:04.066443') 
AND "builds"."result" = $1 LIMIT 1 [["result", "passed"]]

```

This is the most efficient method because it will only find the first piece of data that meets the criteria. The execution time of SELECT 1 ... LIMIT 1 in SQL is relatively short. Overall it is very effective

The following is the time consumed by the query

``` ruby
any?   =>  400.9 ms
present? => 2892.7 ms
empty?  =>  403.9 ms
exists? =>   1.1 ms
```

Based on the above results, it can be seen that `exists?` is the most effective under normal circumstances.

Hope it can help you :)
How to use the dev.to API!
Tags: beginners, webdev, php, tutorial
Published: 2020-06-07 12:58:06

---
title: How to use the dev.to API!
published: true
description: We'll be using PHP to get and display our most recent posts.
tags: beginner, webdev, php, tutorial
---

# Why?

I use dev.to as my main dev blogging area now, but I want to show-off my blogs on my portfolio! So we're going to create a simple list of the latest 3 blog articles which link back to the dev.to site. For this tutorial I'll be showing how this can be achieved in PHP.

# Let's go!

First of all, the below is a great starting point to understand the dev.to API and all of the possible endpoints.

{% link https://dev.to/alfredosalzillo/the-state-of-devto-v0-api-1o2 %}

We're going to be using this endpoint: https://dev.to/api/articles?username=nataliedeweerd which generates a JSON object with the author's latest 30 articles. To get your personal endpoint, change the `nataliedeweerd` username to your own.

So how do we get this data into our website? In PHP we can use something called `cURL`. `cURL` (**c**lient **URL**) is a PHP library which allows you to make HTTP requests. So you can call a URL in your code and get a HTML response from it.

The below code shows a basic curl function which gets us our data:

```php
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://dev.to/api/articles?username=nataliedeweerd",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);
```

We need to decode this data before we can effectively use it however. 

```php
$response = json_decode($response, true); 
```

This decodes the json object into a much more usable array! All we need to do now is loop through the array, and print out the results.

```php
foreach ($response as $key => $article){

	echo '
		<a href="'.$article['url'].'" class="blog__article">
			<h2>'.$article['title'].'</h2>
			<div class="blog__description">'.$article['description'].'</div>
			<div class="blog__readmore">Read More</div>
		</a>
	';

	if ($key == 2){ break; }

}
```

Because the array key's are numeric, we can use these to determine how many articles we've printed. If we've printed 3 articles the key will be 2 (array's start from 0 don't forget), so we break out of the foreach.

If you want to have a closer look at what keys the array is printing out, you can use the below code before the foreach loop:

```php
echo '<pre>'.print_r($response,true).'</pre>';
```

This will show you everything the decoded JSON is returning, allowing you to include your article's images, or canonical links, or tags!

And that's it! We just need to apply a bit of CSS and our dev.to articles are printing out wherever we want!

**Let me know if you have any more questions below.**
Reusable Tagged Templates
Tags: tagged, template, literals, reusablefunctions
Published: 2020-06-07 12:57:17

TLTR; See it in action [https://github.com/isaozler/tagged-templates-io]

Once again, I was working on a dragon component. Based on the transition and loading state the class names should change for custom transition and loading states. There is a really nice package classnames [https://github.com/JedWatson/classnames], but most of the time I find myself stating the class name between two values. If it's true ? '--visible' : '--hidden'. 

```js
const transitionClass = `app__overlay--${isTransitioning ? 'trans-start' : 'trans-end'}`
const loadingClass = `app__overlay--${isLoading ? 'visble' : 'hidden'}`

const stateClasses = [transitionClass, loadingClass].join(' ');

# React Sample
<div className={`app__overlay ${stateClass}`} />
```
## Problem
This does the job actually, but is quite messy, not an elegant solution and not reusable. As I mentioned earlier in the classname package you can do this;

```js
className({ foo: true }) // => 'foo'
```

But, then you have to do another object to get the opposite state.

```js
const stateClass = className({
 'app__overlay--visible': isLoading,
 'app__overlay--hidden': !isLoading,
 'app__overlay--trans-start': isTransitioning,
 'app__overlay--trans-end': !isTransitioning,
});

<div className={stateClass} />
```

# Solution
Of course, there is always room for improvement. But for now, I ended up with a very lightweight package making at least my life easier.
```js
const stateClass = taggedTemplatesIo(
  `{0} {0}--{1} {0}--{2}`,
  [
    ['app__overlay'],
    ['trans-start','trans-end'],
    ['visble','hidden'],
  ],
  [true, isTransitioning, isLoading]
);

# React Sample
<div className={stateClass} />
```

# GraphQL / SQL interpolations
You can always use this for other implementations of course. It was very useful for me with GraphQL / SQL interpolations. To give you an example;

## SQL
```js
const isClient = true;
const as = 'age';
const from = ['clientTable', 'relationTable'];
const fromCondition = isClient;
const where = `${as} = ${42}`;
const start = 0, end = 10;

taggedTemplates(`
  SELECT {select} AS {as}
  FROM {from}
  WHERE {where}
  LIMIT {start}, {end}
`,
  { select: 'age_col', as, from, where, start, end },
  { from: fromCondition },
)


// Outputs

SELECT age_col AS age
  FROM clientTable
  WHERE age = 42
  LIMIT 0, 10
```


# Conclusion
With this lightweight simple helper, I can write cleaner, easier to maintain code blocks. Hope it helps others too!
Day 28 of #100DaysOfCode: Create the Proxy for Next.js application
Tags: 100daysofcode, nextjs, react, webdev
Published: 2020-06-07 12:47:32

## Introduction
I found that using *proxy* in the package.json didn't work for the next.js application. This article is the note to config the proxy for next.js.
   
## Steps
### 1. Install packages
```
npm install http-proxy-middleware

```

### 2. Add a new file in the root folder
* Add a file called *server.js*. The following code will launch a node.js server on port 3000. 
* This server contains the original next.js service and middleware. The middleware will replace the original server's requests from 
 replace *http://localhost:8000/api/xxx* with *http://localhost:3000/api/xxx*

```javascript
// server.js
const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware');

const devProxy = {
    '/api': {
        target: 'http://localhost:8000', 
        pathRewrite: {
            '^/api': '/api'
        },
        changeOrigin: true
    }
}

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({
    dev
})
const handle = app.getRequestHandler()

app.prepare()
    .then(() => {
        const server = express()

        if (dev && devProxy) {
            Object.keys(devProxy).forEach(function(context) {
                server.use(createProxyMiddleware (context, devProxy[context]))
            })
        }

        server.all('*', (req, res) => {
            handle(req, res)
        })

        server.listen(port, err => {
            if (err) {
                throw err
            }
            console.log(`> Ready on http://localhost:${port}`)
        })
    })
    .catch(err => {
        console.log('An error occurred, unable to start the server')
        console.log(err)
    })
```

### 3. Edit package.json
```
{
    ....
   "scripts": {
        "dev": "node server.js",
        ...
   }
}

```

### 4. Launch the server and the proxy
```
npm run dev
```

And we will see the following screen shot

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mkeyy1uaj3fh9uo54wek.png)


## Articles
There are some of my articles. Feel free to check if you like! 
* My blog-posts for software developing: https://medium.com/a-layman
* My web resume: https://jenhsuan.github.io/ALayman/cover.html
* Facebook page: https://www.facebook.com/imalayman
What keeps you motivated ??
Tags: discuss, programming, motivation
Published: 2020-06-07 12:29:01

- Over **6** years of programming knowledge
- tranformed form complete **noob** to **not a noob anymore**
- **20+** projects started (_double or triple the count if rewrites are allowed_)
- But the end result, **No successful project till date**!

The journey of over 6 years of programming has really been fun. I learnt so so so many new stuffs and improved myself a lot. But when I look back at the successful achievements of mine, I see nothing to be shown.

I really am proud of what I have learnt, but there definitely is something missing because of which there is no actual outcome. I never have reached the completion stage for any project because I get demotivated by various factors. But the cycle goes on I do get back to them and make minor progress, and leave it back again.

I really would love to know what keeps you guys motivated, maybe I can  learn something from you guys that will keep me motivated as well ??

---

<center>Sharing experiences is the best way to help other grow :heart:  </center>
Scala+Stellar Weekly Update June 7, 2020
Published: 2020-06-07 12:26:03

Hi! 👋 This is the very first update for the Scala Stellar SDK. I hope to make some progress each week (even if it is just planning) and report on that progress publicly.

🧠 **Thinking about**

The previous week has seen big strides made in the [SDK rebuild](https://github.com/Synesso/scala-stellar#stellar-for-scala). I'm really enjoying implementing vertical slices, with a focus on the most important functionality and accentuating usability. I'm wondering how long it will take to achieve parity with the existing SDK, and how best to balance efforts between the new initiative and the existing one.

I watched [Charlie Shrem's interview with Jed](https://www.youtube.com/watch?v=r8xCmCq1muE). It was really enjoyable. Early on Jed talks about his life-long focus on making useful things for people. Stellar's utility, and focus on worldwide financial inclusion is why was drawn to work on my little corner of it. I'm focusing on the SDK rebuild in order to improve on some of the mistakes of the first build and to provide an API that would best enable Scala developers to build interoperable payments applications.

🔙 **Last Week**

This week has been solely focused on the SDK rebuild:

* Implemented the core `Horizon` type that can be constructed for different Horizon endpoints, but also for different effect types. Core Scala effect types are the first to be supported, with blocking (`Try`) and async (`Future`) methods out of the box.
* The first target is to enable a payment transaction. To that end, I've implemented two query endpoints.
  * **Server capabilities** - Primarily to find out what protocol version is in effect and whether Friendbot is enabled. (For now I'm considering to use testnet rather than the docker image, as the latter has a 5 minute start-up time).
  * **Account details** - To get the sequence id.
* I beefed up the [README for the horizon sub-project](https://github.com/Synesso/scala-stellar/tree/master/horizon#stellar-for-scala--horizon) and enabled [scaladoc publishing](https://synesso.github.io/scala-stellar/api/).
* Tested artifact publishing with jitpack
* Created an [exemplar project](https://github.com/Synesso/scala-stellar-horizon-exemplar#scala-stellar--horizon-exemplar) for getting started.


🍕 **Planned (Jun-Aug)**

* SEP-0007 - URI Scheme to Facilitate Delegated Signing
* SEP-0010 - Stellar Web Authentication
* Ongoing SDK rebuild effort.

✊
World of WoqlCraft - Ep.10 Tour on TerminusDB 2.0 and the new version of WOQL
Tags: database, git, video, tutorial
Published: 2020-06-07 12:21:26

---
title: World of WoqlCraft - Ep.10 Tour on TerminusDB 2.0 and the new version of WOQL
published: true
description: We had a tour at the newly release of TerminusDB 2.0, we have a play at the time-travel feature, going back and forth different commits, making a new branch. We also try using WOQL.js with the new console.
tags: database, git, video, tutorial
---
We had a tour at the newly release of TerminusDB 2.0, we have a play at the time-travel feature, going back and forth different commits, making a new branch. We also try using WOQL.js with the new console.

Find the source code from our [tutorial repo](https://github.com/terminusdb/terminus-tutorials).

Join the TerminusDB community at [Discord](https://discord.gg/Gvdqw97)
A simple way to debug memory leaks of event listeners using Chrome Dev Tools
Tags: devtools, debug, webpref, webdev
Published: 2020-06-07 12:08:15

---
title: A simple way to debug memory leaks of event listeners using Chrome Dev Tools
published: true
description: 
tags: devtools, debug, webpref, webdev
cover_image: https://aavtech.site/wp-content/uploads/2018/09/ChromeDevtoolsArtboard-1-8.png
---

The memory leaks are very hard to find. And if you faced with that problem you can start with analyzing event listeners.

So that very easy you just need to store all HTML elements on the page and make a snapshot of events using a [`getEventListeners(object)`](https://developers.google.com/web/tools/chrome-devtools/console/utilities#geteventlisteners) method

After that, you can manipulate with DOM and make a snapshot again and compare with previous

```js
// Store all elements on page 
allElements = [...document.querySelectorAll('*')]

// Then make a snapshot of all listeners
allElements.map(el => [el, ...Object.keys(getEventListeners(el))]).filter((e) => e[1]);

// After that, make some manipulations on page

// Finally print a snapshot and analyze it
allElements.map(el => [el, ...Object.keys(getEventListeners(el))]).filter((e) => e[1]);
```

I the next example I will hide one cat picture and check that  `pointerdown` and `wheel` events will be removed:

![debug memory leaks demo img](https://dev-to-uploads.s3.amazonaws.com/i/g4l0nh2eytjmsdpc59id.png)

---

[![debug memory leaks demo gif](https://media.giphy.com/media/MEMDMouSp5glx74BYZ/giphy.gif)](https://gph.is/g/ZkRM6p1)


---

if you have any question I am glad to discuss them in the comments!

(c) MurAmur