teleren/devto huggingface dataset:
Props vs. State in React
Tags: react, javascript
Published: 2021-10-07 16:50:00

One question that came up when working with React was: What's the difference between `props` and `state`? But before we explore their difference, let's look at their similarities: `Props` and `state` are both plain javascript objects, and they both hold information that affects the render output in a component.

The key difference between the two is that `props` is passed down from the parent component to its children, whereas `state` is created and managed within the component. `Props` is therefore immutable, and should not be changed, only passed down. `State`, on the other hand, is changeable, internal to the component, and is therefore not passed down to children components.

## Props
Since `props` cannot change during a component's lifecycle, they should be used when handling information that does not need to be acted on or edited. These components are known as "pure" or "stateless" components.

## State
`State` should therefore be used to handle changes internal to a component. When a stateful component first mounts, it is given an initial or default state. Based on user interactions, this default state will change and be re-rendered. 

## `setState()`
Using the `setState()` method, state can be mutated. It is important to note that `setState()` is asynchronous, and should therefore be passed a function instead of an object. This will ensure that `setState()` is always passed the most recent version of `state`. 

Here is an example from the reactjs official documentation:

The below function will not work as intended, because `setState()` is being passed an object.

```
incrementCount() {
  this.setState({count: this.state.count + 1});
}
```

Instead, the above should be written like this:

```
incrementCount() {
  this.setState((state) => {
    return {count: state.count + 1}
  });
}
```

Because a function is being passed, the `incrementCount()` updater will act on the current state, and be able to chain its updates. Before, with `this.state` the updates would act upon the default state value each time, which is not the desired action.

## Summary

To review, `Props` are immutable values that are passed down from parent components to their children. Props cannot be changed during a component's lifecycle.

`State` is handled within a component and is "private" to that component. It starts with a default value that changes over time based on user interactions.
Program execution
Tags: javascript, beginners, programming, computerscience
Published: 2021-10-07 16:49:26



Before we start talking about machine cycle we need to define what is the program; 
 
A set of instructions to process data,
A computer execute the program to create output data from input data, both data and program are stored in memory.

Now, what is the machine cycle:

The central process unit (CPU) uses repeating cycle to execute the instructions in the program (one by one ), a simplified cycle can consist of three phases: 

1- Fetch:
In fetch phase, the control unit orders the system to copy the next instructions into the instructions register in CPU, the address of this instruction ti be copied is held in the program counter register, after copying, program counter ++, to refer to the next instructions in memory.

2- Decode:
When the instructions is in the instruction register, it is decoded by control unit, the result of decode is Binary code for some operation that system will preform.

3- Execute:
The last phase; after decode ends the control unit sends the task order to a component in CPU. 

Example: 
The control unit sends the task to the system to load( read ) a data item from memory.

Next, what is the program instructions, 

( photo example provided from google) 

Happy to share knowledge with you:)
Good first issues for Hacktoberfest
Tags: opensource, hacktoberfest, javascript, node
Published: 2021-10-07 16:37:14



As mentioned in our [previous article](https://dev.to/medusajs/medusa-hacktoberfest-2021-13eb), [Medusa](https://github.com/medusajs/medusa) is participating in Hacktoberfest for the first time this year and the excitement is high. 


#### Getting started
There are loads of issues out there for developers to pick up, but it's not always easy to figure out where to start. We've made a series of good first issues that includes both a video tutorial and a checklist, such that you can easily get started building in public.

#### API fixture generation
The issues chosen for the series deal with API fixture generation. Currently, our fixtures are all stored within the same file, which is suboptimal due to 1) loading large files on the client (our API reference) is bad for performance and user experience and 2) referencing a single fixture in such a large file requires us to look for a _needle in a haystack_. 

The goal is to split each fixture into their own dedicated file making them lightweight and easy to reference.

