teleren/devto huggingface dataset:
Why the heck the _state variable in task_struct structure is 4 bytes
Published: 2023-02-28 01:34:32

According to Robert Love the Author of the book Linux Kernel developement & Linux kernel source :

In the Linux kernel , specifically in the PCB ( process control block ) which a structure that represents the process in the kernel .

The process state is represented by a combination of six state flags, which are:

**TASK_RUNNING**: The process is currently running or ready to run.

**TASK_INTERRUPTIBLE:** The process is waiting for a specific event to occur and can be interrupted by a signal.

**TASK_UNINTERRUPTIBLE**: The process is waiting for a specific event to occur and cannot be interrupted by a signal.

**__TASK_STOPPED**: The process has been stopped (e.g. by a SIGSTOP signal) and can be resumed later.

**__TASK_TRACED**: The process is being traced by another process (e.g. a debugger).

**TASK_DEAD**: The process has terminated and is waiting to be reaped by its parent process.

Each of these flags can be set or cleared to represent the different states that a process can be in. For example, a process that is both **TASK_INTERRUPTIBLE** and **TASK_UNINTERRUPTIBLE** might be waiting for a disk I/O operation to complete, and can be interrupted by a signal but cannot be killed until the I/O operation is finished.

In other words, a process can have multiple states at once, depending on which combination of flags is set.

This state is saved in an **UNSIGNED INTEGER **, that means 32 bits , that means 2³² possible values , but we need only 2⁶ , so 64 possible states as a maximum .

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uzyjgn454zk879nczq4w.png)

the reason is the following : 

There are some predefined functions that manages the process's state such as **READ_ONCE/WRITE_ONCE** that obliges this variable to be an unsigned INT , it's used to be a volatile Long ; here are the commits : 

https://github.com/torvalds/linux/commit/2f064a59a11ff9bc22e52e9678bc601404c7cb34#diff-f8d8a1568ae83bbff6f40f9c70559a4f7dbf426a397131ba9d4fbfb947ea5222R669

Thank you for reading <3 .
Acessando rotas protegidas CSRF ou autenticadas do Laravel com o Postman
Tags: postman, laravel, api, php
Published: 2023-02-28 01:33:15

As vezes precisamos acessar rotas autenticadas ou rotas protegidas com o CSRF com o Postman para fazermos testes, abaixo vou mostrar como conseguimos fazer o login e pegar o valor do token sem precisar excluir URIs da proteção CSRF .

> Lembrando que o postman é para testes de api, mas se por algum motivo precisarem acessar rotas que não sejam de api segue a dica.

1 - Criar o ambiente no postman
```
Environment name: Meu projeto
key: url 
value: http://127.0.0.1:8000/
```
![Environment postamn](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfwg6a71akkaqm0uc5od.png)

2 - Agora você pode usar o endpoint com a variável criada no meu caso url , então ficaria assim: `{{url}}/login`

3 - Adicione o código abaixo na seção **Tests** para criar a variável chamada _xsrf-token_

```javascript
var xsrfCookie = postman.getResponseCookie("XSRF-TOKEN");
var xsrfToken = decodeURIComponent(pm.cookies.get("XSRF-TOKEN"));
pm.environment.set("xsrf-token", xsrfToken);
```
![postman tests](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1u8pmecfir65er7w65o4.png)

4 - Na seção **Headers** adiciona as seguintes variáveis

```
Content-Type:application/x-www-form-urlencoded
X-XSRF-TOKEN:{{xsrf-token}}
Accept:application/json
```

![postman headers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tzigzt50bogywn8684ti.png)

5 - Agora você já pode enviar a solicitação POST para efetuar o login, não esqueçam de colocar no **Body** os campos `email` e `password`

![postman auth](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdvyv08akoosxr3yz1zb.png)
Reorganizing Flask Mail App
Published: 2023-02-28 00:51:39

Hi everyone! I am working on setting up a web application using Flask. I want to be able to send users emails, like when they sign up for example. I followed a tutorial (Sending Emails with Flask - Step-by-Step Flask-Mail Guide | Mailtrap Blog - Sending emails in Flask) and it was working until I reorganized the code to be more than one file, which I need to do to make it work with the rest of my project. Since then, I am getting an error

File “C:\Flask Mail\service\routes.py”, line 6, in index
mail.send(msg)
NameError: name ‘mail’ is not defined

I am clearly doing something wrong, but I don’t know what. My file structure is like this:

Flask Mail
env
service
| pycache
| init.py
| extensions.py
| routes.py
run.py

