teleren/devto huggingface dataset:
Hyaline - Hardest Way to Create Discord Bot
Tags: hyaline, discordpy, python, discord
Published: 2021-06-09 05:17:36

# Hyaline Discord API Wrapper.

**WARNING**: Hyaline is not easy to use library.

Hyaline is a discord api wrapper for python. hyaline is created for discord developers and hyaline makes everything harder. _Its in alpha-release and still not finished._

Check `./docs` folder for documentation and more informations about hyaline. Documentation is not finished. You can use python `dir()` function for get all functions, attrs in the object. Also use `help()` for get help about a function / class.


## Installation
Just type `pip install hyaline` and you are ready to go!

**Current Version** - 0.1.0
## Change Log:
- Added PyPi Support!

## Example Ping-Pong Discord Bot

```py
# Import the library and intent helper.
import hyaline
from hyaline.helpers.Intents import ALL

# Setup session configurations.
# NOTE: If you want to limit message cache add MAX_MESSAGES
session = hyaline.Session({
    "TOKEN": "token",
    "INTENTS": ALL
})


async def on_ready(_packet):
    print(f"Bot Started with name: {session.client.username}.")


async def on_message(msg):
    if not msg.author.id == session.client.id and msg.content.lower() == "ping":
        await msg.reply({
            "content": ":ping_pong: Pong!"
        })

# Configure the events.
# Also you can configure multiple event.
session.event("MESSAGE_CREATE", on_message)
session.event("READY", on_ready)

# Start the session.
session.start()
```
Search UTF8mb4 text of MySQL in PHP
Tags: php, mysql, multibyte, emoji
Published: 2021-06-09 05:06:23

MySQL has utf8 & utf8mb4 charcter collation.

Although UTF8 is one encoding type, MySQL's (MariaDB) utf8 only allows to store upto 3-byte characters.

Therefore, some new emojis and Japanese and Chinese characters are not able to store it unless you use utf8mb4.

My CTO at concrete5 Japan, Inc and I came up with the solution to export mysqldump and search the txt in PHP.

It was difficult to search the text only by using SQL.


# Export MySQL Database with MySQLDump

We used `--skip-extended-insert` option so that each record has one line

```
mysqldump -h {$host} -u {$db_username} --password="{$db_password}" --default-character-set=utf8mb4 --single-transaction --skip-extended-insert {$db_name} {$db_tables} > {$SQL_FILENAME}
```

If you need forgot to change your DB collation to utf8mb4, and need to re-work on the existing data, you may want to mysqldump using `--replace --no-create-info` options.

```
mysqldump -h {$host} -u {$db_username} --password="{$db_password}" --default-character-set=utf8mb4 --single-transaction --replace --no-create-info --skip-extended-insert {$db_name} {$db_tables} > {$SQL_FILENAME}
```

# Search UTF8MB4 characters in PHP

Save this as `textsearch.php` and run it on your local or server.

```
<?php
$searchRegex = '/[\x{10000}-\x{10FFFF}]/iu';
$matches = [];

$handle = fopen("SQL_FILENAME", "r");
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle);
        if (preg_match($searchRegex, $buffer)) {
            $matches[] = $buffer;
        }
        /*
        // If you want to print out which characters are really UTF8MB4, use this pref_match_all instead.
        if (preg_match_all($searchRegex, $buffer, $matchesChar)) {
            echo "Character(s): " . implode(',', $matchesChar[0]) . "\n";
            print_r($buffer);
        }
        */
    }
    fclose($handle);
} else {
    echo "nope! cant open it\n";
}
```

```
$ php textsearch.php > {$result.sql}
```

It will filter you the utf8mb4 SQL.

Tested with PHP 7.4.20 with mbstring extension.
🔴 Build Twitter Clone using HTML and CSS - Tutorial
Tags: webdev, beginners, tutorial, html
Published: 2021-06-09 05:00:19

Hello, Everyone. Lets Learn to build Twitter Clone using just HTML & CSS. I Just Love to build these to practice my HTML & CSS Skills. I made a tutorial video to help beginners to improve there html & css skills to build real world projects.

------------------------------------------------------------------

**➜ Tutorial Video:**

{% youtube TSsPAOmTFsM %}

**➜ Github:** https://github.com/somanath-goudar/html-css-projects

