teleren/devto huggingface dataset:
Day 37 of #100DaysOfCode: PWA + SPA: initialize PWA on Create React App(CRA)
Tags: javascript, react, pwa, 100daysofcode
Published: 2020-09-13 08:11:24

## Introduction
The target of Progressive Web Apps(PWA) is to provide awesome experiences like native Apps. There are three main points for PWA.
1. Reliable: they should load fast and even work if you're offline
2. Fast: it should be able to access device features in an intuitive way
3. Engaging: Feel like a native App on mobile devices

This article notes the initialization of PWA on the React App.

## Steps
### 1. Create a React app
* Use the following command to create a React app
```javascript
create-react-app pwa-example
```

### 2. Show hidden configure files
* Use the following command to show hidden folders
```javascript
npm run eject
```
* The config folder will show
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/c15og4c9nr70bf8aldro.png)

### 3. Edit src/index.js
Change the last line from 
```javascript
serviceWorker.unregister();
```
to
```javascript
serviceWorker.register();
```

### 4. Generate files for production 
* Use the following command to build static files ad assets
```javascript
npm run build
```
* It will generate the build folder with filed including service-worker.js
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9nfwolqo2d439rnnsxj8.png)

### 5. Create a temporarily server to render pages
* Use the following command to install [serve](https://www.npmjs.com/package/serve) and execute it to listen the build folder
```javascript
npm install -g serve
serve -s build
```
* Serve will start to listen requests
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zuavzhg02dna5x36zd8l.png)

### 6.Validations
* Open the browser and visit http://localhost:5000/
* Open the developer tool and select *Application/Service Workers*
* Check *Offline* and reload. The page should be rendered correctly.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4wckc2jryl0qsctu1429.png)

That's it!