My code looks like this:
```
    #__init__.py
    from flask import Flask
    from service import routes
    from .extensions import mail
 
    def create_app(config_file=None):
        # create and configure the app
        app = Flask(__name__)
    
        app.add_url_rule("/", view_func=routes.index)
    
        app.config['MAIL_SERVER']='sandbox.smtp.mailtrap.io'
        app.config['MAIL_PORT'] = 2525
        app.config['MAIL_USERNAME'] = <username from mailtrap>
        app.config['MAIL_PASSWORD'] = <password from mailtrap>
        app.config['MAIL_USE_TLS'] = True
        app.config['MAIL_USE_SSL'] = False
    
        mail.init_app(app)
    
        return app
```
```
    #extensions.py
    from flask_mail import Mail, Message
    mail = Mail()
```
```
    # routes.py
    from flask_mail import Message
    
    def index():
      msg = Message('Hello from the other side!', sender =   'peter@mailtrap.io', recipients = ['paul@mailtrap.io'])
      msg.body = "Hey Paul, sending you this email from my Flask app, lmk if it works"
      mail.send(msg)
      return "Message sent!"
```
```    
    # run.py
    from service import create_app
    
    app = create_app()
    
    
    if __name__ == '__main__':
       app.run(debug = True)
```

What am I missing here?
Introducing... The 2023 College Javascript Tournament
Tags: javascript, webdev, computerscience, devops
Published: 2023-02-28 00:51:01

Tech wizards and college students, listen up about this amazing opportunity to test your skills in the first ever 2023 College Javascript Computer Tech Tournament. 

The 2023 College Javascript Tournament is a brand new tournament, ranks the best schools with the best computer tech programs in coding, marketing, and engineering all in one roof.

The tournament begins on March 2 and will last through April 1, as you will need to follow me on Twitter and Instagram to see who has advanced on to the next round, but you can fill out your bracket by downloading this image below:
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0lkcamueagz267mwvtu.png)

The winner of the contest will get a shoutout in one of my YouTube videos, and a collab opportunity.

You can download the bracket above or upload it as a PNG photo to fill out. If you would like the Excel version of this bracket to fill out, email me at braydynlents09@gmail.com, and I will feature your bracket on the leaderboard if you follow me on Twitter @lentsbraydyn as every week during the official NCAA Tournament, we will reveal the winners week by week. Have fun playing the 2023 College Javascript Computer Tech Tournament.

Have fun and enjoy playing in the #javascriptthTournament.
Node.js built-in module functions as Promises
Tags: node
Published: 2023-02-28 00:11:19

---
title: Node.js built-in module functions as Promises
published: true
tags: ['node']
canonical_url: https://sevic.dev/notes/nodejs-builtin-modules-promises/
---

Node.js provides asynchronous methods for `fs`, `dns`, `stream`, and `timers` modules that return Promises.

```js
const {
  createWriteStream,
  promises: { readFile }
} = require('fs');
const dns = require('dns/promises');
const stream = require('stream/promises');
const timers = require('timers/promises');
const sleep = timers.setTimeout;
const SLEEP_TIMEOUT_MS = 2000;

(async () => {
  const fileName = 'test-file';
  const writeStream = createWriteStream(fileName, {
    autoClose: true,
    flags: 'w'
  });
  await stream.pipeline('some text', writeStream);

  await sleep(SLEEP_TIMEOUT_MS);

  const readFileResult = await readFile(fileName);
  console.log(readFileResult.toString());

  const lookupResult = await dns.lookup('google.com');
  console.log(lookupResult);
})();
```

Use the `promisify` function to convert other callback-based functions to Promise-based.

```js
const crypto = require('crypto');
const { promisify } = require('util');
const randomBytes = promisify(crypto.randomBytes);
const RANDOM_BYTES_LENGTH = 20;

(async () => {
  const randomBytesResult = await randomBytes(RANDOM_BYTES_LENGTH);
  console.log(randomBytesResult);
})();
```
OSD700: Working with BullMQ Worker/Queues
Tags: opensource, typescript, beginners, api
Published: 2023-02-27 23:58:34

This week I got to work with workers/queues without prior experience. I had to fill gaps in my understanding, and implement functionality simultaneously, so this week was less productive in terms of coding and more in terms of learning. 
One of the main reasons I struggled working with BullMQ API was that the concepts seemed too abstract. It took me a while to understand the relationship between Queues and Workers and how to leverage them to run background tasks to check whether we have to send email reminders to users or not. 

