teleren/devto huggingface dataset:
Question on Deadlock | Operating System - M04 P07
Tags: linux, devops, beginners, tutorial
Published: 2020-12-13 12:41:07

**This is a multipart blog article series, and in this series I am going to explain you the concepts of operating system. This article series is divided into multiple modules and this is the forth module which consists of 8 articles.**

_In this article we will see one question based on the concept of deadlock in an operating system._

***Question:*** A system is having 3 processes each requires 2 units of resources **R**. The minimum number of units of **R** requires such that no deadlock will occur?
1. 3
2. 5
3. 6
4. 4

***Answer:***
- **(d) 4 resources** 
- We need `4` resources of `R` because then in worst condition when all the processes request for resource we can give one resource to every process and still one resource will be remaining.
- If we give that resource to any process than it will get terminate because one process require only two resources and when they get that their execution will be complete.
- Now we have two free resources and two processes that need two resources and hence they will also get executed and thus no deadlock will occur.
- If we take `3` resource than deadlock will occur and we are not taking `5` or `6` because we need to find minimum number of resources.

_So this was a simple question on deadlock in an operating system. Hope you liked it and learned something new from it._

If you have any doubt, question, quires related to this topic or just want to share something with me, than please feel free to contact me.

### 📱 Contact Me

[Twitter](https://twitter.com/r_mishra10)
[LinkedIn](https://www.linkedin.com/in/rahul-mishra-66210b185)
[Telegram](https://t.me/rahul_mishra10)
[Instagram](https://www.instagram.com/rahul_mishra10/?hl=en)

### 📧 Write a mail
<rahulmishra102000@gmail.com>

#### 🚀 Other links

[GitHub](https://github.com/rahulMishra05)
[HackerRank](https://www.hackerrank.com/rahulmishra10201)
Solve problem of API responds with 401 error
Tags: javascript, node, react, openweather
Published: 2020-12-13 12:36:28

**Error:**
*Invalid API key. Please see http://openweathermap.org/faq#error401 for more info*

**API calls responds with 401 error:** 
You can get the error 401 in the following cases:

* You did not specify your [API key](https://openweathermap.org/appid) in API request.
* Your API key is not activated yet. Within the next couple of hours, it will be activated and ready to use.
* You are using wrong API key in API request. Please, check your right API key in [personal account](https://home.openweathermap.org/api_keys).
* You have **free** subscription and try to get access to our paid services (for example, [16 days/daily forecast API](https://openweathermap.org/forecast16), [any historical weather data](https://openweathermap.org/price#history), [Weather maps 2.0](https://openweathermap.org/api/weather-map-2), etc). Please, check your tariff in your [personal account]([[price and condition]](https://openweathermap.org/price)).

here are some steps to find problem.

# 1) Check if API key is activated
some API services provide key information in dashboard whether its activated, expired etc. openWeatherMap don't.
to verify whether your key is working 'MAKE API CALL FROM BROWSER'
`api.openweathermap.org/data/2.5/weather?q=peshawar&appid=API_key`  

*replace API_key with your own key, if you get data successfully then your key is activated otherwise wait for few hours to get key activated.*

# 2) Check .env for typos & syntax
.env is file which is used to hide credentials such as API_KEY in server side code.
make sure your .env file variables are using correct syntax which is
NAME=VALUE
```
API_KEY=djgkv43439d90bkckcs
``` 
*no semicolon, quotes etc*

# 3) Check request URL
check request url where API call will be made , make sure
* It doesn't have spaces, braces etc
* correct according to URL encoding
* correct according to API documentation

# 4) Debug using dotenv:
to know if you dotenv package is parsing API key correctly use the following code

```
const result = dotenv.config()

if (result.error) {
  throw result.error
} 
console.log(result.parsed)
```

*this code checks if .env file variables are being parsed, it will print API_KEY value if its been parsed otherwise will print error which occur while parsing.*

*Hopefully it helps :)*
If you would like to confirm a result of your code quickly
Tags: programming
Published: 2020-12-13 12:09:29

You can see the result of your program code from the web service "paiza.io".

https://paiza.io/ja/projects/new

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

Many programming languages have been supported.

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

This web page can be printed in English or Spanish :-)
StringJoiner class provides utility functions to concatenate words
Tags: java
Published: 2020-12-13 11:54:37

The following code can be improved by StringJoiner class in Java.

```java
String[] names = new String[]{"George", "Sally", "Fred"};
StringBuilder sb = new StringBuilder("[");
for(String name : names){
  sb.append(name).append(":");
}
sb.deleteCharAt(sb.length() - 1);
sb.append("]");
System.out.println(sb.toString()); //=> [George:Sally:Fred]
```

In the case of StringJoiner class

```java
String[] names = new String[]{"George", "Sally", "Fred"};
StringJoiner sj = new StringJoiner(":", "[", "]");
for(String name : names){
  sj.add(name);
}
System.out.println(sj.toString()); //=> [George:Sally:Fred]
```

The code has become more concise :-)

Reference
https://cr.openjdk.java.net/~iris/se/11/latestSpec/api/java.base/java/util/StringJoiner.html#
react hook for waiting state update (useAsyncState)
Tags: react, javascript
Published: 2020-12-13 11:30:33

hello guys, React is an awesome library especially after introducing hooks in function component which help us minimize the code writing already written in class components, but this didn't change how react work especially state update which happen asynchronous. 
So image we want to invoke a function on each state update, we need to invoke it from `useEffect` like this example:
```
function App() {
  const [state, setState] = useState(0);
useEffect(()=>{
console.log(state);
},[state])
  return (
    <button onClick={()=>setState(prev => prev + 1)}>
      {state}
      increment
    </button>
  );
}
```
but why we can't have to wait for set update to happen then invoke our function like this:
```
 const currentState = await setState(prev => prev + 1);
 console.log(currentState);
```
this what `useAsyncState` come for have a look at the code:

```
import { useState, useRef, useCallback, useEffect } from "react";

function useAsyncState(initialState) {
  const [state, setState] = useState(initialState);
  const resolveState = useRef();
  const isMounted = useRef(false);

  useEffect(() => {
    isMounted.current = true;

    return () => {
      isMounted.current = false;
    };
  }, []);

  useEffect(() => {
    if (resolveState.current) {
      resolveState.current(state);
    }
  }, [state]);

  const setAsyncState = useCallback(
    newState =>
      new Promise(resolve => {
        if (isMounted.current) {
          resolveState.current = resolve;
          setState(newState);
        }
      }),
    []
  );

  return [state, setAsyncState];
}

export default useAsyncState;
```

usage no need for the `useEffect` anymore :
```
function App() {
  const [state, setState] = useAsyncState(0);
  const click = async () => {
    const currentState = await setState(prev => prev + 1);
    console.log(currentState);
  };
  return (
    <button onClick={click}>
      {state}
      increment
    </button>
  );
}

```
100vh problem with iOS Safari
Tags: javascript, mobile, css, ios
Published: 2020-12-13 11:19:03


![100vh](https://dev-to-uploads.s3.amazonaws.com/i/w3vy0uveuvz6s4naqaf8.jpg)

The web content it's outside the viewport although we used `100vh` (the red opacity box with `100vh` text).

```css
.section {
    height: 100vh; // bad approach 
}
```

The problem you have been receiving after adding the `height: 100vh` to mobile resolutions. It happens due to the calculation method which Safari and Chrome are using. Mobile devices calc browser viewport as (**top bar + document + bottom bar**) = `100vh`. I had a hard time with `100vh` when the page have to have a section filled the whole screen. After a couple of hours, I've found the solutions that I show you.  

They are two solutions, the first needs JavaScript and CSS, the second solution required only CSS.

### 1. JS & CSS solution

Let’s get started first with the JS file:

```js
const appHeight = () => {
    const doc = document.documentElement
    doc.style.setProperty('--app-height', `${window.innerHeight}px`)
}
window.addEventListener('resize', appHeight)
appHeight()
```
**appHeight** function has sets new style property var(`--app-height`) including current window height, `--app-height` it is necessary for next steps.

```css
:root {
   --app-height: 100%;
}

html,
body {
    padding: 0;
    margin: 0;
    overflow: hidden;
    width: 100vw;
    height: 100vh;
    height: var(--app-height);
}
```

In the previous step I've created the reference `--app-height`, wrapping in the `var()` I've received CSS variable `var(--app-height)`. This variable is allowed to read values created by JS.


### 2. CSS solution (not recommend)
The last, but not the least solution is `--webkit-fill-available`, this solution works only on Apple devices, it won't solve the problem on Android devices. I don't recommend this solution, but it's worth showing.

```scss
height: 100%;
height: -webkit-fill-available;
```

Thank you for your attention! I’ll appreciate your feedback.

If you like this article, follow me on Twitter [@MaciejDEV](https://twitter.com/MaciejDEV)
StringBuilder is implicitly used when there is String += in Java
Tags: java
Published: 2020-12-13 11:13:44

In Java, StringBuilder Object is implicitly used when a String variable is operated by "+=".

Example

```java
String s = "hoge";
s += "fuga";
s += "piyo";
```

The above code will be compiled to the below code.

```java
String s = "hoge";
s = (new StringBuilder(String.valueOf(s))).append("fuga")
.toString();
s = (new StringBuilder(String.valueOf(s))).append("piyo")
.toString();
```

This is a waste of machine resource, hence the code should be written, like

```java
StringBuilder sb = new StringBuilder("hoge");
sb.append("fuga");
sb.append("piyo");
String s = sb.toString();
```

Or, it can be written more simply

```java
String s = new StringBuilder("hoge").append("fuga").append("piyo")
.toString();
```

Reference
https://www.ne.jp/asahi/hishidama/home/tech/java/string.html
https://gihyo.jp/book/2014/978-4-7741-6685-8
handle AWS lambda function code on web with layers
Tags: aws, python, programming, cloud
Published: 2020-12-13 11:08:55

 - When developer write AWS lambda function in python or other language than it require some libraries to run code and those libraries may be require more than 3 mb. AWS does not provide function editor on more than 3 mb code than it difficult to handle errors.
 - In this situation AWS provide layers to attach library and reusable those libraries in other lambda function. But if you create a layers in right way than lambda function throw the error. I wanna show to how to create a right layers using ec2 instance in python language.
 ```ec2 instance must be give iam role to full access s3 bucket.```
 - run below command on ec2 instance 
```bash
sudo apt-get update
sudo apt-get install python3-pip -y
sudo apt-get install zip -y
sudo apt-get install awscli -y
mkdir -p build/python/lib/python3.8/site-packages
pip3 install <package> -t build/python/lib/python3.8/site-packages/ --system
cd build/
zip -r <zip name> .
aws s3 cp <zip file> s3://<bucket>
```

 - goto s3 bucket and copy the zip file link
 - goto lambda console click layers
 - create layer input zip file link selete runtime and create.

 - congratulation you crated lambda layer sucessfully.
Want to learn AI and machine learning from basics in Hindi ?
Tags: ai, machinelearning, python, programming
Published: 2020-12-13 10:25:27

Well , there is my channel on youtube and i'm teachine ai and ml from basics and the best part is you can contact me seamlessly from our discord channel.
Hope you will like that Channel !
Link : https://www.youtube.com/channel/UChj7t7HqIYEaHSmJX3Rk-Dg
Spellcheck in Google Docs
Tags: blogging, productivity, beginners
Published: 2020-12-13 10:18:18

I'm not a native english Speaker and didn't use google docs that much before. But in the last few weeks i had to write some texts in the english language which contained more than a few sentences and i quickly realised that Google Docs has a (English) spell and grammar check function activated. Didn't pay attention before at all.

It's not perfect, but having a tab open with an open and empty google document allows me to copy the text for a post i write here and drop into the google docs. There I can easily fix the errors and  copy and paste the complete text back to dev.to tab. Very convenient especially if your other tools (word processors etc) need to be set to a other language than english.
Task Dependency Trees
Tags: notetaking, productivity, documentation, devjournal
Published: 2020-12-13 10:15:06

If you have a lot on your mind it generally helps to write stuff down. I played around with a lot of note taking tools and techniques. A few months ago I realized I like a specific pattern to keep track of my tasks. Instead of the usual task list I create a task tree. This helps in situations where you are fingering out what to do while you are doing it.

So how does this look? Let's assume the following situation (yes, made up. But hopefully it gets the point across):
You have two tasks you are working on. The first one is adding some logic to a script that copies files from a server. But to achieve this you realize you need to find which server actually has the files for you. If you have found the server, depending on the server type you need to use a certain library to find the data on the server and copy it. After you found out, you need to ask a colleague via email about the connection data.

My suggestion is to write it down like this:

- Adding copy logic to script a1.py
   - decide which library to use
      - lookup which server i need to copy from
   - email bob about the connection data
   
You write your main goal / task at the top. Indented under this are the steps you depend on to complete the main goal. One indented level deeper are the steps you depend on to complete your tasks from the level above.

Think of this as a tree. Your main task or tasks are the trunk. The Tasks in the different Levels represent the branches and the leafes. When you work on your tasks you complete the tasks with the highest level and than with the next highest level. You work from the leafes to the trunk.

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

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

This should give you the following information easily:
- What to work on(highest level tasks)
- Why you work on them (complete the tasks of the next level)
- Should help to illustrate some bottlenecks (If a task depends on a lot of other tasks to be completed first)
- If you need to complete for example ten levels of tasks to get to your main goal, you should maybe rethink your approach and see if this could be easier.

Getting a little fancier...

I use this system in OneNote. OneNote has a nice feature where you can put a symbol in front of a line. Ctrl + 1 gives me a checkbox for example. Adding these symbols helps to understand what I have to do a bit quicker. Plus it looks nice.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jkcgjstg4hqwdp8qpytt.png)
Hacktoberfest 2020
Tags: hacktoberfest, opensource
Published: 2020-12-13 09:26:30

Thank you DEV Community, DigitalOcean, Intel Corporation for organizing Hacktoberfest 2020. Got my t-shirt and swag delivered. Learned a lot from Hacktoberfest about open source and how to collaborate and communicate with other fellow developers. 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4i9wcaatsmql2bcco58c.jpg)
Hacking Django websites: Cross Site Request Forgery Protection
Tags: django, python, security, webdev
Published: 2020-12-13 08:38:23

_Ready for a Django security challenge? Play our [Django security challenge](https://django.doctor/challenge/settings-security)._

A malicious website that is accessed by one of your logged in users can fool your website into thinking a request come from that user. That may look like this:

1. The user accesses the malicious website
2. The website executes JavaScript to perform a request to your website
2. The browser exposes the user's cookies to your website
4. Your website thinks the request came from them

Here's a concrete example of a CSRF attack:

{% youtube C22BEW7AkrM %}

And without need for interaction from the user

{% youtube _1l4KuWGCQw %}

The impact of this attack depends on what the forms on your website do. Perhaps the form create a GitHub PR that removes Django tech debt from your codebase (like on https://django.doctor), or maybe it transfers money to someone? Bids on an item? Transfers ownership of the account to someone else? The possibilities are endless.


### Code

The simplest proof of concept React code is as follows:

```jsx
import React from 'react';
      
export default function (props) {
  return (
    <form action={"http://django.doctor/higher-tier/django-doctor-example/"} method="POST">
      <input type="submit" value="Do something innocent" />
    </form>
  );
}
```

And to make the form submit automatically with no user interaction required:

```jsx
import React from 'react';
      
export default function (props) {
  React.useEffect(function() { 
    document.forms[0].submit()
  }, []);

  return (
    <form action={"http://django.doctor/higher-tier/django-doctor-example/"} method="POST">
      <input type="submit" value="Do something innocent" />
    </form>
  );
}
```


### Prevention

Add the following to Django settings to prevent CSRF attacks:

```py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
]
```

And use Django's [csrf_token](https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#csrf-token) template tag in your forms. This will result in Django verifying the submitted form came from your website (the expectation being only your website will have valid csrf tokens).


### Does your website have security vulnerabilities?

Over time it's easy for security vulnerabilities and tech debt to slip into your codebase. I can check that for you at [django.doctor](https://django.doctor), or can [review your GitHub PRs](https://github.com/marketplace/django-doctor/):

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

Or try out [Django refactor challenges](https://django.doctor/challenge).
Tricks in MySQL
Published: 2020-12-13 08:31:57

 The following command shows you all of the processes currently running on your mysql server:
`mysqladmin processlist -u username -p`

Once in mysql and a database is select you can run the following to view the size and further information about your database (like the engine used on each table):
`SHOW TABLE STATUS;`

<b>To change a user's password:</b>
`mysql -u root -p`;
`ALTER USER 'user-name'@'localhost' IDENTIFIED BY 'NEW_USER_PASSWORD';`
`FLUSH PRIVILEGES;`

<b>To add a new user </b>
https://www.digitalocean.com/community/tutorials/how-to-create-a-new-user-and-grant-permissions-in-mysql

`CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';`
`GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';`
`FLUSH PRIVILEGES;`

<b> Extracting SQL file </b>
The following would extract the database into a sql file called dump:
`mysqldump databaseName > dump.sql`
Hacking Know Your Finances (KYF) - Part 0 Setup
Tags: dohackathon, react
Published: 2020-12-13 08:19:01

--- 
series: Hacking Know Your Finances DO Hackathon
---

## Goal
The countless historical record of income and expenses bring zero value to prepare for the future. KYF provides nice visualization insight into how the different upcoming income & expenses can affect you. You can now understand better about your financial health before committing to any financial decision.

## What I have done?
- Setup [Public Github Repo](https://github.com/Zaccc123/kyf) with MIT License
- Deployed an app using DigitalOcean’s App Platform that falls under the Built for Business Category
- Fill out the [form](https://docs.google.com/forms/d/e/1FAIpQLSdHljGT15tIBAl6awNWh1-s3LCP3HMPPgZX5WE9LgHISp6Oiw/viewform?usp=sf_link) to get a $50 credit for DigitalOcean for this DO
- Started [documenting a series](https://dev.to/zaccc123/hacking-know-your-finances-kyf-part-0-setup-3g2p) for the DO Hackathon

## What I plan to do next?
It's been a while since I spend some focused time on coding. I am going to look for possible tools to speed up my development process. Likely to use the following tools:
- Tailwind CSS
- AntDesign
- Basic WYSIWYG UI Input


### How I know about this?
Found out about the [DO Hackathon](https://dev.to/t/dohackathon) from my friend [Kim](https://dev.to/simkimsia). Check out what he is building [here](https://dev.to/simkimsia/building-gogreen-1-n-1pfp).

### Why am I doing this?
For fun and to get back into more coding during my free time. I have transited to a product manager for my day job for about 2 years. Since then, I can only code in my free time. But as work gets busy, I begin to code lesser and lesser. Found out about the DO Hackathon and therefore I hope to intentionally set aside time to do it.