**Note:** [Subscribe](https://www.youtube.com/channel/UC_nTrhTr5fnBGjOxnkPUmmA) to My YouTube Channel, Tomorrow I Will also be building **Hulu Clone** with just HTML & CSS.

------------------------------------------------------------------

**➜ You may also like my other posts:**

{% link https://dev.to/somanathgoudar/facebook-clone-using-just-html-css-beginners-tutorial-2fe5 %} 

{% link https://dev.to/somanathgoudar/build-a-youtube-clone-with-just-html-css-for-complete-beginners-4fk1 %}

{% link https://dev.to/somanathgoudar/build-tiktok-clone-in-just-30-mins-using-html-and-css-213l %}
Converting ER-Diagram to Relational Model
Tags: database, computerscience
Published: 2021-06-09 04:58:39

**Rule 1:** Conversion of an entity set into a table
a) Representation of Strong Entity set with simple attributes.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gl818w200gpx7b3j18c6.png)

b) Representation of Strong entity set with Composite Attributes.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qllykdo5u4bk7ixxdl1y.png)

c) Representation of Strong entity set with a multi-valued attribute.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yrwoxvllm0anz02ghs9x.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ddjzd8p41i1nm273l992.png)

d) Representation of Weak entity set.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c34hwmr3cy0ov8riev4.png)

**Rule 2:** Conversion of Relationship into Relation.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fbkmc8scx0buinugfs2j.png)

Thank You!
See you soon again.
How To Check mysqldump character-set
Tags: mysql, mariadb, mysqldump, utf8
Published: 2021-06-09 04:52:52

Learning from mistake.

`mysqldump` doesn't respect database's collation, but mysql client.

Check your mysqldump default character set by typing

```
mysqldump --help | grep default-character-set
```

You always want to add `--default-character-set` option

Example

```
mysqldump -h {$host} -u {$db_username} --password="{$db_password}" --default-character-set=utf8mb4 --single-transaction {$db_name} > {$SQL_file_name}
```

`--single-transition` option is my preferences for the database which mainly uses InnoDB
Git Aliases Are Like Superpowers
Tags: git
Published: 2021-06-09 04:32:51

Using Git Aliases can make you feel like you have superpowers!