I added a background job to Starchart to repeat every 5 minutes and check whether any domains or certificates in the database expire in less than a month. We send out notifications if we find such an entry in the database. We are also keeping track of the number of times we have notified the user, as we only want to send up to two reminders. The first reminder will be sent out one month in advance, and the second reminder will only be sent out close to the expiration date. 

At the moment, I want to send the first reminder without any problems or side effects. If that goes well, I will work on sending another reminder close to the expiration date.

I want to get comfortable working with BullMQ workers and queues, as the api can be leveraged in many projects requiring background job processing to solve real-world problems without burdening the application.
[Flutter] Managing App Name and bundle ID only in pubspec 🪄. Pub.dev flutter_rename_app_plus
Tags: flutter, ios, android
Published: 2023-02-28 00:08:08

flutter_rename_app_plus, a pub.dev package enable to manage application_name and bundle_name in pubspec.

https://pub.dev/packages/flutter_rename_app_plus

And if You change their values in pubspec, it automatically change them, including info.plist, and androidmanifest.xml. 


By applying this, you can efficiently make a new flutter  project by cloning and converting existing one! 🦄

Parameters are below.
```
flutter_rename_app_plus:
  application_name: Bank App
  dart_package_name: bank_app
  application_id: com.android.bank
  bundle_id: com.ios.bank
  android_package_name: com.bank.app
```

https://pub.dev/packages/flutter_rename_app_plus
Setup HTTPS with Nginx and Docker
Tags: docker, nginx, https
Published: 2023-03-01 16:49:35

---
title: Setup HTTPS with Nginx and Docker
published: true
date: 2023-02-28 00:00:00 UTC
tags: docker, nginx, https
canonical_url: https://blog.robertoconterosito.it/posts/setup-https-with-nginx-docker/
---

_Welcome back to my dev notes!_

Today I was in trouble for a while because I wanted to setup HTTPS with Nginx and Docker and I completely forgot how to do it. So I decided to write down this guide to help me in the future and maybe it will help you too.

I have a Docker container running a PHP application served by Nginx and I wanted to setup HTTPS with a self-signed certificate because I need to test some OAuth flows.

Follow these steps to setup HTTPS with Nginx and Docker:

# Create a self-signed certificate

```
openssl x509 -outform pem -in localhost.crt -out localhost.pem

```

# Edit nginx configuration

Please take attention to the `ssl_certificate` and `ssl_certificate_key` files paths.

```
server {
 listen 443 ssl;
 server_name localhost;
 ssl_certificate /etc/nginx/ssl/localhost.crt;
 ssl_certificate_key /etc/nginx/ssl/localhost.key;
 ...
}

```

# Restart docker

If you are a perfectionist like me you can also add the certificate to your system keychain to avoid browser warnings. Using Mac OS you can do it like this:

```
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain localhost.crt

```

Enjoy!
CodeNewbie Memes
Tags: beginners, codenewbie, discuss
Published: 2023-02-27 23:53:38

It's Meme Monday over here at DEV and we from CodeNewbie thought it might be about time that we start our own thread of memes, specific to the newbies!!!!

SO— if you have any newbie-related, job-related, or starting-a-new-career-related memes or inspiration— we would love to see them! OR if you are a newbie, welcome, it's great to have you here!
The ABCs of JavaScript: Autoboxing in javascript
Published: 2023-02-27 23:41:00

