teleren/devto huggingface dataset:
α/β Pruning
Tags: ai, programming
Published: 2022-07-27 19:40:17

_This post is meant to prepare me for my next project, a chess AI._

## Weights
Humans are very different from computers. What we lack in raw processing power, we make up for intuition. Computers are the very opposite. With no intuition or subconscious, everything is either explicit or calculated. Modern AI uses weights from explicit rules to train a neural net. This is some imitation of intuition. I will attempt to use this method to quickly determine if a move is good or bad.
See [Weight In Uncertainty](https://www.deepmind.com/publications/weight-uncertainty-in-neural-networks) 


## Challenge
The challenge of a modern chess AI is complex in many different aspects. The framework you begin with defines how effective the program may perform, not just from a time-space-complexity standpoint, but also from a competitive perspective.

### The premise:

#### Teach an AI: 

  How the pieces move,
  How to take other pieces,
  Where the pieces are the most valuable,
  How to open,  *more on this later*
  How to checkmate,
  How to determine if a move is good or bad.

### Q:
1. What data structures are required? 
2. How do we reduce big(O)?
3. How do we quickly evaluate a move? 
4. How do we find the best move set?
5. What makes a good move?

This final objective is clearly the most difficult to accomplish and the reason for this blog. First, what makes a move "good"? 

The entire premise of chess is to move your pieces in a way that gives you a checkmate against your opponent. The best way to think of this is through position. The "position" is the way the pieces are arranged. If you have the better position you will win. 

### 3,5: So if a move improves our position, it is good.

To evaluate a position we must create rules and weights based on the first five objectives: How the pieces move, how to capture pieces, where they are the most valuable, how to open like a pro, and how checkmate is possible.
#### A position is evaluated on these five weights.

### The Problem

Now we just have to evaluate every possible position with these weights, ~10^100... That's a one with 100 zeros.
How about the first six moves? After some math, it's about 9,132,484 distinct positions. What gives we can even see a few moves ahead without some insane number of positions. Most games of chess last at least 20 moves, some even in the hundreds. How can we reduce the number of positions to evaluate without a major loss of competitive potential? 

## 1,2,4 The Solution 

### α/β Pruning

This gives us the answer to questions 1 and 2. What is alpha-beta pruning? α/β Pruning is a search algorithm that reduces the number of nodes on a tree based on some explicit or evaluated rules. Say you generate a layer of nodes on a tree with values 1-10. The pruning then removes any node with a value of less than 3. This removes 1/3 of nodes and your next layer is 1/3 * children smaller. If half of all chess moves are objectively bad the problem becomes more linear instead of some runaway value of 10^100 moves. 

Thanks for reading and have a wonderful day.
[Video] Outbox meets change data capture - hooking into the Write-Ahead Log (feat. .NET, PostgreSQL & Kafka)
Tags: dotnet, microservices
Published: 2022-07-27 18:53:56

---
title: [Video] Outbox meets change data capture - hooking into the Write-Ahead Log (feat. .NET, PostgreSQL & Kafka)
published: true
date: 2022-07-27 18:45:00 UTC
tags: dotnet, microservices
canonical_url: https://blog.codingmilitia.com/2022/07/27/outbox-meets-change-data-capture-hooking-into-the-write-ahead-log/
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6zmydcnb3felwefudrs.png
---

Hey folks! 👋

📢📽️ New one sent right into the tubes!

Another video on using change data capture (often referred to as CDC), to hook up into the database transaction log, forwarding incoming entries to the outbox table.

Previously, we used Debezium for this, but I was left wondering, what if I want to implement something similar with .NET? Turns out it's not super hard, with the help of Npgsql, which provides us with APIs to hook into PostgreSQL Write Ahead Log, so we can read the incoming outbox messages and forward them to Kafka.

{% youtube 4rnSzEd9jPI  %}

Here are a couple of related links:

- [Sample implementation](https://github.com/joaofbantunes/PostgresChangeDataCaptureOutboxSample)
- [Intro to the transactional outbox pattern](https://youtu.be/suKSJ5DvynA)
- [Outbox meets change data capture (feat. .NET, PostgreSQL, Kafka and Debezium)](https://youtu.be/WcmLvoxs9ps)
- [PostgreSQL Write-Ahead Logging (WAL)](https://www.postgresql.org/docs/current/wal-intro.html)
- [Npgsql Logical and Physical Replication](https://www.npgsql.org/doc/replication.html)

Thanks for stopping by, cyaz! 👋
Best Time to Buy and Sell Stock
Tags: java, dart, tutorial, algorithms
Published: 2022-07-27 18:23:23

Today lets see one of the basic array problem,

for Best Time to Buy and Sell Stock problem we need to find best day to buy (low price ) and the best day to sell (high price) so we get maximum profit 

The rule is simple we can't sell without buying, i.e sell should be after buying 

lets solve this using both java and dart 


>Java

```
public class StockBuyAndSell {
  public static void main(String[] args) {
    int[] prices = new int[] {7, 1, 5, 3, 6, 4};
    int rightIndex=0;
    int min = Integer.MAX_VALUE;
    int maxProfit = 0;
    while(rightIndex<prices.length){
        if(prices[rightIndex]<min){
            min=prices[rightIndex];
        }
        maxProfit = Math.max(maxProfit,prices[rightIndex]-min);
        rightIndex++;
    }
    System.out.println(maxProfit);
  }
}
```
here we have the stock price list `int[] prices = new int[] {7, 1, 5, 3, 6, 4};`

lets create an pointer `int rightIndex=0`, lets create a `min` with `Integer.MAX_VALUE` and `maxProfit` with zero

we are going to iterate the array from the first to last(for loop ,while loop anything is fine), the idea behind this is we need to find the min value in the array and then we will find the difference between the min and current element, and we used `Math.Max()` to find whether current difference is maximum profit or the previous one and at last we print the maxProfit 

>Dart

```
 import 'dart:math';
  void main(){
    List<int> price = [7,1,5,3,6,4];
    int min=double.maxFinite.toInt();
    int maxProfit=0;
    for(int i=0;i<price.length;i++){
      if(min>price[i]){
        min=price[i];
      }
      maxProfit = max(maxProfit, price[i]-min);
    }
    print(maxProfit);
  }
```
In Dart we don't have min and max values for int so we used double and converted to int 


Time Complexity:- O(n)
Auxiliary Complexity:- O(1)
How to install exa in Ubuntu
Published: 2022-06-30 00:57:48

**exa** is a great comman-line tool for file-listing.
It is a modern replacement of **ls**

## Installation in Ubuntu
By executing the following 3 commands, you can easily install **exa** in your Ubuntu environment ([reference](https://ourcodeworld.com/articles/read/832/how-to-install-and-use-exa-a-modern-replacement-for-the-ls-command-in-ubuntu-16-04)).
```
# Till the date of publication of this article, the latest available download version is the 0.8.0
wget -c https://github.com/ogham/exa/releases/download/v0.8.0/exa-linux-x86_64-0.8.0.zip
unzip exa-linux-x86_64-0.8.0.zip
Copy snippet
# Move the unziped binary with the name "exa-linux-x86_64" to "/usr/local/bin/" with the exa name
sudo mv exa-linux-x86_64 /usr/local/bin/exa
```

## But cannot use --icons
**exa** has cool options. `--tree`, `--g`, etc. `--icons` options is one of those options. But, I could not use `--icons` option, if installed **exa** by following above steps.

To use `--icons` option, you need build from source codes.

```
git clone https://github.com/ogham/exa.git
cd exa.git
cargo build --release
cp exa ~/.cargo/bin/
```
## `exa --tree --level=2 -l -g  --icons`

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

## Why building from source codes?
I tried `cargo install exa`, but failed compiling. Compiling from source codes solved failure of cargo installation.
My Course on Angular Getting Started
Tags: angular, learning, webdev, course
Published: 2022-07-27 18:17:00

Photo by <a href="https://unsplash.com/@nickmorrison?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Nick Morrison</a> on <a href="https://unsplash.com/s/photos/course?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
  

I had planned an Angular Course for the community for a very long time, last year I even decided to stream it. But all efforts were unsuccessful.

There was too much in my plate, I decided to move to a new country, which caused lot of changes in my plan.

## New Plan

I decided to publish it around May again, but due to other factors and depression. I decided to put it on hold again. The plan was to publish it as paid course, but with pay what you want model.

## Finally Publishing It

I decided to leave my job in the mid July, which gave me some free time. I decided to utilize this free time and publish the course.

## Why this course is Free

Lot of people may have this question why free, when I had decided to make it paid.

There is one reason - **community**, Last 7 months were really rough for me, staying away from your loved ones is hard, specially when they are stuck in different country and you can not visit them.

During this time, I got so much support from community, I decided to do something in return.

This is my small way to say think you for everything you all have done for me.

## Where to get this course

You can access it on YouTube 

{% embed https://youtu.be/3qBXWUpoPHo %}


## What if you want to pay

This course will remain free forever, but if you decide to support my work, so I can invest more time creating content for community, you can use GitHub Sponsors link below:

https://github.com/sponsors/santoshyadavdev

Finally thanks to some amazing folks for sponsoring me:

* Chau Tran - https://twitter.com/Nartc1410
* Anand Chowdhary - https://twitter.com/AnandChowdhary
* Sunil - https://twitter.com/sunil_designer
* Trung Vo - https://twitter.com/tuantrungvo
* Umair Hafeez - https://twitter.com/_UmairHafeez_
* Pavan Kumar Jadda - https://twitter.com/pavankjadda
* Pabio - https://twitter.com/PabioHQ
* Maarten Tibau - https://twitter.com/maartentibau
AWS Local Serverless Environment Setup using AWS SAM
Published: 2022-07-27 18:10:01

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

This post is intended to list the steps for setting up your local development environment for creating serverless applications using the AWS SAM CLI.

I will list below all the pre-requisites that you need to have installed in your local machine:

- **A valid AWS Account** —To build and deploy our serverless function to the AWS Lambda, so you must have a valid AWS account. If you are new and do not have an account yet, you can navigate to http://console.aws.amazon.com/ and signup for a new account

- **Python** — My example is developed in Python so i will recommend you to install Python if you want to use my code. You can download the latest version of python by visiting https://www.python.org/downloads/ and install the same based on the operating system you are using. It is important to mention that you can build your serverless functions with any language of your choice. There are quite a few languages supported by AWS Lambda, like Python, C#, Ruby, NodeJS, etc.

- **AWS CLI** — In addition to building the serverless apps locally, we will also need to access the AWS services programmatically. This can be achieved by installing the AWS CLI or the command-line interface, using which you can perform many administrative activities on your AWS Account.

- **AWS SAM CLI** — In order to develop and test the applications locally, you need to install the AWS SAM CLI on your machine. The AWS SAM CLI will provide an AWS Lambda like execution environment using which you can run your code locally and get the output

- **Docker** — Finally, you also need to get Docker installed on your machine if you want to test the application locally. The AWS SAM CLI will use Docker to mount an image where the execution will be performed. You can install Docker by visiting https://docs.docker.com/desktop/

- **Visual Studio Code** — For developing the code, we are going to use the Visual Studio Code as the editor. You can download this from http://code.visualstudio.com/
Once you have installed all the pre-requisites on your machine, you can check the installed versions by running the following commands.

`Python — python –version
AWS CLI — aws –version
AWS SAM CLI — sam –version
Docker — Docker –version`

![versions](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjviqw80g2sgfu950x5e.png)
 
**I hope the content is useful for everyone. Thanks a lot!
Cheers!**

Cristian Carballo
cristian.carballo3@gmail.com
Paracetamol.js💊| #178: Explica este código JavaScript
Tags: javascript, webdev, spanish, programming
Published: 2022-07-27 18:02:00

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
if (true) {
  const y = 5;
  y = 6; // no puede ser re-asignada (para primitivos)
  const y = 7; // no puede ser re-declarada
  console.log(y);
}
```

A. `7`
B. `6`
C. `SyntaxError: Identifier 'y' has already been declared`
D. `5`

Respuesta en el primer comentario.

---
UML in Agile Simply Explained
Tags: development, programming, agile, developer
Published: 2022-07-27 18:16:10

---
title: UML in Agile Simply Explained
published: true
date: 2022-07-27 18:01:04 UTC
tags: #development #programming #agile #developer
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8z9l2k40ezrm1me7ii9u.jpg
---

## Introduction

[**UML**](https://en.wikipedia.org/wiki/Unified_Modeling_Language) is used to simplify written documentation. It is a way to visualize system requirements in diagrams which helps anyone to understand them. Used to model the Object Oriented analysis of a system.

## UML benefits

1. It is agnostic for any language programming.
2. Visuals help anyone to understand the system requirements and design easily.
3. Provide standards that can be learned by anyone.
4. Great compatibility with [**OOP**](https://en.wikipedia.org/wiki/Object-oriented_programming).

## UML Diagrams Types

There are two types:

1. **Structure Diagrams** : They depict system components like objects, relations, etc... For example "User" object (static state).
2. **Behavior Diagrams** : They depict how system components behave and interact with each other. For example "How can a User set an order" (dynamic state).

## When UML would be incredibly useful

**UML** is tightly associated with the [**Waterfall**](https://en.wikipedia.org/wiki/Waterfall_model) model. In this model, system requirements and design must be defined before starting project development. In this model, you can complete modeling your system using **UML** and then start developing.

## When UML might be not fit

In the [**Agile**](https://en.wikipedia.org/wiki/Agile) model, system requirements and design are not defined before starting the project. Instead, they are evolving during the project's progress. As a result, in this model, it is hard to maintain a project using **UML**.

## Difficulties of Using UML in Agile

There are some difficulties to use **UML** in **Agile** projects:

1. System requirements and design are insufficient before starting the project.
2. The big effort to update the **UML** diagrams continuously during the project progress.

## How to Use UML in Agile

If you have the **UML** after project completion, it might be useful as an aid for supporting the system or depicting the system architecture.

## Further Read

- [Is UML Still Relevant Today? How Is it Used in an Agile Environment?](https://managedagile.com/is-uml-still-relevant-today/)
Rubik Cube Simulation in Python: repeat until solved
Tags: rubik, python, cube, simulation
Published: 2022-07-27 17:51:00

If you repeat any sequence of moves on a Rubik cube enough times, the cube will return to the initial (solved) state.
This happens no matter how simple or complex is the chosen sequence.

Each sequence has a length (number of moves in the sequence) and a period, or group order, which is the number of times it must be repeated until the cube returns to the solved state.

Example sequence : F' L' F' L

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

## Sequence Period: How many times to repeat?

On a 3x3x3 cube, depending on the sequence chosen, the period may be as low as 1 or as high as 1260. Here are a few examples.

|Period|Sequence |
|------|---------|
|1     |L L'     |
|2     |R, D, F, F, D', R'|
|4     |U        |
|5     |F' L' F' L|
|6     |R' D' R D|
|105   |U', R'|
|1260  |R' U' R D D U' F R|

On a 4x4x4 cube, the periods can be much larger even reaching 765765.
Some examples.

|Period|Sequence |
|------|---------|
|1     |L L'     |
|4     |U        |
|6     |R' D' R D|
|80    |2L Bw|
|12240 |Rw, U, Fw, Bw, F|
|765765|R R Rw Uw Dw Dw|


## Analysis of the Sequence Period
__Main question__: Given a random sequence of N moves what is the average sequence period?

Although there are [mathematical approaches](https://people.kth.se/~boij/kandexjobbVT11/Material/rubikscube.pdf) to answer this question, we're using a simulation approach with the Python library [magiccube](https://github.com/trincaog/magiccube), which is a fast Rubik Cube simulator.

The simulation is run 1000 times. Each run executes the sequence until the cube returns to the original state.

```python
cube = magiccube.Cube(3)

# Run the simulation N times
for n in range(1000):
    # Generate a random sequence
    moves = cube.generate_random_moves(num_steps=int(sys.argv[1]))
    cube.reset()

    # Execute the sequence
    for i in range(1,1000000):
        cube.rotate(moves)
        # Check if the cube is finished
        if cube.is_done():
            print(i)
            break
```

## Sequence Period decay
The distribution of sequence periods has an exponential decay. Most sequences have small periods, few sequences have large periods.

Using a sequence length of 30 random moves on a 3x3x3 cube, we can see the distribution of period sizes.


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


## Sequence length vs period
The sequence period is typically smaller for shorter sequence lengths, but after a certain threshold, the period doesn't increase any more.
On the 3x3x3 cube, the threshold is around 2-5 moves.
On the 4x4x4 cube, the threshold is around 11-16 moves.
On the 5x5x5 cube, the threshold is in excess of 20 moves.


![Sequence length vs period](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s15tsojuz6yh14ssfcqz.png)

## Final thoughts
Hope you enjoyed. 
If you are a fan of the Rubik cube, you can use the open source  Python library [magiccube](https://github.com/trincaog/magiccube) to solve the cube and perform simulations.
Coin change Leetcode
Tags: dp, java, algorithms
Published: 2022-07-27 17:49:43

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

 

```
Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1
```
```java
class Solution {
    public int coinChange(int[] coins, int amount) {
        if(amount ==0) return 0;
        // we will use dynamic prgramming for  solving this 
        // bottom-up approach
        int dp[][] = new int[coins.length][amount+1];
        for(int row[]: dp) Arrays.fill(row,-1);
        // we will start from last index and go to first index
        int coinsNeeded = findSmallestList(coins.length-1,coins,amount,dp);
        return coinsNeeded ==(int)1e9 ? -1 : coinsNeeded;
    }
    public int findSmallestList(int index,int[] coin,int amount,int dp[][]){
       if(index==0){
           if(amount % coin[index] ==0){
               return amount/coin[index];
           }
           return (int)1e9;
       }
      if(dp[index][amount]!=-1) return dp[index][amount];
        
        int left =(int)1e9;
        //take same index value
        if(amount>=coin[index]){
            left = 1+ findSmallestList(index,coin,amount-coin[index],dp);
        }
        //take next index 
        int right = 0+ findSmallestList(index-1,coin,amount,dp);
        //System.out.println(Integer.min(left,right));
        return dp[index][amount] =Integer.min(left,right); 
    }
}
```

**We can remove the stack space by using top-down approach i.e. Tabulation Approach of Dp**
7 Tools To Convert Code Snippets to Screenshots
Tags: tooling
Published: 2022-07-27 17:47:00

Have you ever needed to share a snippet of code as an image? Maybe you need to send your teammate a quick snippet of a section of code to review. Maybe you want to share a code snippet on social media for some feedback. Here is a list of 7 tools to convert your code snippets to screenshots!

## CodeToImg

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

Code to Image converter is a beautifully designed application that helps you generate beautiful and customizable images of your code snippets. This is built for the developer by the developer. If you want to share your code with anyone or on any social media this is the application you need.

[Visit CodeToImg](https://codetoimg.com/)

## kod.so

![kod.so](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a55hgcdjjqujfa55kxxz.png)

Convert code snippets into screenshots with API support.

[Visit kod.so](https://kod.so/)

## Chalk.ist

![Chalk.ist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2lgqj6860ugwe5uix1p.png)

Turn your source code into beautiful images.

[Visit Chalk.ist](https://chalk.ist/)

## Ray.so

![Ray.so](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atpaw8fe5077reatkoa8.png)

Turn your code into beautiful images. Choose from a range of syntax colors, hide or show the background, and toggle between a dark and light window.

[Visit Ray.so](https://ray.so/)

## Snippet Shot

![Snippet Shot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lu2jt8ft30e4oc7jqalk.png)

Create a screenshot from a code snippet.

[Visit Snippet Shot](https://www.snippetshot.com/)

## Showcode

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

Generate beautiful images of code.

[Visit Showcode](https://showcode.app/)

## Codepng

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

Turn your code into awesome pictures.

[Visit Codepng](https://www.codepng.app/)

---
**Visit our website at [https://nightwolf.dev](https://nightwolf.dev) and follow us on [Twitter](https://twitter.com/nightwolfdev)!**