teleren/devto huggingface dataset:
Using blocking code in async
Tags: rust
Published: 2021-11-27 06:08:39

Tokio's block in place example, this is discussed [here](https://www.reddit.com/r/rust/comments/lg0a7b/benchmarking_tokio_tasks_and_goroutines/gmpcnt2/?context=3), same thing in golang is [here](https://gist.github.com/niklaskorz/38744f7ec2ce541e16eca609dd997be0)
	
``` rust
// source - https://gist.github.com/miquels/8576d1394d3b26c6811f4fc1e7886a1c
use std::{
fs::File,
io::{Read, Write},
time::Instant,
};
use tokio::task::{self, JoinHandle};
		  
async fn compute() {
let handles: Vec<JoinHandle<_>> = (0..1000)
    .map(|_| {
        tokio::spawn(async move {
            let mut buffer = [0; 10];
            {
		  
                task::block_in_place(move || {
                    let mut dev_urandom = File::open("/dev/urandom").unwrap();
                    dev_urandom.read(&mut buffer).unwrap();
                });
            }
            task::block_in_place(move || {
                let mut dev_null = File::create("/dev/null").unwrap();
                dev_null.write(&mut buffer).unwrap();
            });
        })
    })
    .collect();
for handle in handles {
    handle.await.unwrap();
}
}
		  
#[tokio::main]
async fn main() {
// warmup
compute().await;
		  
let before = Instant::now();
for _ in 0usize..1000 {
    compute().await;
}
let elapsed = before.elapsed();
println!(
    "{:?} total, {:?} avg per iteration",
    elapsed,
    elapsed / 1000
);
}
```

**I like `async-std` better here**


### Parallel Hacker news scraping using tokio's `block_in_place`

```rust
use serde_json::Value;
use tokio::task::{self, JoinHandle};

const URL: &str = "https://hacker-news.firebaseio.com/v0/topstories.json";
const ITEMURLBASE: &str = "https://hacker-news.firebaseio.com/v0/item";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {

    let resp = reqwest::get(URL).await?.json::<Vec<i32>>().await?;

    let total_stories = resp.len();
    let concurrency = 50;

    // Create a task group, get 10 story titles at a time
    let only_some = resp[0..total_stories].to_vec();

    for chunk in only_some.chunks(concurrency) {

        let handles: Vec<JoinHandle<_>> = chunk
            .iter()
            .map(|&i| {
                let item_url = format!("{}/{}.json", ITEMURLBASE, i);
                tokio::spawn(async move {
                    // Using block_in_place to avoid context switching
                    task::block_in_place(move || {
                        let r = reqwest::blocking::get(&item_url).unwrap().text().unwrap();
                        let json: Value = serde_json::from_str(&r).unwrap();
                        let title = json["title"].clone();
                        (item_url, title)
                    })
                })
            })
            .collect();

        for handle in handles {
            let (_urls, titles) = handle.await.unwrap();
            println!("{}", titles.as_str().unwrap());
        }

    }

    Ok(())
}
```
App secrets in dot net core
Tags: programming, dotnet, tutorial
Published: 2021-11-27 05:52:30

Create new application in dotnet core using CLI or Visual Studio IDE
Go to project directory and run below command   
```
dotnet user-secrets init
dotnet user-secrets set "Key_name" "key_value"
```
>now get value using 
Environment.GetEnvironmentVariable("Key_name");
or
 private readonly IConfiguration _config;
        public Classtest(IConfiguration config)
        {
            _config = config;
        }

string _key=_config["Key_name"]
Extension methods
Tags: rust
Published: 2021-11-27 05:23:48

### Square extension on numbers

```rust
mod foo {
    pub trait SquareExt {
        type Out; // Associated type
        fn square(self) -> Self::Out;
    }

    use std::ops::Mul;
    impl<T> SquareExt for T
    where
        T: Mul + Copy,
    {
        type Out = <T as Mul>::Output; // Using Mul's associated type
        fn square(self) -> Self::Out {
            self * self
        }
    }
}

fn main() {
    use foo::SquareExt;
    let a = 10.square();
}
```
Easy way to create single page app
Published: 2021-11-27 05:17:57

The list of libraries available for deploying web apps, the list does try to aim to be easiest way to deploy single page apps on web.

## Web libraries

- Phoenix LiveView (Elixir)

So many possibilities with real time data updates on page. Requires server.

- Rust+Wasm Yew framework, or flask-like Rocket in Rust

