teleren/devto huggingface dataset:
Bevy Minesweeper: WASM build
Tags: rust, gamedev, tutorial, bevy
Published: 2022-02-21 15:29:15

> [Check the repository](https://gitlab.com/qonfucius/minesweeper-tutorial)

Let's make our project run on browser:

Let's change our `board_plugin/Cargo.toml`:

```diff
[dependencies]
- # Engine
- bevy = "0.6"

# Serialization
serde = "1.0"

# Random
rand = "0.8"

# Console Debug
colored = { version = "2.0", optional = true }
# Hierarchy inspector debug
bevy-inspector-egui = { version = "0.8", optional = true }

+ # Engine
+ [dependencies.bevy]
+ version = "0.6"
+ default-features = false
+ features = ["render"]

+ # Dependencies for WASM only
+ [target.'cfg(target_arch = "wasm32")'.dependencies.getrandom]
+ version="0.2"
+ features=["js"]
```
We only need one feature of the `bevy` dependency so we improve its declaration, and we add a new dependency only for `wasm` targets which improves `rand` on browser.

Now we edit the main `Cargo.toml`:

```diff
[dependencies]
- bevy = "0.6"
board_plugin = { path = "board_plugin" }

# Hierarchy inspector debug
bevy-inspector-egui = { version = "0.8", optional = true }


+ [dependencies.bevy]
+ version = "0.6"
+ default-features = false
+ features = ["render", "bevy_winit", "png"]

+ # Dependencies for native only.
+ [target.'cfg(not(target_arch = "wasm32"))'.dependencies.bevy]
+ version = "0.6"
+ default-features = false
+ features = ["x11"]

[workspace]
members = [
    "board_plugin"
]
```

We can also disable the default features of `bevy` and only enable the useful ones. We add the `x11` feature only for native use to avoid compilation issue for web assembly.

And.. That's it ! The app can now compile and run natively on wasm.

Let's improve a bit by adding a cargo config in `.cargo/config.toml`:

```toml
[target.wasm32-unknown-unknown]
runner = "wasm-server-runner"

[alias]
serve = "run --target wasm32-unknown-unknown"
```

Then install the runner:
`cargo install wasm-server-runner`

you may now directly execute `cargo serve` and test your app on your browser !
You may also try the [live version](https://qonfucius.gitlab.io/minesweeper-tutorial/)

---

[Previous Chapter](https://dev.to/qongzi/bevy-minesweeper-part-10-5hie)

---
Author: Félix de Maneville
Follow me on [Twitter](https://twitter.com/ManevilleF)

> Published by [Qongzi](https://qongzi.com)
Bevy Minesweeper: Safe Start
Tags: rust, gamedev, tutorial, bevy
Published: 2022-02-21 15:28:06

> [Check the repository](https://gitlab.com/qonfucius/minesweeper-tutorial)

We can uncover tiles, but a good minesweeper should provide a *safe start* uncovered zone.
Let's activate the `BoardOptions` parameter in our `main.rs`:

```diff
// main.rs
// ..
    .insert_resource(BoardOptions {
        // ..
+        safe_start: true,
        // ..
    }
// ..
```

This option does nothing now, we need to implement it in our `board_plugin`.
We want to find an *empty* tile and schedule its tile cover for uncovering, since we already have uncovering *systems* we will just insert a `Uncover` component on it.

We need to retrieve the current `covered_tile_entity` to be able to uncover it.
Since we want only one *safe start* we will add yet again a new argument for our `spawn_tiles` function.

> Clippy already says it has too many already !

We will refactor it on part 9, let's get this working:

```diff
// lib.rs
// ..
fn spawn_tiles(
        // ..
+        safe_start_entity: &mut Option<Entity>,
    ) {
        // ..
        covered_tiles.insert(coordinates, entity);
+       if safe_start_entity.is_none() && *tile == Tile::Empty {
+         *safe_start_entity = Some(entity);
+       }
}
```

And now we change our `setup_board` startup system accordingly:

```diff
// lib.rs
// ..
+ let mut safe_start = None;
commands
     .spawn()
     .insert(Name::new("Board"))
// ..
Self::spawn_tiles(
    //..
+     &mut safe_start,
);
// ..
+ if options.safe_start {
+    if let Some(entity) = safe_start {
+        commands.entity(entity).insert(Uncover);
+    }
+ }
// ..
```

And that's it ! if we run our app, it will uncover a safe area !

![Safe Start](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wht9broyf8tvdnzi3bqt.png)

*We get a pre-uncovered area*

---

[Previous Chapter](https://dev.to/qongzi/bevy-minesweeper-part-6-46jh) -- [Next Chapter](https://dev.to/qongzi/bevy-minesweeper-part-8-4apn)

---
Author: Félix de Maneville
Follow me on [Twitter](https://twitter.com/ManevilleF)

> Published by [Qongzi](https://qongzi.com)
LeetCode: Majority Element (Boyer-Moore Majority Voting Algorithm)
Tags: java, algorithms, beginners, programming
Published: 2022-02-21 15:20:39

Given an array nums of size n, return the majority element.

The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume that the majority element always exists in the array.

Example 1:
Input: nums = [3,2,3]
Output: 3

Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2

This is a **EASY LEVEL** question but it is very important.
It can easily be solved using two or three technics. But the main algorithm that we'll learn while solving it is **Boyer-Moore Majority Voting Algorithm**

To solve the question click here:(https://leetcode.com/problems/majority-element/)

> The <u>Boyer-Moore voting algorithm</u> is one of the popular optimal algorithms which is used to find the majority element among the given elements that have more than N/ 2 occurrences. This works perfectly fine for finding the majority element which takes 2 traversals over the given elements, which works in O(N) time complexity and O(1) space complexity.

**Approaches-**
(1) **Nested for-loop :**
_Time Complexity: O(N^2)_
_Space Complexity: O(1)_

**JAVA CODE:**
```
public static int majorityElement(int[] nums) {
      
        int n=nums.length;
        int max=0,ele=nums[0];
        for(int i=0;i<nums.length;i++)
        {
            int count=0;
            for(int j=i;j<nums.length;j++)
            {
                if(nums[i]==nums[j])
                    count++;
            }
            if(count>max)
            {
                max=count;
                ele=nums[i];
            }
        }
        if(max>=(int)(n/2))
            return ele;
        
        return -1;
    }
```

(2) **Sorting:**
_Time Complexity: O(NlogN)_
_Space Complexity: O(1)_

**JAVA CODE:**
```
public static int majorityElement_m2(int nums[])
    {
            Arrays.sort(nums);
            return nums[nums.length/2];
    }
```

(3) **HashMap:**
_Time Complexity: O(N)_
_Space Complexity: O(N)_

**JAVA CODE**
```
public static int majorityElement_m3(int[] nums) {
        
        HashMap<Integer,Integer> hm=new HashMap<>();
        
        for(int i=0;i<nums.length;i++)
        {
            if(hm.containsKey(nums[i]))
                hm.put(nums[i] , hm.get(nums[i])+1);
            else
                hm.put(nums[i],1);
        }
        int answer =0;
     for (Map.Entry<Integer, Integer> entry : hm.entrySet())
     {
         if(entry.getValue()>nums.length/2)
         {
             answer = entry.getKey();
         }
     }
    return answer;
    }
```
(4)**Boyer-Moore Majority Voting Algorithm:**
_Time Complexity: O(N)_
_Space Complexity: O(1)_

**JAVA CODE**
```
public static int majorityElement_m4(int[] nums) {
        int ans=nums[0];
        int count=1;
        for(int i=1;i<nums.length;i++)
        {
                if(nums[i]==ans)
                    count++;
                else
                    count--;
            
        if(count==0)
        {
             ans=nums[i];
            count=1; 
        }
          
        }
        return ans;
        
    }
```
An ESP32 walks into a bar - Jokes web API MicroPython tutorial
Tags: micropython, beginners, tutorial, python
Published: 2022-02-21 15:15:47

_Originally posted [here](https://bhave.sh/micropython-urequests/)_

_(If this is your first time here, check out my first MicroPython tutorial. Use it to get acquainted with the Wokwi simulator so that you are prepared to dive into this tutorial)_

This week, our MicroPython tutorial flies away and connects to the web to fetch data from an API! While filming it, I ran into a temporary issue with the Wokwi simulator (thankfully it's fixed now, they were quick 🙂) so I ported the code to an actual ESP32 to continue the tutorial. Crisis averted, whew! What we can learn from this experience is that Wokwi is actually a perfect prototyping tool because I had to make zero changes to the code for it to work on real hardware. Amazing!

Hope you enjoy, and click follow down below and on my [YouTube channel](https://youtu.be/73RvDEKb_U4) to get notified when new tutorials are out! I release them about once a week. As always, if you have questions or just wanna chat, hit me up here or on [Twitter](https://twitter.com/beyond_sol)!

{% youtube https://www.youtube.com/watch?v=73RvDEKb_U4 %}
Creating Unique IDs programmatically on DynamoDB
Tags: aws, serverless, python, database
Published: 2022-02-21 15:08:14

**Create a DynamoDB Table**

![DynamoDB Table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bndm3dwsyn4nvd6tt7m0.png)

Leave the Partition Key Set To String, this way it will be easier to create Unique Ids Identifiers because **unlike MySQL Databases DynamoDB will not generate an auto increment ID**. Furthermore, if we select Number or Binaries, there will be a conflict between DynamoDB and the 
uuid library because they respectively use different decimal calculation.

Go to the Terminal and create an uuid

![Terminal UUID](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vu90lvuipybuagpeueq2.png)

Copy and paste the uuid, and create the item on the table

![Item](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k6b6l16s1wmxr0sxmxcp.png)

**Create a put_dynamodb function**


![put_dynamodb Lambda function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clfjhph1c0f9302evu69.png)

Go to Configuration Permissions, Click on the Role Name and Attach the DynamoDbFullAccess policy to this Role


![Role Lambda](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fxwd5yjhjscve952aay.png)

![Attach Dynamodb Policy To Lambda Role](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vst1kbmmlfyd0zplsbqi.png)

**First check if we can retrieve the data**

```
import json
import uuid
import boto3

db = boto3.client('dynamodb')


def lambda_handler(event, context):
    data = db.scan(TableName='database')
    return {
        'statusCode': 200,
        'body': json.dumps('Success')
    }
```
Let's test the function

![Test function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/woxpti2dcpiye5y5rbo3.png)

Now, let's add a new item and an auto generated id with uuid module, and test the function
```
import json
import uuid
import boto3

db = boto3.client('dynamodb')
id_db=uuid.uuid4()


def lambda_handler(event, context):
    data= db.put_item(TableName='database', Item={'id':{'S':str(id_db)},'item':{'S':'iphone-10'},'available':{'BOOL': False}})
    return {
        'statusCode': 200,
        'body': json.dumps('Success')
    }
```

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

Let's write the exact same code except that we are going to add a color attribute.

```
import json
import uuid
import boto3

db = boto3.client('dynamodb')
id_db=uuid.uuid4()


def lambda_handler(event, context):
    data= db.put_item(TableName='database', Item={'id':{'S':str(id_db)},'item':{'S':'iphone-10'},'available':{'BOOL': False},'color':{'S':'pink'}})
    return {
        'statusCode': 200,
        'body': json.dumps('Success')
    }

```


**Now let's check our database**

![DynamoDb updated](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6nhqj0yz7zw1mumo3jz0.png)

As you can see we haven't entered any id manually, and they have been generated programmatically.
Revive files from the dead with git
Tags: git, cli
Published: 2022-02-21 14:38:21

---
canonical_url: https://waylonwalker.com/til/git-revive-dead-files/
published: true
tags:
- git
- cli
series: til
title: Revive files from the dead with git
---

Git reflog can perform some serious magic in reviving your hard work from the dead if you happen to loose it.

## caveat

You must git commit!  If you never commit the file, git cannot help you. You might look into your trashcan, filesystem versions, onedrive, box, dropbox. If you have none of this, then you are probably hosed.

## practice

I really like to practice these techniques before I need to use them so that I understand how they work in a low stakes fashion.  This helps me understand what I can and cannot do, and how to do it in a place that does not matter in any way at all.

This is what I did to revive a dropped `docker-compose.yml` file.  The idea is that if I can find the commit hash, I can `cherry-pick` it.

``` bash
git init touch readme.md git add readme.md git commit -m "add readme" touch docker-compose.yml git add docker-compose.yml git commit -m "add docker-compose" git reset 3cfc --hard git reflog
# copy the hash of the commit with my docker-compose commit
git cherry-pick fd74df3
```

## reflog

Here was the final reflog that shows all of my git actions.  **note** I did reset twice.

``` bash
❯ git reflog --name-only
0404b6a (HEAD -> main) HEAD@{0}: cherry-pick: add docker-compose
docker-compose.yml
3cfcab9 HEAD@{1}: reset: moving to 3cfc
readme.md
9175695 HEAD@{2}: cherry-pick: add docker-compose
docker-compose.yml
3cfcab9 HEAD@{3}: reset: moving to 3cfc
readme.md fd74df3 HEAD@{4}: commit: add docker-compose docker-compose.yml
3cfcab9 HEAD@{5}: reset: moving to HEAD
readme.md
3cfcab9 HEAD@{6}: commit (initial): add readme
readme.md
```

## Discuss

What's your favorite way to get out of git trouble.  I need to learn more about how to unf*** a git repo.
Python Program to Check Leap Year
Tags: python, programming, calender
Published: 2022-02-21 14:33:15

##**Introduction**
Sometimes it is hard to tell if a year is a leap year or not, especially the years back in 1900-1999 right!

Have you ever thought how to check if a year is a leap year using Python?

Before we get our hands on coding check out [this article](https://dev.to/oderofrancis/introduction-to-modern-python-95n) to get more basic information on Python.

**Let's dive in coding**

We shall create a program to check leap year
There are two ways:

1. using calender module.
2. Using operators.

**1. Using calender module**

For this is the simplest as one just have to import calender and use `calender.isleap()` as shown below :

```
import calendar

year = int(input("Enter the year : "))

print(calendar.isleap(year))
```

The year entered is translated to True or False if the year is leap year or not respectively.

**2. Using operators**

This method we have to define our procedure on how to check whether a year is a leap or not.
First we have to get year from the user . Divide by 100 which means century year and divide also divide by 400.
if not divided by 100 means not a century year but year divided by 4 is a leap year.
A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400.

As shown below:


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

Some of the output:

```
Enter a year : 2030
2030 is not a leap year

Enter a year : 2000
2000 is a leap year

Enter a year : 1900
1900 is not a leap year

Enter a year : 1904
1904 is a leap year
```

Now you know on how to check if a year is a leap year using two ways. Thank you for reading this article.

KEEP ON MOVING 👣👣👣👣
Activating your OpenSSH Authentication Agent in Windows 10
Tags: windows10, opensource, godmode, services
Published: 2022-02-21 14:29:14

## OpenSSH Authentication Agent

How to check to see if your **OpenSSH Authentication Agent** is active or disabled.

- Open your Windows 10 PowerShell (user mode)
- Type `Get-Service ssh-agent` in your PowerShell Terminal

You should see this if it's Active/Running:

`Status   Name               DisplayName`
`------   ----               -----------`
`Running  ssh-agent          OpenSSH Authentication Agent`

If it disabled, off or stopped and you want to turn it back on or activate it, follow the steps below.

---

## Activate your OpenSSH Authentication Agent

- Hit the **WINDOWS KEY**
- Type `services.msc or services` it will be under Apps and press **ENTER**
- Scroll down and look for OpenSSH Authentication Agent
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2iw40ok4r328212w5wmx.jpg)

- Make sure both of those services are on Automatic

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

If they are not, make sure each one is set to Automatic individually.

- Right click over `OpenSSH Authentication Agent`
- Click on `Properties`

- Right click over `OpenSSH SSH Server`
- Click on `Properties`

![Services.MSC Window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ty87x4bbd1aafojd3efx.png)

![Services.MSC Window](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zcw0ve42ph8wh95qajl.png)


Once you set both to Automatic:

- `OpenSSH Authentication Agent` 
- `OpenSSH SSH Server`

Finally:

- Hit **APPLY **and **OK**
- Close all your open windows
- Reboot

---


I hope this helps you out! Reach out to me if you have any other questions or need help with a problem you cant solve on your own.

J
How to make your computer to speak using python
Tags: python, webdev, productivity, showdev
Published: 2022-02-21 14:26:34

Hello!friends i created a python speaker so i decided share the code with you.It is awesome you can use it in your future python projects.It was easy to do that .Main step is to install pyttsx3 python library to install it use this command "pip install pyttsx3" and copy code from my github-https://github.com/sripadhs/Python_speaker
4 formas de convertir strings a numbers en JavaScript
Tags: javascript, webdev, spanish, beginners
Published: 2022-02-21 14:23:13

## 1. **Objeto Number**

```js
console.log(typeof(Number("25"))); //number
```

## 2. **parseInt**##

```js
console.log(typeof(parseInt("25",10))); //number
```

## 3. **Operador +**##

```js
console.log(typeof(+"25")); //number
```

## 4. **Hack: restando 0**##

```js
console.log(typeof("25" - 0)); //number
```

Todos los ejemplos solo funcionan con cadenas validas, si intentamos convertir cadenas no validas obtendremos en todos los casos un `NaN`:

```js
console.log(Number("25xw")); //NaN
console.log(parseInt("rr25", 10)); //NaN
console.log(+"25ccs"); //NaN
console.log("25EE" - 0); //NaN
```

---

## **Conclusiones**
Para llegar a Roma existe más de un camino.
WordPress is Underrated.
Tags: wordpress, opensource, productivity, php
Published: 2022-02-21 13:04:38

WordPress is a free and open-source CMS written in PHP, Initially released in 2003.

I have worked on more than 50 WordPress projects, and find it really easy to get started, especially if you're a small organization or can’t afford the proper development time of creating an application from scratch. 

I don't understand why people hate WordPress so much. Few devs advise others to leave the WordPress website as it is not scalable, and has security issues (You are not suppose to use nulled plugins or theme).

People want to build their application on React in the influence that it is the only way to make it fast, and for that they have to adapt a latest framework on Python or Node.js or PHP, but Why do they want to redevelop the backend when It is available in WordPress by default?

My point here is not that WordPress is best and everyone should use it, but don't switch from WordPress under the impression that it is not scalable. especially when you already have an application built on WordPress, and you can totally have a Frontend on React or Next.js and Backend or admin panel on WordPress.

WordPress has functionality of REST api by Default no matter what kind of application you have, you can create its rest api endpoint, Also there are great plugins which can help you to have GraphQL endpoints and your frontend can be any JS framework.

Following are a few of my favorite open source git repo for headless wordpress, built on latest frameworks

[WordPress React](https://github.com/imranhsayed/react-with-wordpress)
[WooCommerce with Next.js](https://github.com/imranhsayed/woo-next)
[WordPress blog with Next](https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress)

Here I am not promoting it, Just want to understand if there is a real need to switch backend as well? when these features are available in WordPress and even easier to develop it.
My Shortcut / Alias to Use Civo Kubernetes
Tags: civo, kubernetes, linux, cloud
Published: 2022-02-21 14:17:50

Hi gangs, today I will share about my alias setup for Civo Cloud.

```
alias civo_create="civo kubernetes create kube-demo --wait && rm ~/.kube/config && civo kubernetes config kube-demo --save"
```
This first alias is for provision new kubernetes cluster(kube-demo) with basic configuration, and I also remove kube config file for easily replace new config with the new one.
```
alias civo_remove="civo kubernetes remove kube-demo"
```
This alias is for removing cluster when I finish my learning / project. Let's we try this alias
```
civo_create
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0lsfzuu2nv7a5fvrsgz.png)
As you can see, I just issue command `civo_create` and cluster created in just **1 minute 58 sec**, How cool is that!

Now Let's remove our cluster
```
civo_remove
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwemov7um1v64vivpon7.png)
Just like that, then we say good bye to our cluster :)
Paracetamol.js💊| #60: Explica este código JavaScript
Tags: javascript, spanish, beginners, webdev
Published: 2022-02-21 14:13:52

## **Explica este código JavaScript**

```js
const colorConfig = {
  red: true,
  blue: false,
  green: true,
  black: true,
  yellow: false,
}

const colors = ["pink", "red", "blue"]

console.log(colorConfig.colors[1])
```

-     A: `true`
-     B: `false`
-     C: `undefined`
-     D: `TypeError`

Respuesta en el primer comentario.

---
The advantages of IDE integrated documentation
Tags: productivity, webdev, documentation
Published: 2022-02-21 14:07:58


![what if I told you context switching was killing your productivity](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mel0o16d2rxoiy2okgsa.png)
[Image source
](https://static.wixstatic.com/media/cfb56d_d2a07791051e4c0c9458ec694bc293e7~mv2.jpg/v1/fit/w_1000%2Ch_831%2Cal_c%2Cq_80/file.jpg)

Integrating documentation inside the IDE is a convenient method for documentation management. I don't know about you, but I avoid context switching at all costs. I just know how fast I can break my focus. 

The easiest way for me to document my code is right in my IDE. Here are three advantage: 

1. It reduces context switching. When I'm looking at code and I want to understand something about it, the documentation is right there. I don't need to leave my IDE and search for info. 
2. I see which parts of the code have been already documented while I'm reading and I make a note to come back later and fill in the blanks. 
3. Reviewing annotations when implementing new code or trying to understand a part of the code- it's more straightforward, easier to review, and just intuitive.

Have you tried [IDE-integrated documentation](https://swimm.io/blog/ide-integrated-documentation-using-swimm/)?
Contributing To Open Source - 10 Ways Developers Make Money Coding Course - E10
Tags: career, javascript, tutorial, leadership
Published: 2022-02-21 13:54:09

As a web developer, you have the opportunity to contribute to open-source projects. You can contribute by fixing bugs or implementing features. It's is a great way to get involved with the community and make new connections. In this video series, I share the best ways and how to increase your money income as a web developer while working from home.
📽️ Video here -  https://youtu.be/Ni6Jlkj4Xuo
👉 Subscribe to Dan Later -  https://bit.ly/31SdiZv