teleren/devto huggingface dataset:
State Hook
Tags: statehook
Published: 2020-08-02 18:37:41

Hooks let you use state and other React features without writing a class.

```javascript
import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
```
React class
```javascript
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
```
##Hooks and Function Components
We can use these functions components in React.  These are ``stateless components``.  They can be called ``function component``  Hooks don't work inside class.  We can use them instead of writing classes.

```javascript
const Example = (props) => {
  // You can use Hooks here!
  return <div />;
}
```

```javascript
function Example(props) {
  // You can use Hooks here!
  return <div />;
}
```

If you want to add state to function component.  You can add Hook `useState` function to it instead of converting it to a class. 
```javascript
import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);
```

Variable `count` could be called by anything. `useStae is used as same as `this.state` provides in a class.  State variables are preserved by React.

The argument to `useState()` Hook is the initial state.  We can pass string or number as an argument for example 0 is initial state.  We can call `useState() twice if we need to state two different values in state. 

The state variable `count` was declare and set it to 0. React will remember the current value between re-renders, and provide the most recent one to our function.  If we want to update the current `count`, we can call `setCount`.

##Updating State
In a class, we need to call `this.setState()` to update the `count` state.  In a function, we already have `setCount` and `count` as variables we don't need `this`

References:
https://reactjs.org/docs/hooks-state.html
Node,Mongo, Mongoose Essentials - CRUD App for Relational Database
Published: 2020-08-02 18:32:30

https://www.youtube.com/watch?v=5H0geGYv_A0

https://dev.to/mkilmer/how-create-relationships-with-mongoose-and-node-js-with-real-example-43ei

https://medium.com/employbl/build-database-relationships-with-node-js-and-mongodb-74e35c315cf

https://developer.mozilla.org/pt-BR/docs/Learn/Server-side/Express_Nodejs/mongoose
Battling my imposter syndrome with projects
Tags: career, juniordeveloper, impostersyndrome
Published: 2020-08-02 18:21:29

I recently finished my first personal project in a while. Between my cross-country move, job searches and Corona I haven't been coding as much as I should be. Because of this my imposter syndrome increased so much and I knew I needed to combat that before it got out of control.

My first step was to take a deep look at what I know are gaps in my knowledge or things that I haven't gotten down as solid as I'd like. Some of those things are CSS pre-processors, APIs and SVG. 

I then created an [advice generator](https://github.com/JennaKoslowski/Advice) to get more comfortable with all of those. I learned a lot and I was so proud of how it turned out... and then I decided to post it on social media and I realized something.

My third step is something I'm trying to do more often which is post about what I'm doing and learning. That way you get more confident talking about coding and getting more comfortable with the verbiage and having people see your work. 

Instagram and Twitter I post things without feeling too much pressure. I've posted problems I've had and bits and pieces along the way, whether they look good or not. It's all about the process. It's more transparent and informal.

However. I also know the importance of posting on LinkedIn and instantly my brain went in a million directions:

* What if no one likes it.
* It's not even that good.
* The design is mediocre/ trash.
* It's such a small project but still took me forever.
* It's a small project.
* It's nothing special.

Basically it boiled down to the fact that I'm not a designer mixed with imposter syndrome.

My roommate made me post it anyway and there hasn't been any interaction within the 30+ people who've seen it. But the world hasn't ended. No one's commented saying it's trash.

For me, the best way to combat my imposter syndrome is to not just code more but to post about it more. I'll create a project that mixes things I already know with things that make me want to tear my hair out in hopes of getting better.

While just one (unsuccessful) LinkedIn post isn't the cure I feel it's a huge step. I've never shared my code work there before despite the fact I want to make the switch to a front-end job. 

TL;DR:
1. Figure out what you're not confident about
2. Utilize those things in a project
3. Share the process and/or finished project
4. Talk about programming and code

### How do you battle imposter syndrome?
Data Science today :: Where do you or your skill fit in ?
Tags: datascience, database, python, file
Published: 2020-08-02 18:18:14

Image Courtesy : Oreilly

**Source / Scrape** : Like wiki pages, today's data source could be anything. Splunk query, Server log any device which produces data in any format (.csv, .log, .json, ,.log, .xml, .xls etc..). You need to be skilled in bunch of tools like Python / Pandas, Shell Scripts, JQ, CSV, Sed and so on..

**Data Cleansing** : Pandas is a good option, but its not limited to that. Community Edition of Pentaho PDI can help in data cleansing. SSDT (former SSIS) has transformations which help in data cleansing. Knowledge of RegEX will be of great help.

**Database** : Knowledge of database is key. Any RDBMS such as Microsoft SQL Server, Postgres, MySQL, Oracle) will do. I personally like MySQL 8 as it has NoSQL and API capability.

