teleren/devto huggingface dataset:
Laravel 9 - updateOrCreate
Tags: laravel, eloquent, laravelupdateorcreate, php
Published: 2022-06-05 04:17:10

If you need to check if the record exists, and then update it, or create a new record otherwise, you can do it in one sentence. Use Eloquent method: `updateOrCreate()`.

Instead of this:
```
$flight = Flight::where('departure', 'Oakland')
    ->where('destination', 'San Diego')
    ->first();
if ($flight) {
    $flight->update(['price' => 99, 'discounted' => 1]);
} else {
    $flight = Flight::create([
        'departure' => 'Oakland',
        'destination' => 'San Diego',
        'price' => 99,
        'discounted' => 1
    ]);
}
```

You can do it by this:
```
$flight = Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99, 'discounted' => 1]
);
```
List of Famous Machine Learning Patents
Tags: machinelearning, patent
Published: 2022-06-05 04:11:44

Summary of famous machine learning patents


![Tokyo patent office](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1q44avwn4q60nenc0s6m.png)

## Introduction
Machine learning community is relatively open. Papers can be dowloaded from arXiv for free. On the other hand, we sometimes  found some methods are registered as patents.

I daily collect these patents shared on Twitter and Reddit. The patents below are  the list of machine learning patents. Some patents are under application, not approved.

## General
### Generating output sequences from input sequences using neural networks by Google
http://www.freepatentsonline.com/10402719.html

known as seq2seq

## Preventing overfitting
### System and method for addressing overfitting in a neural network by Google
https://patents.google.com/patent/WO2014105866A1

known as Dropout

### Batch normalization layers
https://patents.google.com/patent/US20160217368A1/en

