teleren/devto huggingface dataset:
Python Introduction
Published: 2021-07-24 16:45:18

## Working with virtual environment
When working on a python project its always advisable to create for it a virtual environment.

Steps for doing that include :
1. Navigate to the project's directory then

2. Run **python -venv dev**
-note **dev** is just the name of the virtual environment ,your free to name it however you prefer.

3.Activate the virtual environment using this command :
**source dev/bin/activate**

-**Note** if you are using windows run **dev\Scripts\activate** 
instead.

4. create a **requirements.txt** file using the command :
** pip freeze > requirements.txt**
- this file will contain all packages installed for thespecified project.

5. Install any packages required using **pip install <whatever you want to install>**

6. Repeat command in step 4, to update the requirements.txt.
Devlog #1: Creating a node.js mysql CMS
Tags: javascript, diy, devlog, project
Published: 2021-07-24 16:39:21


#Intro ▶️
So for the past few days, I have been working on creating a new blog and as every new blog needs a CMS. I decided to make my blog with MySQL as a database but it was a bit hard to find a nodejs MySQL CMS that I like. I tried forest Admin because it looked like the thing I was looking for but because I am not the one developing it I thought it was pretty limited when it came to customisation so I decided to make my own CMS from the grounds up, And this is going to be my journey of making and developing this CMS.

# Page parts 💻

## login 🗝

So the most important thing is a secure admin login to be secure the blog from anyone else and SQL injections so that is the first thing I started with

