teleren/devto huggingface dataset:
Code Smell 46 - Repeated Code
Tags: oop, codenewbie, tutorial, webdev
Published: 2020-12-08 04:18:57

*DRY is our mantra. Teachers tell us to remove duplication. We need to go beyond.*

# Problems

- Code Duplication

- Maintainability

# Solutions

1. Find repeated patterns (not repeated code).

2. Create an abstraction.

3. Parametrize abstraction calls.

4. Use composition and never inheritance.

5. Unit test new abstraction.

# Sample Code

## Wrong

{% gist https://gist.github.com/mcsee/b6df5d98efbecc9be783006d364e63f8 %}

## Right

{% gist https://gist.github.com/mcsee/4eb63e5acfcdda39b24e3f6a73eb0bdb %}

# Detection

Linters can find repeated code. 

There are not very good finding similar patterns. 

Maybe soon machine learning will help us find such abstractions automatically. 

For now, it is up to us, humans.

# Tags

- Duplication

# Conclusion

Repeated code is always a smell. 

Copying and pasting code is always a shame.

With our refactoring tools, we need to accept the duplication remove challenge trusting our tests as a safety net.

# Relations

{% post https://dev.to/mcsee/code-smell-11-subclassification-for-code-reuse-1136 %}

# More info

[Don't repeat](https://deepdive.hashnode.dev/dry-dont-repeat-yourself)

# Credits

Photo by <a href="https://unsplash.com/@itookthose">Sid Balachandran</a> on <a href="https://unsplash.com/s/photos/parrot">Unsplash</a>

* * *

> Copy and paste is a design error. 

_David Parnas_
Understanding Rust Imports
Tags: rust, namespace, import
Published: 2020-12-08 04:01:52

I have to reference this all the time :D

# Import example.rs into main.rs (same folder)

```
File Structure:
\src
  -example.rs
  -main.rs
```

example.rs:

```rust
// example.rs
pub fn my_function() {
    println!("You called my_function!");
}
```

main.rs:

```rust
// main.rs
mod example;

fn main() {
    example::my_function();
}
```

# Import example.rs into main.rs (example.rs in examples folder)

```
File Structure:
\src
  -main.rs
  \examples
    -example.rs
    -mod.rs
```

examples/example.rs:

```rust
// examples/example.rs
pub fn my_function() {
    println!("You called my_function!");
}
```

examples/mod.rs:

```rust
// examples/mod.rs
pub mod example;
```

main.rs:

```rust
// main.rs
mod examples;

fn main() {
    examples::example::my_function();
}
```

# Import example1.rs into example2.rs (then call example2 from main.rs)

```
File Structure:
\src
  -example1.rs
  -example2.rs
  -main.rs
```

example1.rs:

```rust
// example.rs
pub fn my_function() {
    println!("You called my_function!");
}
```

example2.rs:

```rust
use crate::example1;

pub fn call_example_function() {
    example1::my_function();
}
```

main.rs

```rust
// it's crazy. You have to reexport the example1 from main.rs so that example2 can see this.
pub mod example1;
mod example2;

fn main() {
    example2::call_example_function();
}
```

# Conclusion

It's really complicated. I'm not gonna try to memorize this.
Python3 programming - Exercise 3 - More on data types and comments
Tags: python, beginners, programming, tutorial
Published: 2020-12-08 03:49:58

## More on data types and comments

There are other data types other than those mentioned earlier in `Exercise 2 (Data Types)`. We shall discuss the `boolean` data type.

This data type can only be `True` or `False`. Boolean values are generated when values are compared or when there is a condition. `Eg 1 < 2 is True, 1 > 2 is False` .

## Examples

```python
is_online = True
is_swift = True
is_human = False
```

### Note

Boolean values are case sensitive. Upper-case `T` for `True` and `F` for `False` , in python.

## Comment

A comment is a piece of text that mostly should tell why or what we are trying to achieve. The `#` symbol, placed ( inserted) at the beginning of the line, comments the line ( the line is ignored by the interpreter).

## Examples

```python
# Hello world program
# Display Hello world for the user to see
# Using the print function
print("Hello world")
```

The first three lines starting with `#` are comments. A comment is ignored during execution. You can also comment out some lines during debugging.

### Note

Whatever that comes after the `#` would be ignored.
`print('hello world') # greetings` , _greetings_ would be ignored.

## Practicals

1. In `Exercise 2 (Data Types)`, add comments to your solutions to give the why/what the line is doing or meant to do ( remember that not all lines need a comment if the code is descriptive itself).

1. - How many comments are there in the code below?
   - Which line numbers, would be displayed and why?
     ![practicals](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/psf8knuz0zqfprarem40.png)
 
## Summary

- A boolean value is `True` or `False`.
- These values are generated during the comparison of two or more values.
- A comment is supposed to explain, "the" what or why in the code ( line)
- We can also use it to state how we want to reach our solution
- Use `#` to create a comment
Mirror a Hugo Site
Tags: archive, hugo
Published: 2023-01-06 01:12:14

---
title: Mirror a Hugo Site
published: true
date: 2020-12-08 03:41:17 UTC
tags: Archive,Hugo
canonical_url: https://brandonrozek.com/blog/mirrorhugosite/
---

I’m a big proponent of having offline copies of content. Especially when I’m on travel and don’t have easy Internet access. Using the built in hugo webserver and a reverse proxy, I will show how we can host a local mirror of a Hugo site.

## Systemd Service

To begin with, let’s create a systemd service that will start up the Hugo webserver automatically. To demonstrate this, I will show a mirror of my website.

Edit `/usr/lib/systemd/system/brandonrozek.service`

```
[Unit]
Description=Mirror of brandonrozek.com
Wants=httpd.service
After=httpd.service

[Service]
User=brandon
Type=simple
WorkingDirectory=/home/brandon/repo/brandonrozek.com
ExecStart=/usr/bin/hugo serve --appendPort=false -D -p 22160 -b http://localhost/brandonrozek

[Install]
WantedBy=multi-user.target

```

Replace `httpd` with whatever reverse proxy service this depends on. For every site you mirror, you need to make sure that the port (specified by `-p`) is different.

Now let’s start and enable the service.

```
sudo systemctl start brandonrozek
sudo systemctl enable brandonrozek

```

## Nginx Config

If you are using Nginx as your reverse proxy, we will need to create a config at `/etc/nginx/sites-available/brandonrozek.conf`.

```
server {
    location /brandonrozek {
        proxy_pass http://localhost:22160;
        proxy_http_version 1.1;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr; 
        proxy_set_header Host $host;
    }
}

```

Then to enable it.

```
sudo ln -s \
        /etc/nginx/sites-available/brandonrozek.conf \
        /etc/nginx/sites-enabled/
sudo systemctl restart httpd

```

## Apache HTTPD Config

If you are using apache as your reverse proxy, create a config at `/etc/httpd/conf.d/brandonrozek.conf`

```
<Location /brandonrozek>
    ProxyPass http://localhost:22160/brandonrozek retry=0 timeout=5
    ProxyPassReverse http://localhost:22160/brandonrozek
    ProxyPreserveHost On

    Order allow,deny
    Allow from all
</Location>

```

Then restart the `httpd` service.

```
sudo systemctl restart httpd

```
#MyNotes Make Active Menu When Clicked in Vue Js
Tags: vue, vue5, mynotes
Published: 2020-12-08 03:26:06

![active menu](https://dev-to-uploads.s3.amazonaws.com/i/24sh05awp2tnp1v3m4gq.png)

Untuk membuat menu active secara dinamis seperti gambar diatas, pertama kita harus membuat active menu secara manual terlebih dahulu. Jika sudah bisa membuat seperti gambar diatas maka kita selanjutnya perlu membuat sebuah fungsi yaitu:

1) Buat hari diatas kedalam array yang mana nanti akan kita looping

```javascript
...
setup() {
    const days = ref<string[]>(["selasa","kamis","jumat","summary"])
    return {
      days
    }
}
```

2) Sekarang kita implement ke dalam navigationnya, kita looping array nya. 

```html
<div class="dashboard__nav_days">
 <span v-for="(dayData, i) in days" :key="i">
   <span class="dashboard__nav_days__item">{{ dayData }}</span>
 </span>
</div>
```

3) Jika sudah berhasil terlooping, selanjutnya buat default value untuk dikasi default active nya. Sekaligus kita buat ketika hari yang lain di click active nya ikut pindah

```javascript
...
setup() {
    const days = ref<string[]>(["selasa","kamis","jumat","summary"])
    const day  = ref<string>("selasa")
    return {
      days,
      day
    }
}
```

```html
<div class="dashboard__nav_days">
 <span v-for="(dayData, i) in days" :key="i">
  <span v-if="day === dayData" class="dashboard__nav_days__item dashboard__nav_days__item--active">{{ dayData }}</span>
  <span v-else @click="day = dayData" class="dashboard__nav_days__item">{{ dayData }}</span>
 </span>
</div>
```

4) Nah sekarang buat Get value hari yang sedang active. Rencananya buat di kirim kepada API buat return data sesuai hari

```javascript
import { ..., watch } from 'vue';
...
setup() {
    const days = ref<string[]>(["selasa","kamis","jumat","summary"])
    const day  = ref<string>("selasa")
    watch(day, (day, prevDay) => {
      // console.log(day, prevDay)
    })
    return {
      days,
      day
    }
}
```

### Thanks 🙏
Golang basic: Input Output
Tags: go, tutorial
Published: 2020-12-08 00:33:30

There is 2 type of interface, GUI and the second one is CLI(Command Line Interface) it just show you text. The purpose of write code is to get an input and give output. each programming language has their way to do that. if you from c it gonna be easy cause the way is similar. let's code

## Output Program
create first program it will be good if we start with hello world program it simple and pretty cool. let's we create file `main.go` open it in your love code editor.
write code below.

``` golang
package main

import "fmt"

func main() {
    fmt.Println("Hello World")
}

```
First we declare `main` as package name it will tell the program what package is it. program will look for package `main` to run program first. 

`import` key to import package to go's file you can't use `fmt` if you not import it first. there is many go packages that you can using it.

`func main()` is a function `main`. what code you write in this block it will be run first. 

`fmt.Println("Hello World")`to use package that you have imported before(fmt) just write what package is, for example fmt.(dot) and following what function you need to call. this line will print out "Hello World" to your console. 

to run our code, go to where the file was saved and open te terminal.
``` bash
go run main.go
```
it will show you text 
``` bash
Hello World
```
## Input Program
get input user from console is like a magic what your input, it will show to the console let's we edit the file `main.go`

``` golang
package main

import "fmt"

func main() {
  var name string;

  fmt.Printf("Write your name : ")
  fmt.Scanf("%s", &name)

  fmt.Printf("Hello my name is %s", name)
}
```
`var name string` it will declare variable name as string. We will learn about data type and variable next. 

There is new function we use its `Scanf` it will get user's input. %s it will tell the program that the data type of variable is string and &name is variable that where input use will be stored.
don't forget to add `&` before the variable name.

`fmt.Printf` as before we print program with `Println` but it is without formatting and `Printf` will format what you want to show to user.
"Hello my Name is %s" the %s will replaced by name so what you write in name it will change %s.

let's we run program.
``` bash
go run main.go
```
we will get output
``` bash
Write your name : 
``` 
Input your name 
``` bash
Write your name: shellrean
```
The output will be
``` bash
Hello my name is shellrean
```

## Conclusion 
We have write simple input and output program with go, we have use `Println`, `Printf`, `Scanf` function from `fmt` package to create our simple program. dont forget to change the code if you have and idea to improve the code.

challanger:
Write code that will show
``` bash
I love learn go
```
Material UI File Upload example
Tags: react, materialui, file, upload
Published: 2020-12-08 03:25:05

In this tutorial, I will show you way to build Material UI File Upload example with Rest API. The React App uses Axios and Multipart File for making HTTP requests, Material UI for progress bar and other UI components. You also have a display list of files’ information (with download url).

## Overview

We’re gonna create a Material UI File upload application in that user can:
- see the upload process (percentage) with progress bar
- view all uploaded files
- link to download the file when clicking on the file name

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

## Technology
- React 17
- Axios 0.21.0
- Material UI 4.11.1

## Rest API for File Upload & Storage
Here is the API that our React App will work with:
- *POST* `/upload`: upload a File
- *GET* `/files`: get List of Files (name & url)
- *GET* `/files/[filename]`: download a File

You can find how to implement the Rest APIs Server at one of following posts:
- [Node.js Express File Upload Rest API example](https://bezkoder.com/node-js-express-file-upload/)
- [Spring Boot Multipart File upload (to static folder) example](https://bezkoder.com/spring-boot-file-upload/)

Or: [Spring Boot Multipart File upload (to database) example](https://bezkoder.com/spring-boot-upload-file-database/)

## React App for Material UI upload Files
After building the React project is done, the folder structure will look like this:

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

Let me explain it briefly.

- `upload-files.service` provides methods to save File and get Files using Axios.
- `upload-files.component` contains Material UI upload form, progress bar, display of list files with download url.
- `App.js` is the container that we embed all React components.

- `http-common.js` initializes Axios with HTTP base Url and headers.
- We configure port for our App in `.env`

For more details and Github Source code, please visit:
[https://bezkoder.com/material-ui-file-upload/](https://bezkoder.com/material-ui-file-upload/)
Escape character in python
Tags: python, dev, tutorial
Published: 2020-12-08 03:06:02


 Escape characters
The backslash, \, is used to get certain special characters, called escape characters, into your string.
There are a variety of escape characters, and here I am going to show you the most useful ones:
• \n the newline character. It is used to move text to the next line. Here is an example:
```python
print('Hi\neveryone!')
```
Result
```
Hi
There!
```
another example
```python
print('did you\nunderstand\n\nwhat happen\n\n\nhere')
```
Result
```
did you
understand

what happen


here
```
looking at the example above and its result you will notice that the gap between each line is different. did you notice that? Yeah! that is because we put different newline character between the sentence in our code. check the code again did you see the "\n" use once twice and three times between the sentence? so, the more you add the character the more it ommit the next line. "\n" ommit just next line, "\n\n" ommited next two line "\n\n\n\" ommited next three line etc.

• \' this is used to insert apostrophes into strings. assuming you have the following string:
```python
myWord= 'I can't commit error'
print(myWord)
```
This will produce an error because the apostrophe will actually end the string. You can use \' to get around this:
```python
myWord = 'I can\'t commit error'
print(myWord)
```
Result
```
I can't commit error
```
Another option is to use double quotes for the string :
```python
myWord="I can't commit error"
print(myWord)
```
Result
```
I can't commit error
```
• \" is similar to \' i.e you can use double quote instead of single quote for example
```python
myWord='I can\"t commit error'
print(myWord) 
```

• \\ This is used to get the backslash itself. For example:
```python
newline = '\\n is used for newline'
print(newline)
```
Result
```
\n is used for newline
```
run the code. did you see the backslash? yeah! despite the fact that "\n" it self is used for newline and it is inside our code above yet it doesn't move to next line because the two backslash is interpreted and n is consider as text.

• \t the tab character this is used to give tab space.
example
```python
tab_word="I \twas \tgiven \ttab"
print(tab_word)
```
Results
```
I     was     given     tab
```
try to confirm the code with the result did you see the tab space between them. try more code
Codes
```python
mixing_tab= "I \twas \t\tgiven \t\t\tdifferent \t\t\ttab"
print(mixing_tab)
```
Result
```
I     was         given             different             tab
```
there are more special character which we are going to discuss later but practice this for now and enjoy!
Share Your Scaling Experience
Tags: discuss, development, devops, scaling
Published: 2020-12-08 02:43:38

---
title: Share Your Scaling Experience
published: true
description: 
tags: discuss,development,DevOps,scaling
---
We all someday in our career thought or at least initiated some action towards scaling an application.
Would you like to tell everyone what's your biggest achievement in terms of scaling applications? 


### For me: 
There is not many, and in my short 4Yrs of career, I have managed to store Timeseries Data on mongo in such a way(precalculated), which would help eventually to retrieve the data easily, and the APIs would take from few `seconds`, 
 `minutes` to some `ms` or similar.

## What's your story?
Number in JS
Tags: javascript
Published: 2020-12-08 02:42:00

**In the name of Allah the most merciful and the most gracious**
Today is turn to Number data type in JS which is a primitive data type.
We write number in js without quote unlike string.
For example
```
let studentGrade=56;
console.log(studentGrade);
// result->56;
```
We don’t have any more types for numbers unlike other languages e.g kotlin ,c++ and java.
Just we have number data type.
We can convert number which is inside quote into number.
We can find the type of a data by typing typeof.
Here is the demo:
```
let number=’4.5’;
console.log(typeof number);
//result -> string
console.log(typeof Number(number));
//result -> number
```
We can use parseInt() and parseFloat().
The first one converts decimal number into whole number.
The second one converts whole number into decimal number.
```
let price=45.5;
console.log(parseInt(price));
//result-> 45
Let fruitPrice=10;
Console.log(parseFloat(fruitPrice));
//result-> 10.0
```
# Math operations
As we know from school we studied math and it’s operations those operations are in JS like +,-,* and /.
Here we have so many built-in methods to work math here.
**Examples:**
```
let x=9;
let y=5;
let total=x+y;
console.log(total);
//result -> 14
let difference=x-y;
console.log(difference);
let product=x*y;
console.log(product);
let division=x/y;
console.log(division);
let remainder=x%y;
console.log(remainder);
//result -> 4
```
The modulo operator returns the remainder.
For example, 4/2=2 and the remainder is zero because these two numbers are fully dividable.
4/3=1.3333333333 and 4%3=1 shows the remaining amount between 4 and 3 is 1.
We can use ** to use power.
```
let number=2;
let square=number**2;
console.log(square);
//result -> 4;
```
We can use Math.pow() instead of ** which are the same.
Math.max() or Math.min() …

You can learn more about Math built-in operation by clicking the below link
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Math
Swapping Variables in python
Tags: python, dev, tutorial
Published: 2020-12-08 02:29:00


##How to swap variables in python
Quite often we will want to swap the values of two variables, a and b. It won't yield what we need if we try the following:
Codes
```python
x=3
y=4
x = y
y = x
print('x=',x)#return 4
print('y=',y)#return 4
```
Result
```
x=4
y=4
```
In the above code it might look a little suprise that we still can't get what we need even though it look like we have swapped the value they assigned. have you happened to have used the above and felt shocked? Yes! i alse have done the same mistake. Now what is the logic? where is the error? 
Assuming x is 3 and y is 4. The third line will set x to 4, which is good, but
then the fourth line will set y to 4 also because x is now 4. The trick is to use a third variable to
save the value of x like the following codes:
Code:
```python
x=3
y=4
old_x = x
x = y # x is now 4
y = old_x # y is now the old_x i.e 3
print('x=',x)
print('y=',y)
```
Result
```
x=4
y=3
```
In many programming languages, this is the usual way to swap variables. however,python provides a nice shortcut below
```python
x=3
y=4
x,y = y,x # we have swapped here
print('x=',x)
print('y=',y)
```
Result
```
x=4
y=3
```
 The examples above swap the value that each of them stored. 
 x,y =y,x  ==> these code is interpreted as 
 x=y, y=x 
 the most amazing part in this python shortcut is that it can accept as much as the number of variables we want to swap. try the following codes
Codes:
```python
 a=1
 b=2
 c=3
 d=4
 a,b,c,d=c,d,a,b
 print('a is ', a)
 print('b is ', b)
 print('c is ', c)
 print('d is ', d)#we use "," to join the string with d
```
Results
```
a is 3
b is 4
c is 1
d is 2
```

 Run the code did you see their result? you can use it to swap 5,6 and as many as you want.
feel free to use whichever method you prefer.
The latter method, however, has the advantage of being shorter and easier to understand.
Before we stop there is one more advantage about this shortcut and that is destructuring! i mean with this method you can make your code short when you are assigning value to variables. consider the following codes
```python
a,b,c,d=1,2,3,4 # shortcut codes
print('a is ', a)
 print('b is ', b)
```
Result
```
a is 1
b is 2
```
  The shortcut codes above is the same thing as:
 a=1
 b=2
 c=3
 d=4
 So, if i were to assign value for 5 variables and swap them it is very easy for me with just two lines of code below
```python
 a,b,c,d,e=10,20,30,40,50
 a,b,c,d,e = c,e,d,b,a
print(a)
print(c)
```
Results
```
30
40
```
 with that two lines of codes i have done swapping 
 first line : a=10,b=20,c=30,d=40,e=50 
 second line : a=30,b=50, c=40, d=20, e=10
 so if you print before the second line you get first line values while second line value if the print is done after second line.
 did you find these helpful? then don't forget to follow me here, instagram and on twitter.
 Enjoy coding!