As title shows, Batch Normalization patents. According to [this slide](https://www.slideshare.net/YosukeShinya/ss-125937523),  the patents are registered in many countries.


## Image, Augmentation
### Object detection and classification in images by Microsoft
http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/9858496

Faster R-CNN (object detection). According to [qiita article](https://qiita.com/yu4u/items/6bc9571c19181c1600a7), it is only applied to U.S.

### DATA AUGMENTATION FOR IMAGE CLASSIFICATION TASKS by IBM
http://www.freepatentsonline.com/y2019/0087694.html

similar to Mixup

## Sound
### Spectrogram to waveform synthesis using convolutional networks by Baidu
https://patents.google.com/patent/US20190355347A1/en

waveform generation from spectrogram by (Multi-head) CNN

### Machine learning to generate music from text by Google
https://pdfaiw.uspto.gov/.aiw?PageNum=0&docid=20180190249&IDKey=&HomeUrl=%2F

Music Generation from text

## Others
### Deep reinforcement learning for robotic manipulation by Google
https://patents.google.com/patent/WO2018053187A1/en

Multiple robots learn individually. By using acquired experiments, policy network is learned.


### Active Machine Learning by Microsoft
https://patents.google.com/patent/US20160162802

When new labels are added, model start relearning in the limit of model size.

## Impression
[US patent office was open for comments about AI patents](https://www.federalregister.gov/documents/2019/08/27/2019-18443/request-for-comments-on-patenting-artificial-intelligence-inventions).

If it is paper, the explicit description  like xx% precision improvement is popular. The patents description is ambiguous for enlarging the claim rights.

If you know the other patens, please let me know.
Laravel 9 - Quick Order by created_at
Tags: laravel, query, eloquent, php
Published: 2022-06-05 04:09:23

Instead of:
```
User::orderBy('created_at', 'desc')->get();
```

You can do it by this:

```
User::latest()->get();
```

By default, `latest()` will order by `created_at`.

There is an opposite method `oldest()` which would order by `created_at` ascending:

```
User::oldest()->get();
```

Also, you can specify another column to order by. If you want to use `updated_at`, you can do this:

```
$lastUpdated = User::latest('updated_at')->first();
```
PHP 8.1 ReadOnly class properties
Tags: php, programming, tutorial, cleancode
Published: 2022-06-05 03:52:27

{% youtube https://www.youtube.com/watch?v=X3XKSl868ZI %}

Today, we will learn how and why you can declare your class properties as `readonly` and how your code could be cleaner/shorter too 🚀

More live programming videos at [learning.ph7builder.com](https://learning.ph7builder.com)

My GitHub https://github.com/pH-7


👉 My Udemy course on how to build a real-world PHP 8.1 application from scratch - https://www.udemy.com/course/create-real-world-php-webapp-from-scratch/ 

Happy coding! 🤠
Swapping Nodes in a Linked List
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 03:00:41

You are given the `head` of a linked list, and an integer `k`.

Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/09/21/linked1.jpg)

**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[1,4,3,2,5\]

**Example 2:**

**Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5
**Output:** \[7,9,6,6,8,7,3,0,9,5\]

**Constraints:**

*   The number of nodes in the list is `n`.
*   `1 <= k <= n <= 105`
*   `0 <= Node.val <= 100`

**SOLUTION:**

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def lenList(self, head, a, k):
            if head:
                curr = 1 + self.lenList(head.next, a + 1, k)
                if a == k:
                    self.a = head
                if curr == k:
                    self.b = head
                return curr
            return 0
        
        def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
            n = self.lenList(head, 1, k)
            self.a.val, self.b.val = self.b.val, self.a.val
            return head
N-Queens
Tags: leetcode, dsa, theabbie
Published: 2022-06-03 18:30:35

The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.

Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.

Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/11/13/queens.jpg)

**Input:** n = 4
**Output:** \[\[".Q..","...Q","Q...","..Q."\],\["..Q.","Q...","...Q",".Q.."\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above

**Example 2:**

**Input:** n = 1
**Output:** \[\["Q"\]\]

**Constraints:**

*   `1 <= n <= 9`

**SOLUTION:**

    class Solution:
        def getAllPos(self, usedCols, usedPosDiag, usedNegDiag, i, n):
            if i >= n:
                return [[]]
            op = []
            for j in range(n):
                if j not in usedCols and (i + j) not in usedPosDiag and (i - j) not in usedNegDiag:
                    val = self.getAllPos(usedCols.union({j}), usedPosDiag.union({i + j}), usedNegDiag.union({i - j}), i + 1, n)
                    op += [[j] + v for v in val]
            return op
        
        def getRow(self, i, n):
            val = ["."] * n
            val[i] = "Q"
            return "".join(val)
        
        def solveNQueens(self, n: int) -> List[List[str]]:
            queens = self.getAllPos(set(), set(), set(), 0, n)
            return [[self.getRow(i, n) for i in q] for q in queens]
arttime: beauty of text art meets functionality of clock/timer
Tags: terminal, textart, productivity, showdev
Published: 2022-06-05 02:06:47

[arttime](https://github.com/reportaman/arttime) is a developer-centric interactive terminal application that blends  beauty of text art with functionality of a smart clock/timer. 

With over 300+ high-quality curated text arts of Web 1.0 era to choose from, arttime also provides a developer-centric clock/timer with growing set of useful features.

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

By default it starts in a help/learn mode that shows arttime's key-bindings, so you don't have to go looking for them before building muscle memory. At any point, pressing ``h`` toggles between the help/learn mode and displaying some beautiful text art. To not show help/learn page on launch, start with option ``--nolearn``.

For this, and a lot more to come, try it here: [arttime](https://github.com/reportaman/arttime). For now the installation steps are simple, but manual. Stay tuned for some exciting, useful, and unique features coming up that will redefine what a developer's work/productivity timer is like.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8hrmdkubuofz5qwm8iv.png)
Partition Array According to Given Pivot
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 02:00:46

You are given a **0-indexed** integer array `nums` and an integer `pivot`. Rearrange `nums` such that the following conditions are satisfied:

*   Every element less than `pivot` appears **before** every element greater than `pivot`.
*   Every element equal to `pivot` appears **in between** the elements less than and greater than `pivot`.
*   The **relative order** of the elements less than `pivot` and the elements greater than `pivot` is maintained.
    *   More formally, consider every `pi`, `pj` where `pi` is the new position of the `ith` element and `pj` is the new position of the `jth` element. For elements less than `pivot`, if `i < j` and `nums[i] < pivot` and `nums[j] < pivot`, then `pi < pj`. Similarly for elements greater than `pivot`, if `i < j` and `nums[i] > pivot` and `nums[j] > pivot`, then `pi < pj`.

Return `nums` _after the rearrangement._

**Example 1:**

**Input:** nums = \[9,12,5,10,14,3,10\], pivot = 10
**Output:** \[9,5,3,10,10,12,14\]
**Explanation:** 
The elements 9, 5, and 3 are less than the pivot so they are on the left side of the array.
The elements 12 and 14 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. \[9, 5, 3\] and \[12, 14\] are the respective orderings.

**Example 2:**

**Input:** nums = \[-3,4,3,2\], pivot = 2
**Output:** \[-3,2,4,3\]
**Explanation:** 
The element -3 is less than the pivot so it is on the left side of the array.
The elements 4 and 3 are greater than the pivot so they are on the right side of the array.
The relative ordering of the elements less than and greater than pivot is also maintained. \[-3\] and \[4, 3\] are the respective orderings.

**Constraints:**

*   `1 <= nums.length <= 105`
*   `-106 <= nums[i] <= 106`
*   `pivot` equals to an element of `nums`.

**SOLUTION:**

    class Solution:
        def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
            left = []
            mid = []
            right = []
            for num in nums:
                if num < pivot:
                    left.append(num)
                elif num > pivot:
                    right.append(num)
                else:
                    mid.append(num)
            return left + mid + right
Medium-Uploader - I Added Support For Uploading to Dev.to
Tags: contentful
Published: 2022-06-05 02:00:08

[**Medium-Uploader**](https://medium-uploader.vercel.app) is a Contentful integration app that allows you to upload your blog post to Medium.com directly from the entry editor.

I'm pleased to announce that I've added support for uploading to [**Dev.to**](https://dev.to) as well!

For more information, please visit the [Forum](https://medium-uploader.vercel.app/forum).
How I finally understood when I can use useRef()
Tags: webdev, javascript, beginners, react
Published: 2022-06-05 01:39:54

Currently I've got a ticket to build a react page with a map view.

Since it's a react app, I chose to use the Mapbox GL JS package. It allows you to load the map view as well as add custom markers.

In my case I have a list of companies to show in this app, and I also need to render the markers for each of the companies. At the same time I need to have filters on the result of companies. So the markers need to be re-rendered every time the results get filtered. 

That requires me to remove the markers when I need to render new markers. So I will need an array to store the markers. I tried to declare a global variable first, but it wouldn't work, I guess it had something to do with the closure issue. Then I did a search using the key words such as 'how can I have properties in a function component'. Then I got the answer that I should can declare an array like:

`const markers = useRef([])`

And when I need to access it I will have to use

`markers.current` instead of `markers`
Next Greater Element I
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 01:30:36

The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.

You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.

For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.

Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._

**Example 1:**

**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.

**Example 2:**

**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.

**Constraints:**

*   `1 <= nums1.length <= nums2.length <= 1000`
*   `0 <= nums1[i], nums2[i] <= 104`
*   All integers in `nums1` and `nums2` are **unique**.
*   All the integers of `nums1` also appear in `nums2`.

**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?**SOLUTION:**

    class Solution:
        def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
            n = len(nums2)
            greater = {}
            for i in range(n):
                for j in range(i + 1, n):
                    if nums2[j] > nums2[i]:
                        greater[nums2[i]] = nums2[j]
                        break
            return [greater.get(num, -1) for num in nums1]
How to find average and count in Laravel ? Tips
Tags: webdev, laravel, beginners, tutorial
Published: 2022-06-05 01:15:16

I added a comment Model in my application, and it has a rating and comments section. However, I wanted to display the average rating of a company and the number of comments for that company in the index page.

Here is how I did it, using Eloquent functions withAvg and withCount:
```
Http\Contollers\CompanyController.php

public function index()
    {
        $company = company::withAvg('rating as ratings', 'rating')->withCount('comment as comments')->latest()->filter()->paginate(12);
         return view('Company.Record.index', compact('company'));

    }
```

I hope it's useful.
Count Good Triplets
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 01:00:57

Given an array of integers `arr`, and three integers `a`, `b` and `c`. You need to find the number of good triplets.

A triplet `(arr[i], arr[j], arr[k])` is **good** if the following conditions are true:

*   `0 <= i < j < k < arr.length`
*   `|arr[i] - arr[j]| <= a`
*   `|arr[j] - arr[k]| <= b`
*   `|arr[i] - arr[k]| <= c`

Where `|x|` denotes the absolute value of `x`.

Return _the number of good triplets_.

**Example 1:**

**Input:** arr = \[3,0,1,1,9,7\], a = 7, b = 2, c = 3
**Output:** 4
**Explanation:** There are 4 good triplets: \[(3,0,1), (3,0,1), (3,1,1), (0,1,1)\].

**Example 2:**

**Input:** arr = \[1,1,2,2,3\], a = 0, b = 0, c = 1
**Output:** 0
**Explanation:** No triplet satisfies all conditions.

**Constraints:**

*   `3 <= arr.length <= 100`
*   `0 <= arr[i] <= 1000`
*   `0 <= a, b, c <= 1000`

**SOLUTION:**

    class Solution:
        def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
            n = len(arr)
            ctr = 0
            for i in range(n):
                for j in range(i + 1, n):
                    for k in range(j + 1, n):
                        if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
                            ctr += 1
            return ctr
How to seed Roles in Laravel using Seeder. (Tips)
Tags: beginners, laravel, tutorial, database
Published: 2022-06-05 00:52:49

I was looking for a way to seed roles to the database after refresh, I couldn't find a suitable solution on the internet and I tried to use Faker function called **randomElements();**, but It migrated the roles in a random order.

Code in Factory _RoleFactory.php_

```
protected $role = Role::class;
    public function definition()
    {
        return [
            'Role' => $this->faker->unique()->randomElement($array = array('Admin', 'Student', 'Supervisor')),
        ];
    }
```
However, I found a way that worked for me on the Laravel Docs using Array seeding.
First run the command below:

`php artisan make:seeder RoleSeeder`
Then write/copy the following code to _RoleSeeder.php_


```
class RoleSeeder extends Seeder
{
public function run()
    {
        Role::factory(3)->state(new Sequence(
            ['id' => 1, 'Role' => 'Admin'],
            ['id' => 2, 'Role' => 'Student'],
            ['id' => 3, 'Role' => 'Supervisor'],
        ))->create();
    }
}
```


Lastly, run the following command.
`php artisan db:seed --class=RoleSeeder`

I hope it is useful.
Client Side Routing
Tags: react, beginners, tutorial, programming
Published: 2022-06-04 23:16:10

Welcome to my first blog post.

Most people would write a blog post to share their thoughts to other people but in my case this is more of a learning experience for myself.

So, I implemented client side routing within my most recent project without properly learning the exact functionality of it. This will be a quick crash course to explain to myself and the others reading this what exactly is client side routing.

A popular plugin to use with React is the React Router. The 'React Router' is the most popular client-side routing library. When used combined with React, allows for an interactive webpage that allows users to switch between different components rendering different content displaying on the page.

An example of importing the React router can be wrapped around the App within the index.js page as show:
```
<BrowserRouter>
   <App />
</BrowserRouter>
```

or you can directly import it within your App page and wrap it around elements that you want to "switch" between components.

```
import {BrowserRouter as Switch, Router} from 'react-router-dom'
```

For example, if your current app will have several different components as routes such as:
* /About
* /Home
* /Form
* /Users

We can import a 'Switch', 'NavLink', 'Link, or 'Redirect' so people can navigate and use our app to render those specific parts of our site like so.

```
<li>
  <Link to="/">Home</Link>
</li>
<li>
  <Link to="/about">About</Link>
</li>
<li>
  <Link to="/users">Users</Link>
</li>
```

This is just one of the many core functionalities of client-side routing. After learning about this, it allowed me to see all of the websites that I currently use in a new light. Reddit is a website that is built using React that I visit frequently. Now every time I use it, I wonder the immense amount of time and effort it took to code out the entire website as it contains an almost infinite amount of components as there are millions of subreddits.

Thank you for reading my incredibly novice attempt at explaining Client Side Routing.
Nim Game
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 00:30:48

You are playing the following Nim Game with your friend:

*   Initially, there is a heap of stones on the table.
*   You and your friend will alternate taking turns, and **you go first**.
*   On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
*   The one who removes the last stone is the winner.

Given `n`, the number of stones in the heap, return `true` _if you can win the game assuming both you and your friend play optimally, otherwise return_ `false`.

**Example 1:**

**Input:** n = 4
**Output:** false
**Explanation:** These are the possible outcomes:
1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
In all outcomes, your friend wins.

**Example 2:**

**Input:** n = 1
**Output:** true

**Example 3:**

**Input:** n = 2
**Output:** true

**Constraints:**

*   `1 <= n <= 231 - 1`

**SOLUTION:**

    class Solution:
        def canWinNim(self, n: int) -> bool:
            return n != (n >> 2) << 2
Keys and Rooms
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 00:01:39

There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.

When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.

Given an array `rooms` where `rooms[i]` is the set of keys that you can obtain if you visited room `i`, return `true` _if you can visit **all** the rooms, or_ `false` _otherwise_.

**Example 1:**

**Input:** rooms = \[\[1\],\[2\],\[3\],\[\]\]
**Output:** true
**Explanation:** 
We visit room 0 and pick up key 1.
We then visit room 1 and pick up key 2.
We then visit room 2 and pick up key 3.
We then visit room 3.
Since we were able to visit every room, we return true.

**Example 2:**

**Input:** rooms = \[\[1,3\],\[3,0,1\],\[2\],\[0\]\]
**Output:** false
**Explanation:** We can not enter room number 2 since the only key that unlocks it is in that room.

**Constraints:**

*   `n == rooms.length`
*   `2 <= n <= 1000`
*   `0 <= rooms[i].length <= 1000`
*   `1 <= sum(rooms[i].length) <= 3000`
*   `0 <= rooms[i][j] < n`
*   All the values of `rooms[i]` are **unique**.

**SOLUTION:**

    class Solution:
        def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
            beg = 0
            paths = [beg]
            visited = {beg}
            while len(paths) > 0:
                curr = paths.pop()
                for j in rooms[curr]:
                    if j not in visited:
                        visited.add(j)
                        paths.append(j)
            return len(visited) == len(rooms)