In our previous [article ](https://dev.to/ismailabbi/the-abcs-of-javascript-primitive-and-object-types-3982), we discussed that JavaScript has not only objects but also primitive types. We also mentioned that primitive types do not have properties or methods since they are not objects.

However, let's test this point to confirm whether it is true or not. Try running this code in your editor:
`const name = "john";
console.log(name.length);`


The output will be 4, which refers to the number of characters in the string. But wait, **didn't we just say that primitive data types don't have properties?** :angry: :angry: :angry: :angry:

## Autoboxing 

Don't worry, there is an explanation for this :blush: :blush:. Although primitive values don't have properties or methods, JavaScript uses the concept of **_autoboxing_** to create a temporary object wrapper around the value when we use a property or method on a primitive value.

So, when we use the .length property on the string primitive name, JavaScript automatically creates a temporary String object wrapper around the value "john", which allows us to access the .length property.


We should note that this object is a built-in object in JavaScript, and there are many predefined objects such as String, Boolean, Date, and Math. JavaScript detects the type of primitive data that we create and automatically creates an object that corresponds to that data type. For example, since we created a string primitive in our example, the object created by JavaScript is a String object.

## manual boxing

We can also perform manual boxing ourselves. Here's an example:

`let firstName = String("naima");
console.log(firstName.length);
console.log(name.valueOf()); // "john"`

In this example, we create an object directly without using autoboxing, and we can retrieve our primitive value using the valueOf() method.

I hope this article helps to clear up the confusion that exists around primitive types in JavaScript
让ChatGPT给孩子讲讲什么是公司股票
Tags: chatgpt, blog
Published: 2023-02-27 23:32:16

最近孩子问我什么是公司的股票，问我有多少<a href="https://justyy.com/archives/45631" title="我是怎么加入微软剑桥研究院成为一名高级软件工程师的">微软</a>的股票。这个概念确实很难讲明白，所以我让最近很火的人工智能 ChatGPT 生成式的AI (Generative AI)帮帮我。

问: Explain to Kids what is company shares?

答: 
<blockquote>
Sure, I'd be happy to help explain what company shares are to kids!

When someone starts a company, they often need money to help get things started. They might ask friends or family members to lend them money, or they might go to a bank for a loan.

But another way to raise money is to sell something called "shares" in the company. Shares are kind of like little pieces of ownership in the company. When someone buys a share, they're basically giving the company some money in exchange for a tiny part of the company.

For example, let's say a company has 100 shares total. If you buy one share, you now own 1% of the company. That might not sound like a lot, but if the company becomes really successful, your 1% ownership could be worth a lot of money!

Companies often sell shares to lots of different people, so there might be lots of different owners of the company. And if the company does well and becomes more valuable, the value of the shares can go up, which means the owners can sell their shares for more money than they paid for them originally.

So, in summary, company shares are little pieces of ownership in a company that people can buy and sell to help the company raise money and potentially make money for themselves in the future.
</blockquote>

让ChatGPT自己翻译一下:

<blockquote>
当某人创办一家公司时，通常需要资金来帮助启动事业。他们可能会向朋友或家人借钱，或者他们可能会向银行贷款。

但是另一种筹集资金的方式是出售公司的股票。股票有点像公司的小小所有权。当某人购买一股股票时，他们基本上是向公司提供一些钱，以换取公司的一小部分。

例如，假设一家公司总共有100股。如果你买了一股，你现在就拥有这家公司的1％所有权。这可能听起来不算太多，但如果公司变得非常成功，你拥有的1％所有权可能会价值连城！

公司经常向许多不同的人出售股票，因此可能有许多不同的公司所有者。如果公司表现良好并且变得更有价值，股票的价值可能会上涨，这意味着股票所有者可以以高于最初购买价格的价格出售股票。

因此，总之，公司股票是公司的小小所有权，人们可以购买和出售这些股票来帮助公司筹集资金，并有可能在未来为自己赚取利润。
</blockquote>

重新问了一下（给孩子讲讲什么是公司股票），生成的答案并不完全相同，但大体套路都是一样的。ChatGPT 每次都是一个字一个字往下蹦，说明它是在不停的说出概率大的下一个字(Token)是什么，并不一定是真正理解了问题。

<blockquote>
好的，我可以向孩子们讲解一下什么是公司股票。

当一个人或一组人创立一家公司时，通常需要一定的资金来帮助公司启动和运营。他们可以从亲戚朋友那里借钱，或者向银行贷款。但是，还有一种筹集资金的方式，那就是出售“股票”。

<a href="https://justyy.com/archives/61060" title="订单簿简介(Order Book)+最简单的高频交易策略HFT(低买高卖)">股票</a>就像是对公司所有权的一种表示。如果你买了公司的股票，你就是这家公司的一位小股东。你可以持有公司的一部分股份，就好像你有了公司的一小部分所有权。

举个例子，如果一家公司有100股股票，而你买了其中一股，那么你就拥有了这家公司的1%的股份。这听起来可能不多，但如果这家公司变得非常成功，那么你的股份就可能变得非常有价值。

股票是可以被买卖的。如果这家公司的股票价格上涨，那么你就可以卖出你的股票，赚取你的投资收益。当然，如果这家公司的股票价格下跌，那么你的投资收益也可能会减少。

所以，公司<a href="https://justyy.com/archives/32302" title="疫情来了, 股市低迷, 我的GE股票缩水一半">股票</a>就是公司的一种筹集资金的方式。当你购买了公司的股票，你就成为了公司的股东，拥有了公司的一部分所有权。当公司成功时，你的股票可能会变得更有价值，让你赚取收益。
</blockquote>

下次问问<a href="https://justyy.com/archives/4067" title="有关期权和股权的几个问题">期权</a>是什么？和股票有什么不同。

这种获取知识的方式很便捷，不再需要在搜索引擎里输入关键字，然后一个一个打开链接去寻找自己想要的知识点。通过ChatGPT直接就能吃上喂到嘴边的饭，不得不说，这对于传统<a href="https://justyy.com/archives/3339" title="一个长尾关键字的例子 – 带来短时间的流量">搜索引擎</a>(Google)简直是降维打击。从搜索引擎出现的20年以来，我们习惯了这种搜索获取知识的方式，只是因为没得选择。

博客: [让ChatGPT给孩子讲讲什么是公司股票](https://justyy.com/archives/61321)
My Month of Machine Learning Learning: Introduction
Tags: machinelearning, deeplearning, ai
Published: 2023-02-27 23:29:40

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yr480kxo14v8se9u2ip5.png)

Hello, world!

After having my brain [set on fire](https://www.lesswrong.com/posts/jtoPawEhLNXNxvgTT/bing-chat-is-blatantly-aggressively-misaligned) by the Turing-test-destroying Bing Search AI ([RIP Sydney](https://libreddit.kavin.rocks/r/bing/comments/115fxc1/she_was_a_good_bing_freesydney/)), I became almost obsessively interested in language models and how they work. As a result, I've decided to spend a month and ~100 hours learning just that.

My background: I've been writing code for a long time and had a brief stint as a professional developer, but I don't work in the industry right now. I have no background in machine learning or in artificial intelligence more generally.

My basic goal: To be able to build/use/train (I'm not very familiar with the terminology yet) language models to perform specific tasks and to understand, at least roughly, the underlying theory behind how they work.

This goal is subject to change as I get deeper into the subject and hone in on what I'm interested in. I also have a feeling 100 hours might be overkill for achieving my initial goal, in which case (assuming stable motivation) I'll create new ones.

To start with, I'll be using [_Hands-On Machine Learning_](https://www.oreilly.com/library/view/hands-on-machine-learning/9781098125967/) as my primary resource, in preparation for moving on to [_Natural Language Processing with Transformers_](https://www.oreilly.com/library/view/natural-language-processing/9781098136789/). I'll expand into other materials as I get more familiar with the topic.

Prerequisites to take care of:
- (Re)learning Python: Python was my first programming language—but that was over ten years ago. I'll also need to get comfortable with the NumPy, Pandas, and Matplotlib libraries.
- Brushing up on some math: Relevant linear algebra and differential calculus basics (for the time being).

I'll be applying learning principles and techniques from the book [_Ultralearning_](https://www.scotthyoung.com/blog/ultralearning/) by Scott Young (feel free to check out my [book notes](https://app.skiff.com/docs/e0c46bbf-86d9-4cdc-91f6-6fb42f10e8d9#BEKkje7%2BIxetbzAhCFRm8d6LLRqYozm22612rl33cd4%3D) if this sounds interesting to you).

I'm hoping this blog will help keep me motivated, provide a record of my progress, and maybe elicit useful feedback from the community. I plan to check in here twice a week with progress updates and reflections.

Naturally, cover images will be generated by DALL-E or Stable Diffusion.
Discovering the Magic of CSS and HTML
Tags: beginners, css, html
Published: 2023-02-27 23:11:45

I am thrilled to share that I have recently embarked on a journey of learning CSS and HTML. As someone who has always been passionate about the beauty things and design.

As I have started to explore the intricacies of CSS and HTML, I have been struck by the sheer power and versatility of these technologies. 

CSS, for example, allows you to completely transform the visual appearance of a web page with just a few lines of code. You can adjust everything from the layout and positioning of elements to the fonts, colors, and animation effects used to bring the page to life.

HTML, on the other hand, is the backbone of every web page. It provides the structure and content that is then styled and formatted by CSS.

One of the most gratifying aspects of learning CSS and HTML is the immediate feedback you get from the browser. it's possibilities are endless, and the sense of accomplishment when you finally get your page looking just right is truly addictive.

Of course, learning any new skill takes time and effort. 
There are times when I feel frustrated  by the complexity that the code means to me, because I've never code before. But I am determined to persevere, cause I know that the rewards of mastering CSS and HTML will be worth it. 

In conclusion, I am excited to be on this journey of discovery and growth as I learn CSS and HTML. It IS a challenging and rewarding endeavor that I believe will make a difference both personally and professionally

This is my first project:
https://srhiulli.github.io/MyFirstForm/

Thanks for reading :D