It wasn’t until [recently that I discovered Git Aliases](https://twitter.com/dalezak/status/1390044355704934400), they are so handy that I seriously don’t know how I lived without them. These are two that I use every day now.

### Git Add Commit Push

```bash
git config — global alias.add-commit-push '!git add -A && git commit -m "$1" && git push && git status'
```

Once the alias has been added you can now add, commit and push all on one line.

```bash
git add-commit-push "Add, commit, push in one line!"
```

### Git New Branch

```bash
git config --global alias.new-branch '!git checkout -b "$1" && git add -A && git commit -m "$2" && git push -u origin "$1" && git status'
```

This alias adds, commits and pushes current changes to a new branch.

```bash
git new-branch "123-my-branch" "Checkout, add, commit, push!"
```

Checkout the [Git documentation](https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases) for other alias ideas. _Enjoy!_
Dynamic Programming in JavaScript
Tags: javascript, datastructures, codenewbie, algorithms
Published: 2021-07-10 20:10:39

---
title: Dynamic Programming in JavaScript
published: true
date: 2021-06-09 04:29:13 UTC
tags: javascript,datastructures,codenewbie,algorithms
canonical_url: https://medium.com/devtechtoday/dynamic-programming-in-javascript-4026b69bb24b
---

[![](https://cdn-images-1.medium.com/max/2600/0*FdlkSRNMu-2bwrQJ)](https://medium.com/devtechtoday/dynamic-programming-in-javascript-4026b69bb24b?source=rss-be00f566a88f------2)

Hello! I’m glad you’re here! Today I’m going to go over some basics of dynamic programming in JavaScript. This is another one of those…

[Continue reading on DevTechToday »](https://medium.com/devtechtoday/dynamic-programming-in-javascript-4026b69bb24b?source=rss-be00f566a88f------2)
Architecture To Support Multiple Markets & Flows
Tags: discuss
Published: 2021-06-08 22:56:01

Looking to get some opinions/suggestions on how to manage or improve an application that supports multiple markets and flows. As an example we can use a form. There is one base form that can potentially be different per flow & market.

Current architecture is along these lines:

```
const ExampleTopLevel = ({ customSlots = {}, ...props }) => {
  const newSlots = {
    ...exampleSlot1(),
    ...exampleSlot2(),
    ...exampleSlot3(),
    ...exampleSlot4(),
  };

  const combinedSlots = { ...customSlots, ...newSlots };

  switch (condition) {
    case "BRAND":
      return <ExampleBrandSecondLevel customSlots={combinedSlots} {...props} />;
    default:
      return combinedSlots;
  }
};

const ExampleBrandSecondLevel = ({ customSlots, ...props }) => {
  const newSlots = {};
  const combinedSlots = { ...customSlots, ...newSlots };

  switch (condition) {
    case "FLOW_1":
      return <ComponentFlow1 customSlots={combinedSlots} {...props} />;
    default:
      return combinedSlots;
  }
};

const ComponentFlow1 = ({ customSlots = {}, ...props }) => {
  const newSlots = {};
  const combinedSlots = { ...customSlots, ...newSlots };

  switch (config.market) {
    case "MARKET_1":
      return <ExampleMarket1 customSlots={combinedSlots} {...props} />;
    default:
      return combinedSlots;
  }
};

const ExampleMarket1 = ({ customSlots = {} }) => {
  const newSlots = {
    ...exampleSlot1({ readOnly: true }), // Overwrite top level
    ...newSlot1({
      inputRef: null,
    }),
  };

  const combinedSlots = { ...customSlots, ...newSlots };

  return combinedSlots;
};

// Final Result for Flow_1 & Market_1:
const slots = {
  ...exampleSlot1({ readOnly: true }),
  ...exampleSlot2(),
  ...exampleSlot3(),
  ...exampleSlot4(),
  ...newSlot1({
    inputRef: null,
  }),
};
```

This works, however it is causing a lot of duplicate code as this is the same scaffolding for all components across the application. 

I have thought about a schema approach but that becomes difficult to read when there are 15+ slots with different customisations such as labels, onClicks etc. etc.
LeetCode 515. Find Largest Value in Each Tree Row (javascript solution)

Tags: algorithms, javascript
Published: 2021-06-09 03:14:55

###Description:
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

###Solution:
Time Complexity : O(n)
Space Complexity: O(n)

```javascript
// Bfs
var largestValues = function(root) {
    if(!root) return []
    const output = []
    let queue = []
    queue.push(root)
    while(queue.length) {
        const len = queue.length
        // Keep track of the max per level
        let max = -Infinity
        for(let i = 0; i < len; i++){
            const cur = queue.shift()
            max = Math.max(max, cur.val)
            if(cur.left) queue.push(cur.left)
            if(cur.right) queue.push(cur.right)
        }
        // Add the max to the output array
        output.push(max)
    }
    return output
};
```
Code Smell 77 - Timestamps
Tags: oop, programming, webdev, tutorial
Published: 2021-06-09 03:05:29

*Timestamps are widely used. They have a central issuing authority and do not go back, do they?*

> TL;DR: Don't use timestamps for sequence. Centralize and lock your issuer.

# Problems

- Bijection Fault.

- Timestamp Collisions.

- Timestamp precision.

- Packet Disorders.

- Bad [Accidental Implementation](https://dev.to/mcsee/coupling-the-one-and-only-software-design-problem-2pd7) (Timestamp) for an Essential Problem (Sequencing).

# Solutions

1. Use a centralizing sequential stamper. (NO, not a [Singleton](https://dev.to/mcsee/singleton-the-root-of-all-evil-50bh)).

2. If you need to model a sequence, [model a sequence](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086).

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/395fe180085be252c2ff97020b9f3bc9)
```python
# using time module
import time
  
# ts stores the time in seconds
ts1 = time.time()
ts2 = time.time() #might be the same!!
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/67d4df804716d5fb10bcbb7d8ce6f7fe)
```python
numbers = range(1, 100000)
#create a sequence of numbers and use them with a hotspot

#or
sequence = nextNumber()

```

# Detection

Timestamps are very popular on many languages and are ubiquitous. 

We need to use them just to model... timestamps.

# Tags

- Bijection

# Conclusion

This smell was inspired by recent [Ingenuity software fault](https://www.hebergementwebs.com/transport/the-autonomous-helicopter-mars-named-ingenuity-is-confused-by-a-time-stamp-issue-providing-insightful-lessons-for-self-driving-cars-ai).

If we don't follow our [MAPPER](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086) rules and model sequences with time, we will face trouble.

Luckily, Ingenuity is a sophisticated Autonomous vehicle and has a robust fail-safe landing software.

This video describes the glitch

{% youtube 6IoMiwxL2wU %}

# Relations

{% post https://dev.to/mcsee/code-smell-39-new-date-75g %}

{% post https://dev.to/mcsee/code-smell-32-singletons-1ka %}

# More info

- [Timestamp proposed changes](https://ieeexplore.ieee.org/document/805196)

- [Build a Mapper](https://dev.to/mcsee/the-one-and-only-software-design-principle-3086)

- [What is wrong with software](https://dev.to/mcsee/what-is-wrong-with-software-5pa)

* * *

> The most beautiful code, the most beautiful functions, and the most beautiful programs are sometimes not there at all. 

_Jon Bentley_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
LeetCode 345. Reverse Vowels of a String
(javascript solution)
Tags: algorithms, javascript
Published: 2021-06-09 03:03:18

###Description:
Given a string s, reverse only all the vowels in the string and return it.

The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both cases.

###Solution:
Time Complexity : O(n)
Space Complexity: O(1)

```javascript
// Two pointers
var reverseVowels = function(s) {
    // Helper function to check if the current letter is a vowel
    function isVowel(letter) {
        const vowels = {
            a: 'a', e:'e', i:'i', o: 'o', u:'u'
        }
        return vowels[letter.toLowerCase()]
    }
    
    // Left and right pointers
    let left = 0, right = s.length-1
    // Split s into an array so we can swap letters (string are immuatable)
    s = s.split('')
    while(left < right) {
        // Check if pointers are pointing to a vowel
        const l = isVowel(s[left]), r = isVowel(s[right])
        // If both are vowels swap
        if(l && r) {
            const temp = s[left]
            s[left] = s[right]
            s[right] = temp
            left++
            right--
        } else if(!l && !r) { // If both are not vowels move both pointers
            left++
            right--
        } else if(!l) { // Move left pointer
            left++
        } else { // Mover right pointer
            right--
        }
    }
    // Join array to a string
    return s.join('');
};
```
AWS Amplify AppSync GraphQL custom resolver examples
Tags: amplify, aws, graphql, appsync
Published: 2021-06-09 02:39:22

AWS Amplify is great! It handles AppSync backend with AWS resources, like DynamoDB, ElasticSearch, etc for you. However, sometimes these default generated GraphQL schema and resolvers are not fulfill our business need. We create an [Amplify Appsync GraphQL](https://github.com/yinlinchen/amplify-appsync-graphql) GitHub repo to document some of the custom AppSync Resolver.

There are three steps to create your custom resolvers using AWS Amplify CLI

* Step1: Add custom type to the schema
    * Add custom `Query`, `Mutation` or `Subscription` type to your schema.

* Step2: Create custom resolver template
    * Request and response template should be located in `<project-root>/amplify/backend/api/<api-name>/resolvers` folder.
    * Graphql Transformer follows `<TypeName>.<FieldName>.<req/res>.vlt` as convention to name the resolvers.
        * Request template: `Query.myCustomQuery.req.vtl`
        * Response template: `Query.myCustomQuery.res.vtl`

* Step3: Add resolvers resource by creating a custom stack
    *  By default, there is a file called `CustomResources.json` in `<project-root>/amplify/backend/api/<api-name>/stacks` directory of your API.
    * Example: [CustomResource.json](examples/CustomResource.json) 

Currently, we provides these examples:
1. [Basic models](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/basic.md)
2. [Enable basic search](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/search.md)
3. [Fuzzy search](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/fuzzysearch.md)
4. [Query for Interface type](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/interfacetype.md)
5. [Search with AND/OR operations](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/andoroperation.md)
6. [Multi-fields search](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/multifields.md)
7. [Custom searchable input](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/searchableinput.md)
8. [Query for Union type](https://github.com/yinlinchen/amplify-appsync-graphql/blob/master/docs/uniontype.md)

You can deploy the entire example app here:
[![amplifybutton](https://oneclick.amplifyapp.com/button.svg)](https://console.aws.amazon.com/amplify/home#/deploy?repo=https://github.com/yinlinchen/amplify-appsync-graphql)

We hopes these examples help! Please feel free to contribute more custom examples to us and make it better!
API REST e RESTFUL
Published: 2021-06-09 02:16:10

**Olá** dev, tudo bem? :smiley: 

Hoje explicarei de forma simples e direta os conceitos de uma ***API REST*** e como ela pode ser denominada como uma ***API RESTFUL***. 

Representational State Transfer (REST)
Uma API pode ser denominada como RESTFUL quando cumpre todo o conjunto de 05 princípios de arquitetura :

***Stateless (Sem estado):*** Esse princípio diz que cada requisição feita a API deve ser independente, ou seja, ter todos os dados necessários para autenticação e autorização, por exemplo, quando aplicável.

***Client-Server (Separação de Cliente-Servidor):*** Esse princípio diz que devemos separar a interface do usuário (normalmente gráfica) do armazenamento de dados.

***Layered System (Camadas de sistema):*** A indicação é de que a arquitetura da API seja construída com camadas independentes, de forma que cada camada não pode ver além da camada adjacente, bem como as mudanças de uma camada não afetem as demais. É recomentado que entre o cliente-servidor tenha-se uma balanceador de carga (Load Balancer). Uma das vantagens de ter uma API dividida em camadas é que a arquitetura se torna menos completa e fica mais propensa a modificações.

***Cache (Armazenamento em cache):*** O cache é um armazenamento em memória do lado do servidor que ajuda muito quando o assunto é performance e eficiência, visto que uma informação "cacheada" é retornada de forma muito mais rápida. A indicação é que seja possível fazer uma consulta sem cache a qualquer momento através de um recurso chamado HTTP Header.

***Uniform Interface (Interface Uniforme):*** Resume-se em componentes uniformes entre cliente-servidor. Subdividida em 4 partes:
```
* Identificação dos Recursos;
* Representação dos recursos;
* Mensagens auto descritivas;
* Hypermedia (HATEOAS);
```
&nbsp; 
&nbsp;
##Algumas boas práticas são:
- Criar rotas no plural, por exemplo:
`https://meusite.com.br/produtos` 
&nbsp;

- Utilizar letras minúsculas;
- Manter coerência nos métodos HTTP, exemplos mais comuns:

| Método | Descrição |
| ------ | ------ |
|`GET`    | Consultas em geral|
|`POST`   | Normalmente utilizado para inserção de registros|
|`PUT`    | Edição de registros|
|`DELETE` | Deletar registros|
&nbsp;
- Manter coerência com os códigos de retorno das chamadas (StatusCode), alguns exemplos:

| Código                    | Descrição                  |
| ------                    | ------                     |
| :white_check_mark: 200    | Ok                         |
| :white_check_mark: 201    | Criado                     |
| :warning: 401             | Não Autorizado             |
| :warning: 403             | Acesso Proibido            |
| :x: 500                   | Erro interno do Servidor   |

&nbsp;
Henrique Holtz, desenvolvedor de software. :v:

- [Meu Github](https://github.com/henriqueholtz)
- [Meu LinkedIn](https://www.linkedin.com/in/henrique-holtz/)
- [Markdown do Artigo](https://github.com/henriqueholtz/MarkdownArticles/blob/master/Backend/REST.pt-br.md)
Use Ngrx Selectors with Parameters
Tags: angular, redux, webdev
Published: 2021-06-09 00:09:55

Selecting data from an Ngrx store has always been achieved by using selectors. As Ngrx has developed over the last couple of years, selectors have become easier and easier to use.

```ts
interface Customer { id: number; name: string; }
interface AppState { customers: Customer[] }

export const selectCustomers = (state: AppState) => state.customers;
```

The above **selectCustomers** selector conveniently returns **Customers** from the store.

---

##How can we select a single customer entity from the store by its id?

To do this is nice and simple in Ngrx 12+; we can use a **factory selector**.

```ts
import { createSelector } from '@ngrx/store';

interface Customer { id: number; name: string; }
interface AppState { customers: Customer[] }

export const selectCustomers = (state: AppState) => state.customers;

// selector with param
export const selectCustomerById = (customerId: number) =>
  createSelector(
    selectCustomers, 
    (customers: Customers[]) => 
      customers.find(c => c.id === customerId) 
  )
```


We can then get a customer with the id of 123 from the store; by passing a value for the **customerId** into our selector:
```ts
this.store.select(selectCustomerById(123));
```
Hope this helps you all out as the older method of using props is now deprecated in Ngrx 12+. (https://github.com/ngrx/platform/issues/2980)

I also have a [YouTube channel](https://www.youtube.com/channel/UCUBRJNIIpn90gn_dZE2zpGQ) called **Coffee Music & Coding** which you may find useful for Angular and Ngrx tutorials.