Write full front end using Yew (WASM) and backend in Rust.

- Flask et.al (Python)

Battle tested, easy to use. Hard to achieve good concurrency and real time updates without good coding/infrastructure support

- Node.js/Deno (Express/Oak)

Async, speedy JS. Best for prototypes and production.

- Nim code (backend and front end), karax for single page applications

Compilation to JS makes it much better to make web apps. Backend is also stupid fast

- Akka + Scala.js

Using Akka HTTP for backend and Scala.js for front end. JVM and sbt are a drag to use

- CLJS (figwheel-main, shadow-cljs)

Write Clojurescript. Good, easy and hot reload setup. Lisp. Excellent for single page apps

- Flutter app

Possibility to port a website to mobile app. But generally, writing dart is better than JS, flutter productivity is good

- Using ReScript+React SPA

Looks like Scala but OCaml, easier/faster to learn than typescript??, with really good tooling and very concise JS output. No server side ReScript.

- Dart (Angular Dart)

Another heavy framework, dart2js -O3 gives concise output. (Although, Rescript is faster to learn)


## JS Apps

1. WMR + Preact (fast and easy to use)
2. Svelte. Easy to use and understand.
3. Angular/React?
4. AlpineJS or Stimulus (great for HTML heavy with small JS)
5. htmx
6. MVP.css

## Hosting

1. Glitch (static free, paid servers)
2. Replit (static free, node servers - free for now?)
3. Render (static free, paid for server based)
4. Firebase+Cloud Run (firebase hosting free for static sites, host assets on Firebase CDN and any server on Cloud Run, has good free tier)
5. Github Pages (static only - free)
6. Vercel (static only with server less functions support, no servers)
7. Cloud Run
8. Fleek (static - decentralized)
9. Heroku?
10. Surge (static)


Databases

1. gun.eco is a p2p database, super easy to setup and very fast. This is truly simple and revolutionary

Using the database is as simple as `docker run -p 8765:8765 gundb/gun`

# node or js 
# for js include cdn
```
var Gun = require('gun');
var gun = Gun(["http://localhost:8765"]);
```
2. firebase
3. supabase
OSD600 - Lab 10 - Publishing my Package
Tags: beginners, javascript, opensource
Published: 2021-11-27 05:06:42

## Introduction
Hello all, this week, again I have explored new stuffs, which is about publishing my static site generator to NPM. This is actually my first time ever doing this.