**Explore** : Jupyter / Anaconda / IPython + Pandas + Matplotlib is a good combination. SPARK with Zeppelin will also work, but too much work setting up the cluster.

**Deliver** : GraphQL or REST API is one option, accessing via DB (using ORM tools such as SQL Alchemy) or direct SQL will be time saving option.

**Transform** : Knowledge of powerful open source JS libraries such as D3.js, Chart.js will be helpful. Pentaho community edition is a good alternative. If you have access to Tableau (paid version) that is good too.

Knowledge of Docker will help you with one more more components given above. 

https://www.datascienceatthecommandline.com/1e/
Commandments to take a proactive approach to the job search process
Published: 2020-08-02 18:18:13

By building your self-confidence first and clearly defining your needs and desires, you will be in a better position to search for jobs that will have a lasting impact on your future. You'll know what you want - and what you don't want - on the job. You can also better visualize your way to this job and make immediate plans. For example, your next job might first require more skills that you don't yet have, and thus requires a few months of learning and practice.

Work-oriented self-reflection helps make sure you're on the right track. Self-reflection builds your blueprint for success.

Here is an exercise to help you think and think about your plan. At first, you might be surprised by how much you write! Seeing your written professional needs and needs can provide clarity or new insights you were not familiar with before. This self-reflection is designed to reach the heart of your career.

Maybe you have already decided what your dream job is, or maybe you have no clue. No matter where you are in this range, you must first design your own scheme for success and professional fulfillment. Use the exercise below to guide your self-reflection.

Note: Don't worry about getting the correct answer. Treat this exercise as an opportunity to start thinking about your personal and professional needs and desires.

You can always copy your notes from this exercise to a new document and continue working on it! For now, let's start!

**Why did you choose to pursue the new profession?**

**What questions do you currently have about the technology industry?**

**What skills do you want to improve or develop?**

**What are 2-3 personal values ​​that interest you above all? For example, it is "helping people."**

**What are your best preferences for a compatible work environment (geographical location, company size, type of employment, etc.)? The list can be whatever you want!**
Transitioning to a DEV
Tags: codenewbie, 100daysofcode, beginners, career
Published: 2020-08-02 18:12:56

So I’ve been taking the time during this quarantine, to pursue an interest of mine and take the leap of faith into switching careers. I’ve been slowly but surely teaching myself how to code, and have learned so much within the past 3 months. This week I will be starting my first internship with a software development company, and I’m so grateful and excited to be collaborating with great minds and learning more. This may not be a job but it is a huge deal for me because I doubted myself so much in the past of my capabilities, and now I’m here!! Of course, there’s so much more learning for me to do, and achieving my goals isn’t going to happen overnight but every achievement needs to be celebrated no matter how small. I’m so grateful to God and my amazing partner who has continued to support me. This might sound cliche, but it’s truly NEVER too late to go after your dreams.To document my journey, I've created a youtube page where I post about my 100 days of coding challenge. https://www.youtube.com/channel/UCKxFE0AFLVDBJUG7WkQK6mA?view_as=subscriber
Testing Exceptions with Pytest
Tags: python, testing
Published: 2020-08-02 18:12:01