![Login page](https://i.ibb.co/z7hhNkG/frame-generic-dark-5.png)

So as you see the login page is fairly simple and only takes an email and password where the data is sent and validated. The password is validate and encrypted with bcrypt so that is nearly impossible to decrypt the password hash without knowing the password it self.

## Dashboard 🚪

![frame-generic-dark-1](https://i.ibb.co/CmDpPMh/frame-generic-dark-1.png)

For now, the dashboard is still empty and there is nothing in it but what I am planning is to put stats about the page visitation and posts reactions (if i decide to add reactions).

## Post creation and editing 🛠

![frame-generic-dark-3](https://i.ibb.co/JRt4vx9/frame-generic-dark-3.png)

The thing that I needed the most was a rich text editor that passes my uses and that was the main reason I didn't like a lot of the pre-made CMS:s for nodejs and MySQL. But I didn't want to build a rich text editor from the start so I decided to look if there was a pre-made open source one and after hours of looking for the perfect rich-text editor and looking throw a lot I finely found the perfect one TinyMCE which was perfect and customisable and has a lot of plugins that i need like code samples and pictures.

#### What I am planning to add more

*   formated tag editor
*   image uploading
*   dark theme for the code sample

## The articles list 📄

![frame-generic-dark-2](https://i.ibb.co/LkRdG9R/frame-generic-dark-2.png)

The article list was fairly simple to implement where I just created a table and then for each article from the database it just inserts a new row and then you can either edit or delete the article (If you have suggestions for more actions just let me know because i can't come up with anything).

And yah I just realised I forgot to change the "Dashboard" text in the top and i am going to do it.

# Conclusion 🔚

So what I am planning to do is that I see that I did good work with developing this CMS and I add enough futures to it then I am going to release it as an open-source CMS for Nodejs and MySQL.

I am going to continue the work on it and try to make it CMS as Wordpress or joomle and not only for blogs but for any type of website.
TIPS & TRICKS OF JAVASCRIPT & REACT
Tags: javascript, react, node
Published: 2021-07-24 16:33:03

#TIPS 1: Easiest way of string to integer conversion.

```
const value_1 = "1" 

const value_2 = "2"

function add(field_1, field_2){

  return field_1 + field_2;
}


add(+value_1, +value_2); 
```

#TIPS 2: Easiest way of float to integer conversion.
```
const floatToInt = 23.9 | 0;
```
#TIPS 3: Use Global object always should not need localStorage

***Note[if data is is static then you should use it. and don’t use any kind secret or confidential data here..]***

```
const user = {

  first_name: "Rowan",

  last_name: "Atkinson"
}

window.user=user
```

#TIPS 3: Don’t use if not necessary ternary (<statement>?<statement>:<statement>)

```
const DemoComponent = ()=>{

const [show, setShow] = useState(false)

   return (<div>

     {show? <Message/>: ''}

</div>)
}
```

##Right way with (&&)
```
const DemoComponent = ()=>{
const [show, setShow] = useState(false)

   return (<div>
     {show && <Message/>}
    </div>)
}
```

#TIPS 4: Don’t do it

```
if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}
```

##Do this short and simple

```
const variable2 = variable1  || 'new';
```

#TIPS 5: Don’t do it

```
Math.floor(4.9) === 4 // true
```

##Do this short and simple

```
~~4.9 === 4 // true
```
#TIPS 6: Don’t do it

```
switch (something) {

  case 1:
    doSomething();

  break;
case 2:
    doSomethingElse();
  break;
case 3:
    doSomethingElseAndOver();
  break;
  // And so on...
}
```

##Do this short and simple

```
const cases = {
  1: doSomething(),

  2: doSomethingElse(),

  3: doSomethingElseAndOver()
};
```

***[Note: This one has performance issue I prefer use this one when you have crying need. Switch statement is more faster than this solution***

#TIPS 7: Don’t do it

```
if(x == 1 || x == 5 || x == 7)  {
  console.log('X has some value');
}
```
##Do this short and simple

```
([1,5,7].indexOf(x) !=- 1) && console.log('X has some value!');
```
#TIPS 8: Don't do it

```
const param1 =1;
const param2 = 2;
const param3 = 3;
const param4 = 4;


function MyFunc =(param1, param2, param3, param4)=>{
  console.log(param1, param2, param3, param4)
}

MyFunc(param1, param2, param3, param4)

```
##Do this short and simple

```
const params = {param1: 1, param2: 2, param3: 3, param4: 4}

function MyFunc =({param1, param2, param3, param4})=>{
  console.log(param1, param2, param3, param4)

}

MyFunc(params)
```


#TIPS 9: Don’t do it

```
function Myfunc(value){
   if(value){
     console.log("you have a value")
   }else{
      throw new Error("You don't have a value")
   }
}
```

##Do this short and simple

***NOTE: If you check error first then it’s don’t go else block but if you do first one it will check first value is exist then if not found it will go the else block.***

```
function Myfunc(value){
   return !value ? throw new Error("You don't have a value") : console.log("you have a value")
}
```
Want to Ask something in React
Tags: react, html, javascript
Published: 2021-07-24 16:27:08

Hello everyone
I am making a new project and I am stuck at one point

The question is 
I have a list in my 'Home Page' and there is another 'Add User' page
So when I add a user on my 'Add User' page using a button, Then how can I show the list of users on my 'Home Page' using map function.

It's like using a button a add something on one page and then show that thing on another page.

I want the logic and some help 
Thank you
Next Version?
Tags: zimjs, canvas, javascript, launch
Published: 2021-07-24 16:19:40

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2wf5f2cqemtt1dconax.jpg)

Dr Abstract will announce the next version of ZIM at the ZIM ZOOM on Thursday, July 29 at 12pm EST.  The invite link can be found here https://zimjs.com/zoom

ZIM is a JavaScript Canvas Framework with conveniences, components and controls to help code creativity!  https://zimjs.com

Currently, we are on ZIM Cat 04 and will move to a new major version beyond Cat.  Please join us - all are welcome - on ZOOM as we announce the next version and will have time for conversation and questions.

ZIM has been called a "criminally underrated framework" - come see why!
Mount my Passport WD driver on MacOS Big Sur with NTFS read write
Tags: costeffective, free, ntfs, macos
Published: 2021-07-24 15:57:04

After upgrading my MacOS to big sure, i realized that some features did not work intuitively as previously. This includes my HD driver (MPassport).
Files are formatted with NTFS, and the Boss MacOS does not want to allow write. 

# Paid Solutions

There is iBoysoft NTFS for Mac and others.
But i solved the issue with simple script

# Free Solution

Plugin your HD drive, then check its volume name under /Volumes

let's say your volume origin name (ls -l /Volumes) is MPassport.

retrieve the disk name

```sh
disk_name=$(diskutil list | grep -i passport | awk '{print $6}')
```
then:

```sh
origin_name=MPassport
sudo umount /Volumes/${origin_name}
sudo mkdir /Volumes/${disk_name}
sudo mount -t ntfs -o rw,auto,nobrowse /dev/${disk_name} /Volumes/${disk_name}
open /Volumes/${disk_name}
```

Happy read/write !

More details https://gist.github.com/CharlesThierry/7305166b208d6f6cdd37962761d5ac23
Understanding Redis
Tags: redis, devops, discuss, database
Published: 2021-07-24 15:35:00

Redis is an inmemory data store

People misunderstand redis as only as plain key value store 

 ⭐ But it is a data structure server supporting different kinds of values 

Redis is used to handle 

⭐ Blocked tokens in Authorization
⭐ RabbitMq Queues, chat, messaging etc.

Redis helps resolving complex concepts with simple commands 

🔗 With rapidly changing data redis seems more adaptable than other popular databases like Mongo Db

🔗 But the only concern is the rapidly changing data should fit in memory

Feel free to add the benifits & points on redis 👇

For more tech information stay connected with me via [Twitter](https://twitter.com/Dhanush_Nehru)
Type Conversion in C++
Published: 2021-07-24 15:31:46

---
published: true
series: Competitive Programming
title: Type Conversion in C++
---

### Disclaimer:
> I am a beginner in competitive programming, and this is me documenting my learnings. So, anything I say is just what I think at the moment and should not be taken as hard truths.


## char to int

```cpp
main() {
  char c = '5';
  int num = c - '0'; 
  cout << num << endl;

  // OR

  int number = atoi(&c);
  cout << number << endl;
}
```

## int to char [only 0-9]
```cpp
main() {
  int num = 5;
  char c = num + '0';
  cout << c << endl;  // output: 5
}
```

## string to int

```cpp
main() {
  string s = "256alphabet";
  int num = stoi(s);
  cout << num << endl;  // output: 256
}
```

`stoi` will parse any string and return integer. Additonally takes the `base` as parameter.

```cpp
main() {
  string s = "001010";
  int num = stoi(s, nullptr, 2);
  cout << num << endl; // output: 10
}
```


## int to string

```cpp
main() {
  int num = 256;
  string s = to_string(num);
  cout << s << endl;  // output: 256
}
```

## string to vector\<char\>

```cpp
#define all(x) begin(x), end(x)

main() {
  string s = "5555";
  vector<char> v(all(s));
  for(auto& c: v) cout << c << ' ';  // output: 5 5 5 5
}
```

## vector\<char\> to string

```cpp
#define all(x) begin(x), end(x)

main() {
  vector<char> v = {'1', '2', '3', '4', '5'};
  string s(all(v));
  cout << s << endl;  // output: 12345
}
```

## vector\<int\> to string

```cpp
main() {
  vector<int> v = {12345, 54321};
  string s;
  for(auto& e: v) s.append(to_string(e));
  cout << s << endl;
}
```

## string to vector\<int\>

```cpp
main() {
  string s = "12345";
  vector<int> v;
  for(auto& c: s) v.push_back(c-'0');

  // OR

  vector<int> v_new;
  transform(all(s), back_inserter(v_new), [](auto& c) { return c-'0'; });
}
```

Okay! Now we understand basic transformation from one form to another.

Now let us see some base conversions.

## base 10 to base 2 [decimal to binary]
```cpp
main() {
  int num = 5; // binary : 0101
  string binary = bitset<8>(num).to_string();
  cout << binary << endl;  // output: 00000101
}
```

## decimal to hex|oct [ int -> string ]

```cpp
main() {
  int num = 16; // hex: 10
  stringstream ss;
  ss << std::hex << num;
  cout << ss.str() << endl;  // output: 10

  // for oct
  ss << std::dec << num;
  cout << ss.str() << endl;  // output: 20
}
```


## some base to another base(dec/hex/oct) [ string -> string ]

```cpp
main() {
  string num = "16";
  stringstream ss;
  // consider s to be decimal
  // decimal to hex
  int initial_base = 10;
  ss << std::hex << stoi(num, nullptr, initial_base);
  cout << ss.str() << endl; // output: 10
}
```


## Sources:
- [Decimal to Binary](https://stackoverflow.com/questions/22746429/c-decimal-to-binary-converting)

## Further Read:
- [Base 10 to Base N conversion](https://stackoverflow.com/questions/12713999/base-10-to-base-n-conversions)
Don't be too dependent on useState, useRef is there for you
Tags: beginners, react, nextjs, javascript
Published: 2021-07-24 15:19:27

Hello 👋
Hope all are doing good in this pandemic time. 


Whenever i am seeing any reactjs code snippets in internet i am noticing the unnecessary usage of `useState`. 

In react updating a state is a very expensive in terms of performance. The main reason is whenever the state updates the component will re-render again.

Here is an small example:
![Screenshot 2021-07-24 at 5.36.02 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627128370241/e2G3yi7dV.png)

In the above code i created a counter using `useState` when i am incrementing the counter `App component` is re-rendering again. There if you check the logs `Component initialised` got printed 4 times (1st time when component initialised and 3 times when i clicked on the `+` button). It is re-rendering the `App component` because i am updating the state on click of the `+` button.

Here we need to use state because our intention is to show the `counter` value in the document. 

Consider the following code 👇🏻
![Screenshot 2021-07-24 at 5.51.43 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627129308593/sUNjWfevy.png)

Here i am using two state variables one is for value next is to set type of input. Do we really need two state variables 🤔 ?. Actually why don't we try building this component without state ? the reason why i am saying like this is assume if we are building a form has many input fields in that case we need to pass value state to `input component` from `form component` if that's the case entire form component will re-render on every keystroke in any input. 

#### Solution
In the second example actually we don't need state. `useRef` is fine. Check the below code 👇🏻

{% codepen https://codepen.io/saketh-kowtha/pen/yLbzRLr %}

in the ☝🏻 snippet we are not using state but still we able to achieve what we want without out re-rendering. Even in form use case instead if passing state from `form` to `input` we can pass ref it will prevent unnecessary re-renders.

So what i would suggest is whenever you are dealing DOM manipulation like changing class name conditionally or changing any attribute of element etc.. then try to use `useRef`  instead of `useState`. it will prevent your app from too many re-renders.

Follow me on 
Linkedin : https://www.linkedin.com/in/saketh-kowtha/
Twitter : https://twitter.com/sakethkowtha
Github : https://github.com/saketh-kowtha

You can now extend your support by buying me a Coffee.


<a href="https://www.buymeacoffee.com/sakethk" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
Higher-order function in python
Tags: python, composition
Published: 2021-07-24 14:58:40

## Introduction 

A Higher-order function is a function that takes another function as a parameter or a function that returns a function. The built-in map, filter, and reduce functions are all examples of Higher-order functions. In this post, you will learn about decorators and nested functions.

## Nested Function

To understand Higher-order functions, you need to know about nested functions.  A nested function is a function within a function. The purpose of nested functions is to hide functionality from the global scope. The inner function cannot be called outside of the function. 

The following is example on how to create a nested function.
```
def outer_func(msg):

    def inner_func():
        print(msg)

    return inner_func


# Output: Hello Word
hello_word = outer_func("Hello World")
hello_word()


```
You see, the outer function returns the inner function, and the variable "hello_word" is bound by that function. If you would call the inner function outside of the outer, you will receive an error.

## Decorator

A decorator is a simple way to pass a function as a parameter. A benefit of decorators is that it adds functionality to existing functions. Another benefit because it makes your code readable or pythonic. 
  


The following is an example of how to use a decorator.
```
def double(f):

    def inner_func(*args):

        result = f(*args) * 2

        return  result


    return inner_func


@double
def add(x,y):

    return  x + y

@double
def subtract(x,y):

    return  x - y

#Output: 6
result = add(1,2)

print(result)

#Output: 8
result = subtract(5,1)

print(result)
```

Just like our previous example, the outer function returns the inner function. The annotation is used to call the outer function while the function below is passed as a parameter. A parameter inside the inner function is the same as a parameter in the function it decorates.  Adding a * to your parameter allows your function to take varying inputs.
ĐỊNH VỊ XE MÁY TẠI QUẬN 7
Tags: divixemayquan, dinhviquan7
Published: 2021-07-24 14:16:40

* Chỉ Cần Alo là có kỹ thuật đến lắp ĐỊNH VỊ XE MÁY QUẬN 7 uy tín, Lắp đặt dấu kín bí mật, Chúng tôi không lắp bình ắc quy xe máy, vị trí này dễ bị phát hiện. Lắp tận nơi bảo hành tận nơi. 

Hướng dẫn sử dụng và vận hành
⇒ Quý khách có thể dùng thử phần mềm bằng cách sau: Từ điện thoại của quý khách đối với điện thoại Android bạn vào CHplay, trên Iphone Bạn vào Appstore Tải chương trình T-Track pro về máy. Sau đó mở chương trình bạn mới tải về lên và làm điền thông tin như trong hình.

» Ổ số 1 bạn gõ: baovietgps.com
» Ô số 2 bạn gõ: DEMOBV
» Ô số 3 bạn gõ: 123456 và bấm đăng nhập
Hoặc từ máy tính quý khách có thể đăng nhập bằng cách truy cập trực tiếp từ địa chỉ website sau: www.baovietgps.com

Liên Hệ Bảo Việt Technology 
https://dinhvixemay.org/dinh-vi-xe-may-tai-quan-7.html
Hotline: 0903108661
(Zalo,Viber) 0923652365
Định Vị Cho Xe Máy Quận Tân Bình
Become a Productive Programmer
Published: 2021-07-24 13:47:59

In this video I'm talking about how to become a more productive programmer. Productivity is always a hot topic and it's something that a lot of developers struggle with. In order to become a productive developer you'll need to put in a lot of effort, but there are some ways to improve the way you work even in environments full of distractions!

🎥 Timeline
0:00 intro
0:30 deep work, shallow work
1:58 tip #1 - good preparation
3:57 tip #2 - own your calendar
8:27 tip #3 - split your tasks
9:56 why pomodoro technique doesn't work
10:47 working in a team
11:47 magic productivity techniques
12:44 Outro
Rails Dummy OTP verification with Nexmo API / Twilio
Tags: ruby, rails, webdev, newbie
Published: 2021-07-24 13:18:55


I recently stumbled on a web app based on helping people who need donations during this pandemic, but one thing I couldn't get right was sending OTP for phone number verifications since email was *optional*.
I decided to come up with a dummy idea!

## *Create a user table with a column for saving a temporary generated OTP code, and a column to set account state.*  

```
  create_table "users", force: :cascade do |t|
    t.string "email"
    t.string "phone_number"
    t.boolean "verified", default: false
    t.string "tmp_code"
   end
```

### Implement a method to generate a number from 1012 to 9292, in this case, I will always have  numbers of length 4

``` 
class User < ApplicationRecord
  after_create :set_sms_code

  private
  def set_sms_code
    code = Random.rand(1012..9292)
    self.tmp_code = code
  end
end
```
### In my controller, when a user enters a verification code. I catch it from the params and check it against the one I had saved in the database.
```
  def verify_code
    if current_user.tmp_code === params[:confirmation_code]
      current_user.update(activated: true)
      redirect_to root_path, notice: "account activated"
    else
      flash[:alert] = "invalid code"
      render :welcome
    end
  end
```

I know this was a dummy and probably unhealthy, I, later on, had a background job to set it to a different number every 30 minutes and resend it to the user.  

## Next: Part ||
I've created knex-graphql-utils, which optimizes your GraphQL server with PostgreSQL
Tags: typescript, graphql, postgres, node
Published: 2021-07-24 13:09:29

---
title: I've created knex-graphql-utils, which optimizes your GraphQL server with PostgreSQL
published: true
description: 
tags: typescript, graphql, postgresql, nodejs
cover_image: https://user-images.githubusercontent.com/10719495/126866657-a6ca9463-bac8-4056-9963-1f0aae8bf7fd.png
---

I've created a tiny library which improves performance for GraphQL + Knex.

# tl;dr

### Before

![image](https://user-images.githubusercontent.com/10719495/126906832-f991dd7d-b563-4fa2-9313-738f476d46c8.png)

### After

![image](https://user-images.githubusercontent.com/10719495/126906862-71b456bd-82da-46d1-b6d3-acd1c3233885.png)


- Filter `select` columns based on a query from clients
- Load relations without N+1 problem (pagination available!)

https://github.com/acro5piano/knex-graphql-utils

Currently only PostgreSQL is supported, but I'll support other RDBMS too if needed.


# Motivation

Creating a GraphQL service with a Relational Database is a hard thing. We should take care of:

- Performance for querying relations. N+1 problem will happen if you don't use Dataloader.
- `select *` make your server slow, but hard to filter columns based on requests.
- Pagination. [Dataloader pattern is hard to implement pagination](https://github.com/graphql/dataloader/issues/231) without a hacky `union` or window functions. `knex-graphql-utils` uses `row_number()` window function to do it.

As a developer, I noticed that I'm doing the same thing again and again - so I convert my work into a library.

The syntax is like this:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rl8u4p6io98ds8pv6dhx.png)

Please try it! Any feedback is welcome.

https://github.com/acro5piano/knex-graphql-utils