The issues can be found filtering on label `api-fixture`, or use [this link](https://github.com/medusajs/medusa/issues?q=is%3Aopen+is%3Aissue+label%3Aapi-fixture) for easy access.

#### How-to
To easily get started use the following checklist:
- checkout `docs/api`
- branch out to `docs/api-[ns]-[endpoint]`
- if necessary clear dist and run `yarn bootstrap`
- cd `integration-tests/docs`
- `yarn && yarn build`
- `medusa-dev --scan-once`
- Open `__tests__/[ns].js`
- Import from `../test-input/[ns]/[endpoint]`
- Add test to the `toTest` array
- `yarn test --watch __tests__/[ns].js -t [operationId]`
- Make changes
- Make sure that snapshots are correctly defined so that tests pass across two runs
- Only add the fixtures and test changes related to your generated fixtures
- Push and open PR against `docs/api`

Additionally, you can watch [this video tutorial](https://www.loom.com/share/230b0c3ec59144bebbfa7029d31fd1fb) 
explaining the hows and whys narrated by co-founder Sebastian.

If you encounter issues, reach out to the community on [Discord](https://discord.gg/MvfArDW6f4) or submit them to our [Github](https://github.com/medusajs/medusa) issue board.
How to Scale Engineering Processes w/ Twitter’s VP of Engineering
Tags: techtalks, podcast, womenintech, twitter
Published: 2021-10-07 16:32:33

Maria Gutierrez is the VP of Engineering for Strategy and Operations at Twitter. She joins a special livestream of the Dev Interrupted podcast to share her career journey, her strategies for sustainably scaling engineering teams and the three pillars of engineering processes.

In a first for the Dev Interrupted podcast, Dan Lines hosted this episode live in front of a virtual audience during the INTERACT engineering leadership conference. Maria was a fantastic guest, sticking around after her interview with Dan to take questions from the audience. Her lessons on team management, building company culture, hiring and mentorship are not to be missed!

Maria has also been working and managing engineering teams remotely for over a decade and offers a great deal of practical advice for team leads everywhere.

#**Listen to the full episode**
{% spotify spotify:episode:5jALAzAYQdqqALlJMLfwyI %}

## Episode Highlights Include:

* Maria’s career path to Twitter

* How to successfully scale engineering teams

* Why processes matter

* The importance of mentorship

* Q&A panel where Maria takes questions from a live audience

## Join the Dev Interrupted Community

With over 1800 members, the Dev Interrupted Discord Community is the best place for Engineering Leaders to engage in daily conversation. No sales people allowed. [Join the community >>](https://discord.com/invite/devinterrupted)

![](https://cdn-images-1.medium.com/max/2048/0*reErCw5Vnk3QvnAL.png)

*Originally published at [https://devinterrupted.com](https://devinterrupted.com/podcast/how-to-scale-engineering-processes-w-twitters-vp-of-engineering/).*
[JS newbie] Array indexes in for...in loops.
Tags: javascript, beginners
Published: 2021-10-07 15:54:15

TL;DR. The indexes got in this way may not be what you anticipated.

If your are using `for(idx in arr)` to enumerate through an Array, note that the type of `idx` is actually `string`, not `number`.
``` js
> for(i in arr) { console.log(`type of key ${i}: ${typeof(i)}`) }
type of key 0: string
type of key 1: string
type of key 2: string
type of key 3: string
type of key 4: string
```

That is, if you want to derive some values from the index in your loop like this:
``` js
for (i in arr) {
    let val = i + 1 + arr2[i-1];
    // will probably become sth like "0122" rather than a number.
}
```
Your code will either explode or behave unexpectedly.

This is because the indexes of an Array are actually enumerable properties of an Object and are of type `string`. The [MDN doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) has some explanation, and you can also check the indexes of an Array as properties by `Object.getOwnPropertyNames`.
``` js
> Object.getOwnPropertyNames(arr)
[ '0', '1', '2', '3', '4', 'length' ]
```

Also, it is suggested that you'd better not use this to iterate through an Array if the order of execution is important since it is arbitrary according to [MDN doc](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#array_iteration_and_for...in).

That's today's joke. Sorry if there is any misunderstanding and corrections are appreciated!.
Contributed to some OSSs with pull-requests in this year too.
Tags: hacktoberfest, opensource, hacktoberfest2021
Published: 2021-10-07 16:13:10

---
title: Contributed to some OSSs with pull-requests in this year too.
published: true
tags: hacktoberfest, opensource, hacktoberfest2021
---

### Hacktoberfest 2021

In this year too, I contributed to few OSSs. As far as I remember, I joined this event from 2019. 🎉

### Contributions

#### souvikinator/gofuzz

https://github.com/souvikinator/gofuzz/pull/5

This pull-request add go-colorable (This is my package) to enable colors on Windows.

#### ArkScript-lang/Ark

https://github.com/ArkScript-lang/Ark/pull/318

This pull-request fixes possibly memory overflow.

https://github.com/ArkScript-lang/Ark/pull/319

This pull-request fixes compiler warnings.

#### fsouza/fake-gcs-server

https://github.com/fsouza/fake-gcs-server/pull/595

Fix to use path/filepath package instead of path package.

### Conclusion

Shut the fuck up and write some code. 🤘
Google Reader for Devs
Tags: productivity, news, programming
Published: 2021-10-07 15:48:48

Hey Guys!

With a Dev friend we struggled a lot to do an efficient tech watch in order to keep up to date and improve ourselves...

So we are working on a project to help people to finally do an efficient tech watch ^^

It's kind of a Google Reader (Rest In Peace) but for Developers :) Gathering your sources in one place and recommend content depending on your job and reading history ! (Stop scrolling to the infinite!)

We just launched our beta and would glad to have your feedback! if you are interested to try, it's here -> https://newzy.io

Take care,
Custom Candle boxes uk
Tags: career, candleboxes, customcandle, uk
Published: 2021-10-07 15:45:37

https://packagingprinting.co.uk/custom-candle-boxes/
In the packaging business, various types of materials are used in the assembling of these custom candle boxes uk. Every single of the materials such as kraft, cardboard, or rigid is sturdy and durable.
Apollo GraphQL: testing the `fetchMore` function
Tags: react, graphql, javascript
Published: 2021-10-07 15:26:19

---
title: "Apollo GraphQL: testing the `fetchMore` function"
published: true
description: "Pagination in GraphQL is a very succinct beast, and thankfully Apollo gives us a really useful method to run a query multiple times so that each item can be fetched from a server. However, what about testing `fetchMore`? how do you supply multiple queries to the GraphQL mockProvider? Here's how you can do it."
tags: 
- react
- graphql
- javascript
---
I'm building a messaging app with my team, and one of the things we realised recently is that our API has a hard limit on it. We can't fetch _all_ of a users' message threads in one go due to rate limits, so we have to use the relay style, cursor-based pagination that the API team have introduced.

Implementing this pagination in our application was super easy, largely thanks to two things: (1) [this post about  pagination with Apollo by Emma on her personal blog](https://www.emgoto.com/apollo-pagination/) and (2) Realising that [Apollo have a relay-style pagination helper already](https://www.apollographql.com/docs/react/pagination/cursor-based/#relay-style-cursor-pagination) which is a doddle to implement. 

But when I wanted to test this implementation, there was very little documentation on how to test `fetchMore`

Here's my implementation:

```javascript
    const {
        loading,
        error,
        data,
        fetchMore,
    } = useQuery(THREAD_LIST_QUERY, {
        variables: {
            ThreadsInput: {
                limit: 50,
            },
        },
    });
    useEffect(() => {
        if (data && fetchMore) {
            const nextPage = getHasNextPage(data);
            const after = getAfter(data);

            if (nextPage && after !== null) {
                fetchMore({
                    updateQuery,
                    variables: {
                        ThreadsInput: {
                            limit: 50,
                            cursor: after,
                        },
                    },
                });
            }
        }
    }, [data, fetchMore]);
```

If you're wondering about the contents of the `getHasNextPage` and other functions in this snippet, head over to Emma's blog I mentioned at the outset.

In the rest of my test suite, I have my mocks like this:

```javascript
    <MockedProvider
        mocks={mocks}
    >
        <Threads />
    </MockedProvider>
```

What I hadn't noticed before is the significance of why `mocks` is an _array_: it's so you can pass multiple mocks ... sequential ones:

```javascript
    <MockedProvider
        mocks={[…mocks, fetchMoreMocks]}
        addTypename={false}
    >
        <Threads />
    </MockedProvider>
```
It's as easy as that!

I'm glad we have such a comprehensive suite of tools in Apollo, but they can't cover everything in their documentation, it's already quite comprehensive. Still, this was a delightful discovery I wanted to pass on to you!
Introducing ReadUse - A CSS Framework for Readable and Useable Content
Tags: showdev, css, webdev, saas
Published: 2021-10-07 15:15:50


Earlier, I shared my plan to design [my website](https://toheeb.com) in public.

The adventure is to write guides that'll design the website itself, in real time. At the end, I'll have content on web design that uses this very website as a capstone project.

Wouldn't that be fun?

---

To track how the website's visual will evolve over time, I decided to branch off those styles to a package.

And to make this package useful to anyone, the styles will **only** be for making contents on a webpage **read**able and **use**able. Hence the name: **readuse**.

Here's how I see websites. They need to be:

- readable & useable
- creative & unique

ReadUse, a CSS Framework, will take care of the readability and useability part of a website. And let the designer go nuts in making their website unique to their taste. Letting your creativity shine 😂

ReadUse CSS framework will contain two parts:

- A drop-in stylesheet that'll will format content to aid User Experience. Using global styles which aren't bad unless misused
- A Layout Utility stylesheet that contains common layout components.

All these make up the Functional layer of any website. How website differs is by the decorative layer. 

Other CSS Frameworks do both. The result of which makes websites look similar. I want ReadUse to be Creativity-Agnostic. I hope I got that grammar combo right. You get my point anyways 😆


Here's my plan:

💡 I'll be using Github Issues to write and brainstorm on to-dos. A set of them makes a milestone ready for release.

✍️ My site will contain detailed guides of my research on why & how I'm styling it

⚡️ You get to see the result of the framework on this very website as well. Everytime!



Right now, It has crossed its first milestone 🚀

v0.1.0 release is a sanity test that says "hello world" 😂

2nd milestone, v0.2.0 release, will provide well-enough styles to make articles I'll write fairly easy to read. 

While future version will provide better UX.




I'm figuring this out on the go! It's my first open source project! And I'm using it to dive deep in CSS. It isn't ready for public use yet.

💡 Ask/Teach me anything, it'll help me learn more

👉 Follow [@toheebdotcom](https://twitter.com/toheebdotcom) for updates. 

{% twitter 1445041045146767360 %} 

🗒️ Learn more on [Github](https://github.com/toheeb/readuse)

{% github toheeb/readuse %}

🌟 Star the repo if you like the adventure ✌️
Introducing Messageraft! # buildinpublic
Tags: node, opensource, typescript
Published: 2021-10-07 15:07:15

Introducing [Messageraft](https://twitter.com/messageraft_com)  🎉. A single API that can be used to dispatch email, SMS, and chat-based notifications all from a single interface.

## Backstory

Since I sold my startup, I have been left with a void that my creative mind was looking for ways to fill.

One of the ideas that I kept coming back to prior to selling my startup was a notification gateway as a service. I went ahead and scratched my itch and MessageRaft is the result of that.

Let's get some things out of the way first.

## Notifications gateway, erm whats that doc?

A notifications gateway as the name implies is a portal where notifications pass through. In layman terms, it's basically a server that has an API exposed to other services/apps and receives requests.

And you guess it, notification requests. Simply put, it is a single API that can process multiple types of notifications and dispatch accordingly.


While it is still in its infancy, it is fully functional, the core is open-source hence it is **free** to use and you can get started in **under 2 minutes** (your internet connection and computer is the only bottleneck on that!!!)

So, without further ado, I have built and released a CLI which you can use to get started [here](https://www.npmjs.com/package/@messageraft/cli)


## Future plans

Messageraft is going to be 100% build in public and its core will always be free. I am looking to see if it picks traction and if it does I plan to create a product around it for people who don't want to host the service themselves plus a magnitude more providers support.

In addition, I have recently released a helper tool that makes it even easier and faster to develop and test emails locally from your machine with the help of MessageRaft which I am going to cover in another article so stay tuned for that!

-------------------------------

This is the first time I am building in public and would appreciate any type of feedback you can provide. As always you can find me on [twitter](https://twitter.com/9pitops)
Python bool()
Tags: python, programming, codenewbie, tutorial
Published: 2021-10-11 13:48:38

---
title: Python bool()
published: true
date: 2021-10-07 15:00:00 UTC
tags: #python #programming #codenewbie #tutorial
canonical_url: https://itsmycode.com/python-bool/
---

ItsMyCode |

Python’s **`bool()`** function converts a given value into Boolean(True or False) using the standard truth testing procedure.

## bool() Syntax 

The syntax of **`bool()`** method is 

```python 
**bool([value])**
```

## bool() Parameters

The **`bool()`** method can take one argument on which the standard truth testing procedure is applied.

The parameter is optional for the **`bool()`** function. If you do not pass any value by default, it returns **`False`**.

## bool() Return Value

The **`bool()`** function returns 

- **`True `** if the parameter of the value passed is True
- **`False `** if the parameter of the value passed is False or if the value is omitted

There are few exceptional cases where the **`bool()`** method returns False. Following are the values:

- **`None`**
- **`False`**
- Empty sequence such as **()**, **‘ ‘** ,**[]** etc
- Zero of any numeric type such as **0** , **0.0** , **0j**
- Empty mapping such as **{}**
- If Objects of Classes having **` __bool__ ()`** or **`__len()__`** method, returning **0** or **`False`**

## Example of bool() function in Python

```python 
# Python program to demostrate bool() function

# Returns False as x is False
x = False
print(x, 'is ',bool(x))

# Returns True as x is True
x = True
print(x, 'is ',bool(x))

# Returns False as x is an empty sequence
x = ()
print(x, 'is ',bool(x))

# Returns False as x is an empty mapping
x = {}
print(x, 'is ',bool(x))

# Returns False as x is 0
x = 0.0
print(x, 'is ',bool(x))

# Returns False as x is None
x = None
print(x, 'is ',bool(x))

# Returns True as x is a non empty string
x = 'ItsMyCode'
print(x, 'is ',bool(x))

```python 

**Output**

```
False is False
True is True
() is False
{} is False
0.0 is False
None is False
ItsMyCode is True
```

The post [Python bool()](https://itsmycode.com/python-bool/) appeared first on [ItsMyCode](https://itsmycode.com).
What are the best languages for cloud Computing?
Tags: programming, python, javascript, java
Published: 2021-10-07 14:51:46

There are tons of [**Computer programming languages that can be used for Cloud Computing**](https://www.alixaprodev.com/2021/10/best-programming-languages-for-cloud.html) and depends on the Cloud Platform. Some Platform Like Google Cloud, Amazon Cloud, and IBM Cloud uses multiple Programming languages which can help us access their cloud platform. Other platforms may be using one or two.

#List of the Programming languages used for Cloud Computing
1. Java 
2. Python
3. Javascript
4. C#
5. GoLang

These Programming languages are the most popular Programming languages for Cloud computing. But it highly depends on the platform as well.
Learn more about [which Programming language should be good for Cloud Computing?](https://www.alixaprodev.com/2021/10/best-programming-languages-for-cloud.html)
Hide/Show Navbar and Footer in React Application
Tags: programming, javascript, beginners, react
Published: 2021-10-07 14:18:02

Working on an application, that required a registered users interface and admin interface, I came across an issue - hiding the navbar and footer in the admin part. After countless research on the internet, I was able to make sense of what the possible solution entailed.

```javascript 
//app.js
import { Route, withRouter } from 'react-router-dom';
import Navbar from 'Components/Layout/Navbar';
import Footer from 'Components/Layout/Footer';
import Home from 'Pages/Home';

//Admin Imports
import Dashboard from 'Pages/Admin/Dashboard';
import DisplayProducts from 'Pages/Admin/DisplayProducts';

const App = ({ location }) => {
   // Array of excluded routes to hide navbar/footer
  const excludedRoutes = ['/admin/dashboard', '/admin/products'];

   return (
      {!excludedRoutes.includes(location.pathname) && <Navbar />}

      <Route path="/" component={Home} exact />
      <Route path="/dashboard" component={Dashboard} exact/>
     <Route path="/products" component={DisplayProducts} exact/>

    {!excludedRoutes.includes(location.pathname) && <Footer />}
  )
};

//withRouter gives access to location props
export default withRouter(App)
```


The final step...
```javascript
//index.js

import React, { StrictMode } from 'react';
import ReactDOM from 'react-dom';
import App from './App';

//Router ensures the URL matches the UI
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <StrictMode>
      <Router>
        <App />
      </Router>
  </StrictMode>,
  document.getElementById('root')
);
```

Hope this helps.