## References
* [Progressive Web Apps (PWA) - The Complete Guide](https://www.udemy.com/course/progressive-web-app-pwa-the-complete-guide/)
* [三步驟客製化 Create React App 的 Service Worker](https://medium.com/@liuderchi/%E4%B8%89%E6%AD%A5%E9%A9%9F%E5%AE%A2%E8%A3%BD%E5%8C%96-create-react-app-%E7%9A%84-service-worker-1c2ffaf70a1a)
* [Create-react-app service worker not functioning](https://stackoverflow.com/questions/56122942/create-react-app-service-worker-not-functioning)

## Articles
There are some of my articles. Feel free to check if you like! 
* My blog-posts for software developing: https://medium.com/a-layman
* My web resume: https://jenhsuan.github.io/ALayman/cover.html
* Facebook page: https://www.facebook.com/imalayman
* Daily learning: https://daily-learning.herokuapp.com/
Dart & Flutter Easy Wins 29-35
Tags: flutter, dart
Published: 2020-09-13 08:06:03

---
title: Dart & Flutter Easy Wins 29-35
published: true
description: Easy ways to improve your Dart & Flutter code. Published weekly.
tags: flutter, dart
//cover_image: https://direct_url_to_image.jpg
canonical_url: https://codewithandrea.com/tips/dart-flutter-easy-wins-29-35/
series: Dart & Flutter Easy Wins
---

I recently started a series of [daily tweets](https://twitter.com/search?q=from%3Abiz84%20Easy%20Win&src=typed_query&f=live) about easy ways to improve your Dart & Flutter code. I called this **Easy Wins**. 

To make these easier to find, I'm sharing 7 tips every week here.

## 29. When EXTENDING classes, all ABSTRACT methods MUST be overridden & other methods CAN be overridden. When IMPLEMENTING classes, ALL methods MUST be overridden.

![When EXTENDING classes, all ABSTRACT methods MUST be overridden & other methods CAN be overridden. When IMPLEMENTING classes, ALL methods MUST be overridden.](https://codewithandrea.com/tips/2020-08-30-dart-flutter-easy-wins-29-35/images/029-extends-vs-implements.png)

## 30. Need to iterate through a map in a null-safe manner? Use `.entries`:

![Need to iterate through a map in a null-safe manner? Use .entries](https://codewithandrea.com/tips/2020-08-30-dart-flutter-easy-wins-29-35/images/030-map-entries.png)

## 31. Need different implementations for web and native platforms? Use conditional imports.

More info here: [Conditionally importing and exporting library files](https://dart.dev/guides/libraries/create-library-packages#conditionally-importing-and-exporting-library-files)

![Need different implementations for web and native platforms? Use conditional imports.](https://codewithandrea.com/tips/2020-08-30-dart-flutter-easy-wins-29-35/images/031-conditional-imports.png)

## 32. Need to declare a function type with generics? Use a typedef:

![Need to declare a function type with generics? Use a typedef](https://codewithandrea.com/tips/2020-08-30-dart-flutter-easy-wins-29-35/images/032-typedef-function-builder.png)

## 33. Need to work with *computed* variables? Use getters and setters.

![Need to work with *computed* variables? Use getters and setters](https://codewithandrea.com/tips/2020-08-30-dart-flutter-easy-wins-29-35/images/033-getters-setters.png)

## 34. Need to return a Future that returns immediately? Use `Future.value`.

![Need to return a Future that returns immediately? Use Future.value](https://codewithandrea.com/tips/2020-08-30-dart-flutter-easy-wins-29-35/images/034-future-value.png)

## 35. Want to force a delay before executing some code? Use `Future.delayed`.

![Want to force a delay before executing some code? Use Future.delayed](https://codewithandrea.com/tips/2020-08-30-dart-flutter-easy-wins-29-35/images/035-future-delayed.png)

More tips coming next week. [Subscribe via RSS](https://codewithandrea.com/rss.xml) for updates!

Happy coding!
Attempted import error: 'combinedReducers' is not exported from 'redux'.
Tags: help, redux
Published: 2020-09-13 07:51:36

```javascript
import {createStore, combinedReducers, applyMiddleware, compose} from 'redux';
import {productListReducer} from './reducers/productReducers';
import thunk from 'redux-thunk'

const initialState = {};
const reducer = combinedReducers({
    productList: productListReducer
})

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, initialState, composeEnhancer(applyMiddleware(thunk)));
export default store;
```
"if else condition" how to use pug/jade, scss, javascript, python(backend) - (Stack Tutorial 3)
Tags: pug, scss, javascript, python
Published: 2020-09-13 07:27:19

---
title: "if else condition" how to use pug/jade, scss, javascript, python(backend) - (Stack Tutorial 3)
published: true
description: 
tags: pug,scss,javascript,python
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/s6lpq552y8qdfnkk8db0.png
---
Hi Friends,
We are going to use the condition of our stack learning.
[Previous Post](https://dev.to/nikhilroy2/while-loop-developer-how-to-use-pug-jade-scss-javascript-python-backend-stack-tutorial-2-15dj)



`Open up git bash in the current folder`
and type 
``` code . index.pug style.scss script.js hello.py ```
It will create file and open the Visual Studio code editor.
* index.pug 
* style.scss
* script.js
* hello.py

**Pug/Jade**
for pug/jade compiler now we are going to use visual studio code to compile the pug to html code directly.
![Live pug to html compiler](https://dev-to-uploads.s3.amazonaws.com/i/a0o4bdpwlidxagscqp96.png)
**Example 1**

```
- var time= true
if time == true
 h1 I am true
else
 h1 I am false
```


**Scss**
**Example 1**
```
@mixin bdr($px,$type,$color,$boll: true){
  @if $boll{
    border: $px $type $color;
    border-radius: $px;
  }
  @else{
    border: $px $type $color
  }
}


.demo{
  width: 200px;
  height: 200px;
  background: red;
  @include bdr(20px,solid,black);
  
}
```

**Javascript**
**Example 1**

```
let time = true;
if(time==true){
  console.log(" I am true")
}else{
  console.log(" I am false")
}

```

**Python**
**Example 1**

```
name = ["nikhil","sonchoy","shanto"]
if "nikhil" in name:
    print("Name has nikhil name")
elif:
    print("Name has no nikhil name")

```

**Example 2**
```
country = True
if country == True or country != False:
    print("Country is true")
elif:
    print("Country is false")
```

There are a lot of examples but we just use very basic concepts to go farther.
If you interested in this post like, comment, and follow me.
Thanks.
Simple Elixir State Machine for Validation
Tags: elixir
Published: 2020-09-13 07:15:25


At some point, we will have an entity which the status can be transitioned to many possibilities and we want to have a rule to enforce an integrity of the data. 


For example, this is a human emotion state change diagram.

![state machine](https://dev-to-uploads.s3.amazonaws.com/i/n4r6j7nlae21xudz2jgr.png)
  

And some transitions are okay, while some are not.
```elixir
# 👌 OK
iex> update(%Human{emotion: :hungry}, %{emotion: :full})
{:ok, %Human{emotion: :full}}

# 🙅‍♂️ No, get something to eat first!
iex> update(%Human{emotion: :hungry}, %{emotion: :sleepy})
{:error, "invalid status change"}
```

### 🤖 Simple validation with pattern matching

For elixir developer, you can guess the pattern matching is pretty good for solving state change problem like this. 


```elixir
def update(%Human{} = human, attrs) do
  with :ok <- validate_status(human.emotion, attrs.emotion),
  ...
end
```

```elixir
def validate_status(current_status, new_status) do
  case {current_status, new_status} do
    # Put all the transition paths as a whitelist
    {:hungry, :full} -> :ok
    {:hungry, :angry} -> :ok
    {:angry, :angry} -> :ok
    {:angry, :full} -> :ok
    {:full, :sleepy} -> :ok

    # return error for the rest
    _ -> {:error, "invalid status change"}
  end
end
```

### ⚡️ Can we embed this rules into Ecto changeset?

If we want the rule to be strictly applied to the ecto data schema, we can also build a custom changeset validation for status change as well. 

```elixir
def changeset(human, attrs \\ %{}) do
  human
  |> cast(...)
  |> validate_required(...)
  |> validate_status_change() # <- custom validation
end
```

```elixir
def validate_status_change(changeset) do
  # Get current and new field data
  current_status = changeset.data.status
  new_status = get_field(changeset, :status)

  case {current_status, new_status} do
    # do nothing if ok
    {:hungry, :full} -> changeset
    {:hungry, :angry} -> changeset
    {:angry, :angry} -> changeset
    {:angry, :full} -> changeset
    {:full, :sleepy} -> changeset
    {nil, _} -> changeset # any new status is ok

    # add error to ecto changeset errors
    _ -> add_error(changeset, :status, "invalid status change")
  end
end
```


That's it! Hope this could give you some idea in your next task. Feel free to discuss if you have any comments! 😊
100DaysOfCode | Day 36, 37
Tags: python, challenge, 100daysofcode, beginners
Published: 2020-09-13 07:03:09

Hey wassup everyone?
I'm feeling great, yesterday I started __Database__ and __SQLAlchemy__.
They are sounding weird for me, cause I don't have any background or experience with __Databases__, but there's no worry about it cause I think it will be great stuff to learn and that's really necessary for back-end developers.

I always do my best and working hard to achieve my great goals.

I have 4 rules in my life:

__1. Patience__
__2. Commitment__
__3. Persistence__
__4. Master the 3 Rules__
Finding Minimum in rotated sorted array
Tags: python, coding
Published: 2020-09-13 06:58:05

*Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e.,  [0,1,2,4,5,6,7] might become  [4,5,6,7,0,1,2]).

Find the minimum element.

You may assume no duplicate exists in the array.*
Example - 
"""
Input: [3,4,5,1,2] 
Output: 1
"""
Solution - 
The naive approach is to iterate over the array and find the minimum.
```
return min(arr)
```
It takes O(n) time.
Better approach is to use binary search algo.
The intuition here is that - **
The array is rotated around a pivot. So, If we are in the left side of the the pivot, values will always be greater than the values on right side of the pivot. So, we can decide to go to the right.
Similarly, If we are on right side of the pivot, the values will be less than the left side of the pivot, also it will be less than the rightmost value.
**
If we are at the pivot then it satisfies the following condition - 
` arr[pivot-1] < arr[pivot] < arr[pivot + 1] `
So, using above intuition we come to following solution
```
def findMin(self, nums: List[int]) -> int:
        arr = nums
        lo = 0
        hi = len(arr) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if lo == hi:
                return arr[lo]
            if arr[0] < arr[mid] < arr[hi]:
                return arr[0]
            if arr[mid-1] > arr[mid] and arr[mid] < arr[mid+1]:
                return arr[mid]
            else:
                if arr[mid] > arr[hi] :
                    lo = mid + 1
                else:
                    hi = mid - 1  
```
Maximum Sum Circular Subarray
Published: 2020-09-13 06:03:06

We have to consider two cases while solving this problem:

Case 1: When the maximum sum SubArray is present in the normal order of array.
Example,
{-10, 2, -1, 5}
Max sum is 5

{-2, 4, -1, 4, -1}
Max sum is 7 (4+(-1)+4)
Use Kadane’s algorithm

Case 2:When max sum subArray is Present in circular fashion.
Inversion of the array is required only to find the maximum sum in circular fashion.

Example,
{10, -12, 11}
The max sum is 21 (11+10)
Inverted array, {-10,12,-11}
Maximum sum is 12
Cumulative sum of original array is 9
Max sum=9+12=21

{12, -5, 4, -8, 11}.
The max sum is 23 (11+12)
Inverted array, {-12,5,-4,8,-11}
Maximum sum is 9 (5+(-4)+8)
Cumulative sum of original array is 14
Max sum=14+9=23

Note:
Our array is like a ring and we have to eliminate the maximum continuous negative (i.e. the minimum sum) that implies maximum continuous positive Sum(i.e. maximum sum) in the inverted arrays.

Inversion is done to apply Kadane’s algorithm which finds the maximum sum.

Hence, the maximum sum of inverted array would be the minimum sum of the original array.

Then, we will subtract the maximum Sum of inverted array from the Sum all the elements of the original array(i.e. cumulative sum).

At last compare the max sum obtain from both the cases and print the larger one.

Kadane’s Algorithm:
Initialize:
max_so_far = 0
max_ending_here = 0

Loop for each element of the array
(a) max_ending_here = max_ending_here + a[i]
(b) if(max_ending_here < 0)
max_ending_here = 0
© if(max_so_far < max_ending_here)
max_so_far = max_ending_here
return max_so_far
[Fix] Missing top level class documentation comment Rubocop
Tags: rails
Published: 2020-09-13 05:53:20

Rubocop is the best way to enforce best practices in our rails project. While working on the project with rubocop enabled, it's normal to stumble upon the warning: **Missing top-level class documentation comment. [Style/Documentation]**. When this happens, we have three options to fix or disable the warning.

## Warning

- Missing top-level class documentation comment. [Style/Documentation]

## Options Available for Fix

You can disable or fix this warning using either of the 3 options:

1. Disable cop in the project
2. Disable cop in only one class
3. Add comment just above the class declaration

### Option 1: Disable cop in the project

Most of the classes we use are self describing, meaning as a developer, you can easily make sense of what the class is doing. Normally I find this rule not very useful, so most of the time I disable it in the whole project. Add the following cop to your configuration file to disable it project wide:

```ruby
# .rubocop.yml

Style/Documentation:
  Enabled: false
```

### Option 2: Disable cop in only one class

If you feel this cop is important in your project and don't want to disable it in the configuration file, then you can disable it in only one class as required.

```ruby
# app/models/user.rb

# rubocop:disable Style/Documentation
class User
end
```

### Option 3: Add comment just above the class declaration

You can also make the warning go away by adding the comment as warning suggests.

```ruby
# app/models/user.rb

# Service to download ftp files from the server
class FtpService
end
```

Though this article is specific to resolving **Missing top-level class documentation comment. [Style/Documentation]**, this fix also works on every other warning that rubocop throws. Did I miss any option that you are using? Let me know in the comments below.

**Image Credits:** Cover Image by <a href="https://unsplash.com/@mattpopovich?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" target="_blank">Matt Popovich</a> on <a href="https://unsplash.com/s/photos/cop?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" target="_blank">Unsplash</a>
Sohbetodalari
Tags: sohbet, sohbetodalari
Published: 2020-09-13 05:45:06

 Yepyeni insanlarla tanışmak ve güzel bir arkadaşlık kurabilmek için günümüzde birbirinden değişik sohbet siteleri bulunuyor. Ancak burada önemli olan kaliteli hizmet anlayışıyla güvenilir bir altyapı kapsamında destek sağlayan siteler üzerinden giriş gerçekleştirmektir. Bu konuda kaliteli bir hizmet sunan, birbirinden değişik [https://sohbet.page](https://sohbet.page) sohbet odaları üzerinden destek sağlayan bu site aracılığıyla rahatlıkla muhabbetlere katılabilirsiniz. Böylece değişik karakter yapılarındaki kadın ve erkeklerle tanışabilir; onlarla hem genel odalarda hem de özel odalarda eğlenceli bir chat ortamı yaratabilirsiniz.

 Çevrenizi Genişletin
 
 Daha geniş bir çevreye ulaşabilmek için bu kaliteli site bünyesinde, sohbet keyfini eğlenceli odalarda gerçekleştirebilirsiniz. Her oda içerisinde değişik sohbetler dönmekte ve bu sohbetlerle beraber değişik karakter yapısındaki insanlarla tanışılabilmektedir. O anki ruh haline ve modunuza bağlı olarak sohbet odaları arasından tercih gerçekleştirmeniz mümkün. Değişik yaş kriterlerindeki kadın ve erkeklerle tanışırken, güzel bir arkadaşlık ve dostluk kurabilirsiniz. Telefonu günün 24 saati boyunca chat odaları içerisinde ne zaman isterseniz değerlendirmeniz mümkün.
Typescript for beginners: number
Tags: typescript
Published: 2020-09-13 05:03:27

One time I've been working with Rest API and there was this one property, that was supposed to be a number. Instead, it wasn't, it was a string and it broke my function. At the time I wasn't using typescript and it took some time to find a problem. With typescript, it would have been so much quicker!

Typescript basic type number:

```
function addTax(num: number) : number {
    const tax : number = num * .21;

    return num + tax
}
addTax(100) // 121
addTax("100") // 10021 // error "Argument of type 'string' is not assignable to parameter of type 'number"
```
Fix and Forge
Tags: codenewbie, rails, ruby
Published: 2020-09-13 03:43:47

---
title: Fix and Forge
published: true
description: Creating a web application using Ruby on Rails
tags: codenewbie, rails, ruby
cover_image: https://twilio-cms-prod.s3.amazonaws.com/original_images/twilio-on-rails.png
---
# Ruby on Rails
After months of learning about Ruby, HTTP requests, Active Record, and more, I finally arrived to the  Ruby on Rails portion at Flatiron School a few weeks ago. What an adventure it has been. All that hard work and now I am learning about all the magic this framework has to offer (not to mention the abundance of resources across the web). I know there are haters out there who say it is dying/dead, but it has so much to offer in so many different areas. I feel like the more I follow the Rails path, the better I get at creating software not just programming.
## The Project
We were tasked with creating a simple CRUD web application with a solid back-end. Very similar to our Sinatra project with a few more requirements and a lot more magic (I still can't get over the magical built-in helpers of this framework). I decided to build a project/issue tracker where users can create projects, submit issues, and assign tasks to themeselves. Fix And Forge was born. I know... I have this cliche affinity for alliteration.
## Generating Everything
Creating a new Rails application is as easy as:
```bash
rails new application-name
```
And once you're in your new application's root directory you can generate just about whatever you want with:
```bash
rails g resource
rails g migration
rails g model
```
These commands take a number of arguments and options and inform you what was done. It is awesome and I can't get over all the work devs have put into making Rails development so smooth, consistent, and even fun.
## A Few Hiccups
As I was working on my models, controllers, views, partials, and helpers I ran into a number of gotcha's. Here are a few of them:
* In a **belongs_to** migration put **user_id** not just **user**
* Make sure to include **local: true** in your list of arguments to **form_with**
* A form within a nested route needs to have the **url: path** specified
* If you want to take advantage of your **has_many through** relationships make sure you also have the **has_many** relationship with the model you are going through.

## JS
Rails has been an absolute blast and I still have so much to learn. I'm excited to continue practicing and learning Rails as we move on to JavaScript and the front-end!
Group Anagrams Python Solution
Tags: python, datastructures, algorithms
Published: 2020-09-13 03:29:37

[Link to leetcode problem here](https://leetcode.com/problems/group-anagrams/)

The problem states:
Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.


##Initial Thoughts
The first thing we should think of is how to tell if any given word is an anagram of another. Looking at each letter in a word might be a start for our solution. But going through each letter and figuring out if 2 words have the same letters might take too long.

What if we sorted each letter in a word alphabetically. This can point out to us words that have the same letters and are anagrams.

The best way to sort the words out would be with a sort method. in python you are able to just do it on the word itself 
`sortedWord = "".join(sorted(word))`
Other languages may not be so kind.

Now that we can arrange every word to sort within itself, we can then group up the words that are sorted to be the same. 
Words like "eat, tea, ate" will all be sorted to the same "aet".

This is not our whole solution though since the problem is called "group anagrams." How would we store all these separate groups?

Well since we know the words "eat, ate," and "tea" all get sorted to "aet". What if we group them to that sorted word in a hash table or dictionary.
The dictionary would then look something like
```python
table = {
    "aet": ["ate", "eat", "tea"]
}
```

We would then be able to check any word if they are anagrams of each other. If for instance we get a different word such as "car".
`"".join(sorted(car)) => acr ` 

which is not the same as "aet" therefore is not an anagram of the other words.

Since we have a new word then we can add it to our table as a new key value pair

```python
table = {
    "aet": ["ate", "eat", "tea"],
    "acr": ["car"]
}
```

This is the general pattern until we go through the whole input array of words. 

The problem asks us to return the list of anagrams together in one big array. We can then return with `list(table.values())` in python which would return all the values of our table in a list of arrays with anagrams.

```python
def groupAnagrams(words):
    anagrams = {}
    for word in words:
        sortedWord = "".join(sorted(word))
        if sortedWord in anagrams:
            anagrams[sortedWord].append(word)
        else:
            anagrams[sortedWord] = [word]
    return list(anagrams.values())
```