## How I Get Started
First, I follow [these steps](https://docs.npmjs.com/packages-and-modules/contributing-packages-to-the-registry) to set up my package to publish it. I have previously done most of the steps as it mentioned. However, when I try to run `npm publish`, looks like the package is not satisfied with me for some reason. It shows this message for me ![authentication-image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/whth7zsri1dtcmp60ae2.png) I figure out the reason why it happens is because I did not log into NPM yet, so I have to run `npm adduser`, as well as log into [npmjs](https://www.npmjs.com/) too. I thought it was success after adding username there, but no, another time of encountering error. I am totally clueless why it says my package name is too similar to existing package ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jaj03tu21ccoppx6kxvu.png) However, I has to follow what the message says, I head into my `package.json` file and then change the name of my program. After all, everything is fine. This is my package after publishing: [my package](https://www.npmjs.com/package/txt2html_version2).

Two things I did for my package is testing it as a user, and then kindly ask my friend to try it without giving any extra information. I thought I would be in trouble when I do this, but my program is looking good. Moreover, I am also thinking about maintaining this program, add more features in the future, make it better then how it is right now.

## Conclusion
OSD600 is an amazing course I have ever taken, it taught me a lot of things I have not known before. Giving me chances to go through all concepts about Git. After this course, I could say that I have more experience in using Git. My friend has to admit that Git is really important and powerful even though he has been in this IT field for many years. As my professor said, "git is hard. But if you really take the time to understand it, it’s so powerful", and I always put those words in my mind as a motivation.
Get your proposal winning: Bits of Advice from TOP RATED FREELANCER on Upwork
Tags: career, tutorial, productivity, beginners
Published: 2021-11-27 05:03:02

Hi there!

Let's jump into the steps directly to save your time 🙂

ON Upwork, clients need to work with the best freelancer and the best freelancer is the one who knows clearly what is the client need.

So, using a real example I'll show you how I got a job from a client, the client contacted me instantly.

There was a job on Upwork, the client want to clean up some data in an Excel file.

In this case, you've to show the client that you understand the need and know how you will do the task.

![The Job Posting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/129k5hiry75yo5egdpvc.png)

and my proposal was

![Proposal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i65oyonkfltl4mxmj896.png)
 
You can see here that I've sent a video to explain to the client how I'll do the task, and imagine at the moment the client says WOW!. because he can see that you're really interested in the job and knows how you'll do it. so no way, he will contact you.

and don't forget to explain more in the proposal that you understand the description and your free time to start the work.

I hope you benefit from this experience and apply it to get great results.

[Upwork: Tawfik Y.](https://www.upwork.com/freelancers/~0153b17a33b0226c96)

Good Luck,

Tawfik
Worker queues
Tags: programming, devops
Published: 2021-11-27 04:42:23

## Redis as a Job Queue

Tried Beanstalkerd, for a job queue, realized the language support is not very good.

But, I realized Redis has Lists. We can use them to push (from producer) and pop (worker/consumer)


### Producer pushes

```
127.0.0.1:6379> RPUSH list2 0
(integer) 1
127.0.0.1:6379> RPUSH list2 1
(integer) 2
127.0.0.1:6379> RPUSH list2 2
(integer) 3
127.0.0.1:6379> RPUSH list2 3
(integer) 4
127.0.0.1:6379> RPUSH list2 4
(integer) 5
```

### Consumer pulls from the queue

```
127.0.0.1:6379> BLPOP list2 0
1) "list2"
2) "0"
127.0.0.1:6379> BLPOP list2 0
1) "list2"
2) "1"
127.0.0.1:6379> BLPOP list2 0
1) "list2"
2) "2"
127.0.0.1:6379> BLPOP list2 0
1) "list2"
2) "3"
127.0.0.1:6379> BLPOP list2 0
1) "list2"
2) "4"
```

We can also push multiple items to the list, and have multiple consumers listening to the same list with no duplication. 

P.S. - "B" in "BLPOP" is blocking operation, waits for the message from the queue
Roblox Studio - How To Make Games - #1
Tags: programming, tutorial, beginners, gamedev
Published: 2021-11-27 03:49:31

You're wanting to create a roblox game. You go to [roblox](https://roblox.com/), you login, and you start looking for the link. You may find it or it might find you -- just in case you don't know where it is, click Create on the top tab -- and you download the program required. You start Roblox Studio and then you create a template (use baseplate).

![Roblox projects to select from](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/310l5o7doht26rp0ud57.png)

Hold on. When you get inside, you don't know what to do. How do we fix that?

Well, we could make a script.

Click on workspace, press the plus button, and add a Script. Not a LocalScript, but a Script.

After you do that, copy and paste the following code.

```
local players = game.Players -- get players
players.PlayerAdded:Connect(function(plr) -- on player joined get player
	local char = plr.Character or plr.CharacterAdded:Wait() -- wait for character
	local hum = char:WaitForChild("Humanoid") -- wait for humanoid
	hum.Health = 50	-- change humanoid health to 50
end)
```

This code looks overwhelming, but as you can see here, this gets the list of players, get player when added, gets the character and the humanoid (properties of the player). Then it changes the humanoid health to 50. Read more [here](https://developer.roblox.com/en-us/api-reference/class/Humanoid).

Well, that's all of now. Be prepared for future updates. I will let you know when I released another one.
Creating Command Line Tool using swift package manager
Tags: swift, javascript, webdev, beginners
Published: 2021-11-27 03:32:29

## Introduction to SPM
The release tool used in swift programming is a swift package manager [Package Manager](https://www.swift.org/package-manager/)
The Swift Package Manager is a tool for controlling Swift code distribution. It works with the Swift build system to automate the download, compilation, and linking of dependencies.
-The Package Manager is included in Swift 3.0 and above.-
```
$ swift package init --type executable
```

## Release version to command-line-Tool
You'll want to install your command-line utility after you've finished developing it. This can be accomplished by using the release configuration while building. Within the.build/release folder, an executable will be created. We need to copy it into the /usr/local/bin folder before we can utilise it.

```
$ swift build --configuration release
$ cp -f .build/release/banner /usr/local/bin/banner
```

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

## Using Git Tags
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmhsbc5juysc6qte43j4.png)
```
git tag  -a v1.1 -m "ModernSSG version"
```

## User Testing

Well, I partenered with ritik bheda, he made his project in node.js. Testing with node.js is simpler and easier task. I tested the project and we didn't run into any error. It was very well communicated with other members to test project build in their language.

## How to use and run my swift project
```
$ swift build
$ swift run
```
or 
Double click the ModernSSG executable file to run the project.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6og17to3vyno1ntw800i.png)
Self-Taught Developer Journal, Day 5: CSS, Joining, Virtual Coffee, and Binary Search
Tags: todayilearned, beginners, devjournal, codenewbie
Published: 2021-11-27 03:08:05

Back from the holidays! I hope everyone had a great Thanksgiving :).

Today I learned...

## CSS
* **The CSS Box Model** is the idea that everything in CSS is a box. The boxes wrap around every HTML element and are built up of core pieces: content, padding, border, margin. Each of these pieces have different properties.
* *Content* manipulates the width and height properties of the inner content box that contains the HTML element.
* *Border's* commonly used properties are border-width, border-color, and border-style.
  * **border-width** controls the thickness of the border
  * **border-color** controls the color
  * **border-style** controls the line style (dashed, etc.)

You can also use a border shorthand property. A shorthand property is a single property that can set multiple properties like width, style, and color for border.

    border: 4px solid black

**border-radius** is used to round the corners of an element's outer border edge.
* *Padding* is the space between the content and the border of the element. Like the bubble wrap of a box. Same as border, you can set individual properties and shorthand.
* *Margin*
The space outside of an elements border. The space in relation to the other elements around it. Also includes individual and shorthand properties.
* Display Property
  * Inline - width and height are ignored. Margin and padding push elements horizontally but not vertically.
  * Block - break the flow of a document. Width, margin, height, and padding are respected.
  * Inline Block - behaves like an inline but width, margin, height, and padding are respected.

## C
I am still on chapter one, I finished the section on word counting and got to arrays. I am trying to make sure to do the exercises after the sections. I got a little confused on the one for arrays and revisiting it tomorrow.

## Binary Search
Continuing from last weekend, I was reviewing the Binary Search algorithm and decided to test myself on an easy LeetCode problem. I had some trouble on it and had to look up the solution. I am happy I decided to practice it because I realized I didn't understand it as much as I thought I did.

## Joined Virtual Coffee
I participated in my first [Virtual Coffee](https://virtualcoffee.io/) meet-up yesterday! I had a great conversation with the group I was in and got some good insights.

## Ending Thoughts
I am beginning to understand that I don't need to learn everything because its that's not realistically possible and even senior developer have to continuously learn new things. So what is something I don't have that they do? Or what is it I'm still lacking?

Resources:
https://developer.mozilla.org/en-US/docs/Web/CSS
The Web Developer Bootcamp 2022 by Colt Steele

Day 4: https://dev.to/jennifer_tieu/self-taught-developer-journey-day-4-59pa
Please refer to [Starting My Self-Taught Developer Journey]( https://dev.to/jennifer_tieu/starting-my-self-taught-developer-journey-2dga) for context.
Things I Learned About Python this Week
Published: 2021-11-27 03:02:38

```python manage.py shell```
this gets you into an interactive shell
```
from basic_loans.models import BasicLoan DOES NOT WORK
from dyor_com_app.basic_loans.models import BasicLoanPage
b=BasicLoanPage
from dyor_com_app.base.models import People
p = People
p.first="matt"
p.last="dyor"
bl1 = BasicLoan.objects.filter(id=1).first()
```
which is the same as: 
```
bl1 = BasicLoan.objects.get(id=1)
bl1.loan_amount
```
create a record
```
BL = BasicLoan()
BL.loan_amount
BL.original = bl1
```
import datetime
```
BL.loan_start_date = datetime.date(2021, 11, 25)
BL.save()
```
create an object with inline properties
```
page = Page.objects.create(title='my title', summary='my summary')
page.__dict__
```
Day 21 of #100daysofcode: Your code will haunt you
Tags: 100daysofcode, react, python, beginners
Published: 2021-11-27 02:59:29

I hope everyone has had a great holiday so far.

One of my mentors really liked the phrase "Your code will haunt you" and I thought it was really memorable. It was kind of a mantra to make sure the code you were writing was code you wanted to look at and maintain. I have been tying things together in this project with toothpicks and hot glue, and it's really starting to feel messy. My code is indeed starting to haunt me.

State in my project has turned into a giant web of mistakes. Now that I have learned so much, I feel it might be faster to start over from the very beginning than to continue working on my mistakes, but I will bear through. I'm considering drawing out the state I have so far so I can get a better visual to try and fix it. I have learned a lot, but I still need to test a couple things to really be sure I understand some of the nuances of state inheritance.

Today was spent trying to fix broken things by (unfortunately) breaking them further. I really got lost in the weeds today and I'm hoping tomorrow has a better solution in store for me. 

## Today
I once again want to apologize, I will not be sharing details of the struggles in my group project. That is taking up nearly all of my time at the moment, and a portion of the remaining time is being spent on studying for finals. The spare time I am spending on my #100daysofcode challenge is currently being spent on tutorials and reading more about Django! 
* Dove straight into school project
* Worked through the rest of the FreeCodeCamp Regex tutorials (yay!)
* Read a bit about Django, (started this series! [Understand Django](https://dev.to/mblayman/from-browser-to-django-j0l) by Matt Layman. Very well written, I really recommend it!

## Upcoming
* **Finals and final project sprints**: Not much time left!
* Continue reading about Django, 
* Iron out details regarding the Study Aid app (I really need to name this thing) -- May work on this this weekend
  * Flask vs Django - This is still an ongoing discussion. I received some good advice to stick with what I know in Flask, however I am still considering diving into Django, as I will have free time soon. Diving in headfirst has always been my favorite way to learn, however it is often not efficient!
  * Should I change how I deploy? Should Docker get in the picture?
  * Are there any other systems I should think about using as a part of this project?
* Learn more about Material UI, I will probably use Material UI a little bit in my (ongoing) school project. 
* Start the Study Aid app!
* Later in the challenge: AWS Deployment, AWS Certification, and Using Docker!?

Have a great, long weekend everybody, stay safe!

### Resources
[JS Course - FreeCodeCamp](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/)
[Material UI](https://mui.com)
[Regex Tutorial - FreeCodeCamp](https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures#regular-expressions)
[Understand Django - Matt Layman](https://dev.to/mblayman/from-browser-to-django-j0l)
HTML5 Canvas - conceitos básicos
Tags: braziliandevs, javascript, canvas, ptbr
Published: 2021-11-27 02:22:56

Olá você que me lê. 

Esse vai ser o primeiro post de uma série sobre canvas do zero, basedo em livros, videos, posts e testes.

A cada conceito interessante ou importante, será escrito um post.

Como primeiro post vamos falar um pouco do que é o canvas e conceitos importantes para domina-lo.

**O que é HTML5 Canvas?**

Canvas é uma tag do HTML5 usada para definir um quadro de desenho gráfico 2D ou 3D, para fazer eses desenhos é necessario o uso do JavaScript, ou seja a tag canvas no HTML5 só reserva o espaço assim como outras tags.

É possivel ultilizar atributos globais nesta tag, como ID, Class, Style e por ai vai.

A tag canvas é escrita: <canvas></canvas>

Contendo uma abertura e um fechamento.

Qual a vantagem de usar canvas sendo que posso desenhar com svg ou css?

Sendo o canvas um elemento dedicado para renderização de vários frames por segundo(fps), este tem a vantagem de ser mais performático do que outras formas de animação e interação gráficas dentro de projetos, não perdemos qualidade e nos dá a posibilidade criar animações, jogos e interações mais complexas.

**Conceitos básicos**

Cada conceito será melhor explicado com um post dedicado, abaixo está uma visão geral sobre o que precisamos aprender para dominar o canvas.

1- Criar e Mudar o tamanho do canvas

2- Desenhar elementos no canvas

3- Animar elementos no canvas

4- Interagir com os elementos do canvas

A partir do ponto que conseguirmos fazer esses quatro passos sem dificuldade é possivel criar jogos , animações e elementos interativos em nossos projetos web.

meu objetivo é começar por esse ponto e explorar todas as possibilidades que o JavaScript pode nos oferecer, essa linguagem tão estranha e tão maravilhosa ao mesmo tempo.

Obrigado por ler, duvidas sugestões ou criticas, aqui em baixo nos comentários ou por email. Terei o prazer em responder.

Referências:

Video -> [Chris course](https://www.youtube.com/watch?v=EO6OkltgudE&list=PLpPnRKq7eNW3We9VdCfx9fprhqXHwTPXL)

Livro -> [Desenvolva jogos com HTML5 Canvas e JavaScript](https://amzn.to/3AgwfAM)