Every time I end up wanting to test that an expected exception is thrown with [Pytest](https://docs.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions), I end up looking up the syntax, so here it is:

```python
import pytest

def test_my_exception_is_raised():
    with pytest.raises(MyException):
        my_function()
```

This test will fail if calling `my_function()` *doesn't* raise an exception of the type `MyException`.

But what if I want to check the exception has the expected message too?

```python
def test_my_exception_is_raised_with_message():
    with pytest.raises(MyException) as e:
        my_function()
    assert "my message" in str(e.value)
```

In this case, `e` is of type [`ExceptionInfo`](https://docs.pytest.org/en/stable/reference.html#exceptioninfo), not actually `Exception`, so you need to use `e.value` to get at the message. You can also assert things about the traceback of the exception via `e.traceback`, but I've not had a usecase for that recently.

While I was looking this stuff up again, I found out that you can actually clean this up a bit in some situations, by doing a regex match on the string representation of the exception thrown, like this:

```python
def test_my_exception_is_raised():
    with pytest.raises(MyException, match=r"^My message.*"):
        my_function()
```

This uses [`re.search`](https://docs.python.org/3/library/re.html#re.Pattern.search) to do the matching, and see the [Python docs](https://docs.python.org/3/library/re.html#regular-expression-syntax) for a quick regex reference.

I think I'd use this regex method if I wanted to assert something like the presence of a particular error code somewhere in my error message, but the more verbose version when I'm asserting something about the message that depends on the context of my test, such as is the ID of the thing I just tried to put into my database in the error message.

```python
def test_this_raises_error_code_1234():
    with pytest.raises(MyException, match=r"1234"):
        myfunction()

def test_this_raises_error_including_item_id_and_data():
    my_test_id, my_test_data = "XXXX", {"some": "data"}
    my_test_object = MyThing(id=my_test_id, data=my_test_data)

    with pytest.raises(MyException) as e:
        my_function(my_test_object)

    assert f"Couldn't process MyThing {my_test_id} with data {my_test_data}!" in str(e.value)
```
Day 3: Navbar to CSS Grids
Tags: react, beginners, learning
Published: 2020-08-02 18:11:49


###<center>Collapsing Menu Bar</center>
___
My navbar is up, woot! At first my hamburger menu wasn't quite showing up until I realized that its bc of how we sized things on `flex` and `width` within the `.menu-content-container`🤦🏻‍♀️

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

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

###<center>CSS Grids & Data</center>
___
Where the struggle begins: my lack of familiarity w/ [React Router.] (https://reactrouter.com/web/api/Router) My "Trending Posts" do not show up on `Home` in place of my `404`.
###page-rend.js
```javascript
import React from "react";
import { useRouteMatch } from "react-router-dom";

const generatePage = (page) => {
  const component = () => require(`./pages/${page}`).default;

  try {
    return React.createElement(component());
  } catch (err) {
    console.warn(err);
    return React.createElement(() => 404);
  }
};

export default function PageRenderer() {
  const {
    params: { page },
  } = useRouteMatch();

  return generatePage();
}
```
###home.js
```javascript
import React from "react";
import { PostMasonry } from "../components/common";
import trending from "../assets/mocks/trending";

const trendingConfig = {
  1: {
    gridArea: "1 / 2 / 3 / 3",
  },
};

export default function Home() {
  return (
    <section className="container home">
      <div className="row">
        <h2>Trending Posts</h2>
        <PostMasonry posts={trending} columns={3} />
      </div>
    </section>
  );
}
```
###app.js
```javascript
import React from "react";
import Navigation from "./components/nav";
import "./assets/scss/base.scss";

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from "react-router-dom";
import PageRenderer from "./page-rend";

function App() {
  const user = {
    firstName: "Thit",
    lastName: "Nguyen",
  };

  return (
    <Router>
      <div className="App">
        <Navigation user={user} />
        <Switch>
          <Route path="/:page" component={PageRenderer} />
          <Route path="/" render={() => <Redirect to="/home" />} />
          <Route component={() => 404} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;
```

###<center>Possible Resolutions/Pace Is the Trick</center>
___
I've got a hunch that it has something to do with how the `<Router>` and `<Switch>` component categories are set up because, everything else seems to check out.

So for now, I'm going to dive into the documentation and search for sources to get a better understanding of how all of this processes before going any further.

So far, learning React these past few days has taught me:

1. Patience
2. Punctuation
3. Literalness
4. Humility


######Image Credit 一 [bluumind] (https://instagram.com/bluumind/)
What the `Nullish coalescing operator (??)`
Tags: javascript, codenewbie, beginners, webdev
Published: 2020-08-02 18:10:36

Well, you must be wondering what I am going to talk about! Today, I learn about a peculiar operator which modern javascript supports, known as **Nullish Coalescing Operator(??)**.
So what is this operator?
Syntax:
```
Expression1 ?? Expression2
```
So, from the above syntax, you can see that
* It is a binary operator( i.e. it requires two operands / expressions ) and 
* returns the value of the first expression which is not null or undefined
Example: 
```
let age = a ?? b
```
Here, the age variable will contain the value of `a` if it is not `null` or `undefined`, otherwise, it will contain the value of `b`.

Well, Basically It turns into the below code
```
// consider a and b is known
if(a == null || a == undefined)
{
   age = b;
}
else
{
  age = a;
}

```
NOTE: ?? operator works similar to the || (logical-OR) but the only difference is that  the || operator checks for `falsy` values and ?? checks for the values that are `null` or `undefined`
```
let var1 = 0 ?? 23  // var1 = 0
let var2 = 0 || 23  // var2 = 23
```
Limitation: 
* We can't use this ?? operator with && or || without explicit parantheses.
Example:
```
0 && 2 ?? 3  // Uncaught SyntaxError
( 0 && 2 ) ?? 3 // 0
```
2nd code works perfectly fine and returns 0 because the code becomes `0 ?? 3` and because 0 is not null or undefined the output is 0. :wink:

I Hope, you learnt something new today and will find this useful. As this is my first post on this amazing platform, please spare me, if the post has any error. 
Have a good day and night as well :stuck_out_tongue: 

**Resources:** (for more information)
>https://javascript.info/nullish-coalescing-operator
>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
[ podcast ] My First Freelancing project - 8 mistakes to avoid when freelancing
Tags: podcast, webdev, beginners, codenewbie
Published: 2020-08-02 18:10:15

Hey there!

{% spotify spotify:episode:6ztZhF1oBKl7OGBGfXd9Ne %}

New episode out. I recently took up a freelance project, so reemphasizing on these 8 points that you need to know. I have also included my own experience, the money I charged etc., at the end of the podcast.

Hope you find it interesting. Consider *following* if you liked it. 

You can find more articles are https://www.tharunshiv.com

{% user developertharun %}
Top 10 linux basic commands
Tags: linux, beginners, tutorial
Published: 2020-08-02 18:05:20

Hi, This is my first post but have experience of about 10 years in php, coding and web technologies. In this first post, I would like to share about my dream, which is very old and couldn't work on it since 9 years now. But, this year I promised myself to start working on it anyhow. so, here I am with my first tutorial video which took more then 3 months to make :|

I will be sharing top 10 commands plus few more commands which will be useful for any beginner. I hope you all like it and I will be curiously awaiting for your feedback/comments.
Kindly excuse me, if I missed anything. Here is the link to it https://youtu.be/EF2DenRW2c4

I will add next section soon, where we will see another important aspect of linux which is roles and permission. So stay connected.
Thanks
kscript from docker
Tags: bash, docker, kotlin, kscript
Published: 2020-08-02 18:07:13

---
title: kscript from docker
published: true
date: 2020-08-02 18:03:57 UTC
tags: bash,docker,kotlin,kscript
canonical_url: https://le0nidas.gr/2020/08/02/kscript-from-docker/
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/qr6aax3rvszn0wvwot52.png
---

This is one of those cases that you go down the rabbit hole and end up doing ten different things before the one that you initially wanted to!

My original intention was to try out [kscript](https://github.com/holgerbrandl/kscript). What I ended up doing is learning about [dockerfiles](https://docs.docker.com/engine/reference/builder/), building images and trying to run `.kts files` without having kscript, or [kotlin](https://kotlinlang.org), installed locally in my machine!

#### The result

A [github repository](https://github.com/le0nidas/kscript-from-docker) that you can clone, run the install script and have a `kscript` executable that works as described [here](https://github.com/holgerbrandl/kscript#script-input-modes).

#### Why?

I wanted to play with `kscript` but did not want to install it on my machine. I don’t like _bloating_ my OS by having libraries and software that might not be used often.

#### How?

Having everything installed in a docker image and use containers to play with `kscript` was a one way street for what I wanted to achieve.

##### Dockerfile

It was [my first dockerfile](https://github.com/le0nidas/kscript-from-docker/blob/main/Dockerfile) but there are tons of tutorials that helped me out. I ended up using alpine, installing java through its repositories, [sdkman](https://sdkman.io/) using its installation guide and kotlin, kscript through sdkman!

Finally, `kscript` was added as the image’s entry point which means that every time a container is being run `kscript` will be the first command that gets executed.

And it worked for the most parts. By executing

> docker run –rm -i kscript < params >
> 
> --rm to remove the container after its done, -i to have the script’s output passed to the terminal</cite>

I was able to use `kscript` as described in its repository, except for the case of having a `.kts file`!

##### kscript-router.sh

For the case of a `.kts file` what turned out to solve my problem was to pass the file’s entire content. And this is part of what [kscript-router.sh](https://github.com/le0nidas/kscript-from-docker/blob/main/bin/kscript-router.sh) does. It checks if the first parameter is a .kts file and if so it passes its contents to the container. In every other case it passes all given parameters directly to the container.

##### install.sh

To tie everything together I added a script that creates the image, adds the _router_ script to the user’s path and creates an alias, named `kscript`, for executing the _router_.

## [kscript-from-docker](https://github.com/le0nidas/kscript-from-docker/)
Introduction to Express (Part 1)
Tags: node, express, npm, webdev
Published: 2020-08-02 18:00:22

Express is a node framework for creating the backend of the application. A framework is a set of rules that are pre-defined for the smooth development of the application. This helps in making big and stable projects. A framework is different than a library. A library is used for solving small problems. It has a limited number of functionalities. The framework provides a whole set-up for application development. We just need to include our custom requirements.

JavaScript was earlier used as the client-side language for browser interactivity. With the introduction of Node, JavaScript was able to get executed at the CLI and started used for backend development purposes.

There are many frameworks for backend development available on NPM, express is very popular. Being popular and a huge developer community supporting it, it makes things easy for someone who is just starting up, as there are many tutorials available, with community support we will be able to find solutions to our coding problems.

A website generally contains a lot of dynamic pages. To navigate to these dynamic pages a concept routing is used in the express. Let us try to understand routing in express by the help of an example. 

```
//First we install the express framework inside our project folder
C:\Users\user_name\project\FirstExpressProj> npm install express --save

//Then we include express.js in our main file that is generally app.js or index.js

var express = require("express");

var app = express();

//We use the get method to access the required website like  -->> https://localhost:3000
app.get("/", function(req, res){
	res.send("Hi There");
});

// To access the route https://localhost:3000/dog
app.get("/dog",function(req, res){
	res.send("Hi Dogu, How are you doing");
})

// The listen method defines the port on which the server runs, here 3000
app.listen(3000, function(){
	console.log("Server has started!!!");
});
```

In the above article, we studied the introduction to express. Also, we saw how to install express, include express in our project, and some basic routing with the help of an example. In the next article, we will see, how to include a file, send HTML structure, and some other advanced topics.