teleren/devto huggingface dataset:
Number of Ways to Select Buildings
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 09:00:51

You are given a **0-indexed** binary string `s` which represents the types of buildings along a street where:

*   `s[i] = '0'` denotes that the `ith` building is an office and
*   `s[i] = '1'` denotes that the `ith` building is a restaurant.

As a city official, you would like to **select** 3 buildings for random inspection. However, to ensure variety, **no two consecutive** buildings out of the **selected** buildings can be of the same type.

*   For example, given `s = "0**0**1**1**0**1**"`, we cannot select the `1st`, `3rd`, and `5th` buildings as that would form `"0**11**"` which is **not** allowed due to having two consecutive buildings of the same type.

Return _the **number of valid ways** to select 3 buildings._

**Example 1:**

**Input:** s = "001101"
**Output:** 6
**Explanation:** 
The following sets of indices selected are valid:
- \[0,2,4\] from "**0**0**1**1**0**1" forms "010"
- \[0,3,4\] from "**0**01**10**1" forms "010"
- \[1,2,4\] from "0**01**1**0**1" forms "010"
- \[1,3,4\] from "0**0**1**10**1" forms "010"
- \[2,4,5\] from "00**1**1**01**" forms "101"
- \[3,4,5\] from "001**101**" forms "101"
No other selection is valid. Thus, there are 6 total ways.

**Example 2:**

**Input:** s = "11100"
**Output:** 0
**Explanation:** It can be shown that there are no valid selections.

**Constraints:**

*   `3 <= s.length <= 105`
*   `s[i]` is either `'0'` or `'1'`.

**SOLUTION:**

    class Solution:
        def numberOfWays(self, s: str) -> int:
            n = len(s)
            z = 0
            o = 0
            zeroes = [z]
            ones = [o]
            for c in s:
                if c == '0':
                    z += 1
                if c == '1':
                    o += 1
                zeroes.append(z)
                ones.append(o)
            ways = 0
            for i in range(n):
                if s[i] == '0':
                    ways += (ones[i] - ones[0]) * (ones[-1] - ones[i + 1])
                elif s[i] == '1':
                    ways += (zeroes[i] - zeroes[0]) * (zeroes[-1] - zeroes[i + 1])
            return ways
Outreachy: Introducing myself
Tags: outreachy, opensource, uiux
Published: 2022-06-05 08:52:42

Hello everyone!
I am Khushi, doing my undergrad in computer science at IIIT Guwahati. I have been into web development for the initial 2 years of my college life but recently shifted to UI/UX and product design 🎨.

I have been recently selected as an Outreachy intern for the May-Aug'22 cohort 🎉. I'll be working with ODK-X on the project “User interface uplift for mobile apps” with my mentors Ben Green and Caroline Krafft.

My Core values:
Courage and Communication

I remember when I applied for Outreachy last year, even my initial application did not get shortlisted which somewhere made me believe Outreachy was a very big (unachievable) goal for me. Eventually, I got over that fear and self-doubt and decided to apply again this year with double the amount of hard work and confidence, which surely worked in my favor 😁🎉. Similarly, we often tend to self-reject or underestimate ourselves, when we really just need to be a little courageous and show up!

'Communication is the key': Truer words have never been spoken. I feel that good and clear communication can solve anything and even bring you great opportunities. Clearly asking my doubts and communicating with the mentors for help definitely helped me draft a good proposal for Outreachy and helped my mentors to get to know me better as well 😅.

My motivation to apply to Outreachy:
I already knew about open-source and Outreachy but did not expect to find any design-related projects here. That changed when I found a fellow product designer on LinkedIn who had interned with Outreachy in the past. Talking to her opened a whole new door for me and made me apply to Outreachy, mainly focusing on design projects 😌🙌.
Introducing prosql.io!
Tags: mysql, go, javascript
Published: 2022-06-05 08:48:09

Hello!

Are you a developer? Do you use MySQL? Which client do you use? Probably one of MySQL Workbench, DBeaver, Navicat or Sequel Pro?

Right. If you are like me you must have wondered why all the clients are so clunky? Why are they so painful to use?

I have been working with MySQL for a few years now and was sick of using available clients. So I did what any self-respecting developer does: I built my own client! You want to check this out:https://prosql.io .

Watch it in action here: 
https://www.youtube.com/watch?v=minL5DgRHmc

If you are thinking the name sounds similar to Sequel Pro, then you are absolutely right! Prosql (read: pro-sequel) is inspired by Sequel Pro which, sadly, runs only on Mac and does not support MySQL 8.0. I started with a goal to make a cross platform (and better) Sequel Pro. I think I have succeeded to a large extent. Here are the top features you may like:

    

1. Clean, clutter free, intuitive interface.
2. Runs on all major platforms: Windows, Linux, Mac and all others supported by Golang.
3. Every query you run gets automatically synced to cloud. Access from anywhere!
4. Queries can be easily searched and tagged.
5. Easily rename databases.
6. In the table viewer you can select only the columns you are interested in. Very handy when debugging.
7. Fast export of data to CSV

… and many more

Coming to some nitty-gritty:

I considered various tech stacks, but concluded that as of 2021 (Flutter was still in beta then), browser is the best medium to deliver applications across platforms. But how to connect to a MySQL server from within the browser? Simple: have an agent (a tiny webserver really) installed on user’s computer and let the Javascript code talk to the agent using CORS. The agent acts as a conduit between the browser and the server.

I was concerned that users may not be willing to install the agent on their computers. I have tried to address that concern by making the agent open source. It is also very very easy to install on all the major platforms. Hell, if you want you can build the agent yourself! I hope installation does not become a bottleneck in Prosql’s adoption.

The agent and the installer are built in Go. If you want to create something cross platform then Golang should be on top of your list. It is trivial to compile Go code for any OS or architecture. If you have ever worked with C you know how painful it can be to port code to various OSes. Go makes it super simple. I love it!

The front end is built in vanilla JS and a bunch of open source libraries. Backend uses Golang and a bit of PHP.

I will be very happy to answer any questions you may have about the tech part.

Give it a try! Let me know your feedback in comments. Thanks!
Valid Sudoku
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 07:30:35

Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**:

1.  Each row must contain the digits `1-9` without repetition.
2.  Each column must contain the digits `1-9` without repetition.
3.  Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition.

**Note:**

*   A Sudoku board (partially filled) could be valid but is not necessarily solvable.
*   Only the filled cells need to be validated according to the mentioned rules.

**Example 1:**

![](https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png)

**Input:** board = 
\[\["5","3",".",".","7",".",".",".","."\]
,\["6",".",".","1","9","5",".",".","."\]
,\[".","9","8",".",".",".",".","6","."\]
,\["8",".",".",".","6",".",".",".","3"\]
,\["4",".",".","8",".","3",".",".","1"\]
,\["7",".",".",".","2",".",".",".","6"\]
,\[".","6",".",".",".",".","2","8","."\]
,\[".",".",".","4","1","9",".",".","5"\]
,\[".",".",".",".","8",".",".","7","9"\]\]
**Output:** true

**Example 2:**

**Input:** board = 
\[\["8","3",".",".","7",".",".",".","."\]
,\["6",".",".","1","9","5",".",".","."\]
,\[".","9","8",".",".",".",".","6","."\]
,\["8",".",".",".","6",".",".",".","3"\]
,\["4",".",".","8",".","3",".",".","1"\]
,\["7",".",".",".","2",".",".",".","6"\]
,\[".","6",".",".",".",".","2","8","."\]
,\[".",".",".","4","1","9",".",".","5"\]
,\[".",".",".",".","8",".",".","7","9"\]\]
**Output:** false
**Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid.

**Constraints:**

*   `board.length == 9`
*   `board[i].length == 9`
*   `board[i][j]` is a digit `1-9` or `'.'`.

**SOLUTION:**

    from collections import defaultdict
    
    class Solution:
        def isValidSudoku(self, board: List[List[str]]) -> bool:
            n = 9
            k = 3
            rowseen = defaultdict(set)
            colseen = defaultdict(set)
            cellseen = defaultdict(set)
            for i in range(n):
                for j in range(n):
                    curr = board[i][j]
                    if curr != ".":
                        if curr in rowseen[i] or curr in colseen[j]:
                            return False
                        rowseen[i].add(curr)
                        colseen[j].add(curr)
                        cell = (i // k, j // k)
                        if curr in cellseen[cell]:
                            return False
                        cellseen[cell].add(curr)
            return True
search through a table in one line of code
Tags: javascript, html
Published: 2022-06-05 08:44:48

## One Line of code


```html
<!DOCTYPE html>
<html lang=de>
  <meta charset=UTF-8>
  <title>Document</title>
  <link rel=stylesheet 
    href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css">
<body class=container>
  <h1>filter table</h1>
  <input type=search id=F>
  <table>
    <thead>
      <tr><td>City<td>Einwohner
      <tbody id=EW>
        <tr><td>Berlin<td>3748148
        <tr><td>Hamburg<td>1891810
        <tr><td>München<td>1471508
        <tr><td>Köln<td>1085664
        <tr><td>Frankfurt am Main<td>753056
        <tr><td>Stuttgart<td>634830
        <tr><td>Düsseldorf<td>619294
        <tr><td>Leipzig<td>587854
  </table>
    <script>
      F.onkeyup=e=>[...EW.rows].map(e => e.style
       .display=[...e.cells]
        .map(e => e.innerText)
        .join(';').match(RegExp(F.value,'i'))?'':'none');  
    </script>
```

{% codepen https://codepen.io/FrankWisniewski/pen/MWQBJVM %}
Course Review: Eloquent performence patterns
Tags: laravel, php, database, sql
Published: 2022-06-05 08:40:08

## Course review 
Eloquent orm is a daily stuff for laravel developers. With profeciency in eloquent, you may easily grow-up your skill to next level. 
Recently, I have completed this course. 
The course link: https://eloquent-course.reinink.ca/

## Tools
To measure database query performence, the author used [laravel debugbar](https://github.com/barryvdh/laravel-debugbar).

## Outcomes
- The proper use of `OneToMany` relationship with effiency. The author showed the wrong and common approach first. Then, he describes the problem. Finally, came with solution. 

- The incredible power of sub queries. How, subqueries eliminates exicution time and memory use.

- Calculating totals using conditional aggregates. 
- Using sub queries to order by related data
- Configuring Laravel to make N+1 issues impossible. 
- and so on.

## Feature
- The crazy tings about the course is, every video has its own code base provided with course. So, you can easily switch  among code bases.

## Conclusion
Thnks,[Rainink](https://twitter.com/reinink) for such a great course.
A11Y 101: Content flow matters
Tags: a11y, webdev, beginners
Published: 2022-06-05 08:38:58

I'll be honest with you, I've made this mistake we will look at in this article many times before.

The mistake we are talking about is content flow. In simple terms, which direction does your content flow in?

When we write our code, there is some semantic follow-up.

```html
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
```

As you can see, these divs are represented in a logical order in the dom.
The main thing is screen readers will always read it in this way.

However, with the magical powers of CSS, we can manipulate the order and reverse it.
For example, we could wrap it on the above and apply `flex-direction: column-reverse;`.

Now the visual user will see the following flow:

```text
4
3
2
1
```

You might think, alright, but why does that matter?
And it gets confusing when we convert these elements into cards and try to use keyboard navigation.

![Flow direction change demo](https://cdn.hashnode.com/res/hashnode/image/upload/v1653548241178/wj8e_TGmj.gif)

In the video above, we can see the keyboard navigation focusing on the correct flow, but for a visual representation, it's super unclear why the flow we see isn't represented.

You can even try it yourself in this CodePen.

{% codepen https://codepen.io/rebelchris/pen/BaYmvaZ %}

## When to be careful?

So, while writing this article, I looked at my website and still reversed some visual elements.

Including my mobile article cards, they switch around the image and the title visually.
But seeing as they are not separate tab elements, I found no harm in this.

Although, I've reached out to some accessibility experts to get their opinion on it.

My guidance at this point is never to change the focus order from the source order.
However, you could make exceptions if it makes better visual sense for elements that don't receive direct focus. (Keep this to a minimum)

## Action item

Try and navigate through your website. Is the tab order the same as the visual order?

You'll be surprised by how many modern websites the tab order is wrong.

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Tell us what to write next?
Tags: webdev, blog, tutorial, help
Published: 2022-06-05 08:36:14

Hello People, 

We at iHateReading are immensely happy to receive such a good response from you all. We will not stop here until we accomplish our goals. Our goal is to help each other in building great products and solving real-world problems. And you can play a crucial role to help us. Share your expectations, share us your next problem statement, share with us your favourite topic, tell us on what topics we should write the next story. And we will certainly write on those topics to help each other.

[You can give suggestion over here] (https://ihatereading.in/feedback)
React A JavaScript library for building user interfaces
Published: 2022-06-05 08:36:10


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

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ieu2ums355ja86nfu0uz.png)[](https://syskido.tistory.com/)
Search a 2D Matrix II
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 08:30:45

Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:

*   Integers in each row are sorted in ascending from left to right.
*   Integers in each column are sorted in ascending from top to bottom.

**Example 1:**

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

**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5
**Output:** true

**Example 2:**

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

**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20
**Output:** false

**Constraints:**

*   `m == matrix.length`
*   `n == matrix[i].length`
*   `1 <= n, m <= 300`
*   `-109 <= matrix[i][j] <= 109`
*   All the integers in each row are **sorted** in ascending order.
*   All the integers in each column are **sorted** in ascending order.
*   `-109 <= target <= 109`

**SOLUTION:**

    import bisect
    
    class Solution:
        def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
            m = len(matrix)
            n = len(matrix[0])
            for i in range(m):
                j = bisect.bisect_left(matrix[i], target)
                j = min(j, n - 1)
                if matrix[i][j] == target:
                    return True
            return False
The best way to compress an image⚡️
Tags: compress, image, macos, window
Published: 2022-06-05 08:24:41

Hi!
In this short tutorial, I will show you how to compress images with an application available on macOs and Windows.

First, here is the link to the application: [antonreshetov/image-optimizer: A free and open source tool for optimizing images and vector graphics. (github.com)](https://github.com/antonreshetov/image-optimizer)

Here is the installation on macOs:

![macOs Installation](https://cdn-images-1.medium.com/max/3838/1*JybL7AOi3psrKbraAFmN3g.png)

![macOs Installation](https://cdn-images-1.medium.com/max/3838/1*ODZ3hyRE90mrAeU65_mAoQ.png)

![macOs Installation](https://cdn-images-1.medium.com/max/3838/1*NQDKwxvuBGXVHtLHjXgjcA.png)

Here is the installation on Windows:

https://www.youtube.com/watch?v=ToOxngkrjAk

The application is now installed! After that you just have to launch the application and go to your folder with the images.

![Compression](https://cdn-images-1.medium.com/max/3154/1*1oqREkylmvr0RvES-hgGow.png)

![Compression](https://cdn-images-1.medium.com/max/3042/1*pkxp_l_nUQxNJY0lw0ifDg.png)

![Compression](https://cdn-images-1.medium.com/max/3194/1*gMKVaoKLDBeGN5P7n2DcTA.png)

## **It’s over! Your images are compressed!**
First Missing Positive
Tags: leetcode, dsa, theabbie
Published: 2022-06-05 08:00:42

Given an unsorted integer array `nums`, return the smallest missing positive integer.

You must implement an algorithm that runs in `O(n)` time and uses constant extra space.

**Example 1:**

**Input:** nums = \[1,2,0\]
**Output:** 3

**Example 2:**

**Input:** nums = \[3,4,-1,1\]
**Output:** 2

**Example 3:**

**Input:** nums = \[7,8,9,11,12\]
**Output:** 1

**Constraints:**

*   `1 <= nums.length <= 5 * 105`
*   `-231 <= nums[i] <= 231 - 1`

**SOLUTION:**

    class Solution:
        def firstMissingPositive(self, nums: List[int]) -> int:
            nums = set(nums)
            mnum = max(nums) + 2
            for i in range(1, mnum):
                if i not in nums:
                    return i
            return 1
Separate array of arrays into arrays
Tags: javascript
Published: 2022-06-05 07:56:42

Let's say you have an array of arrays like this:
[ ['one', 1], ['two', 2], ['three', 3] ]
and what you want are two arrays that are:
['one', 'two', 'three']
[1, 2, 3]

How do you do that?

## Array looping - maps and filters
All you have to do is to loop through the outside array and then the inside array:
```js
const arrayOne = outerArray.map(innerArray => {
  return innerArray.filter((innerArrayItem, index) => index === 0);
});

const array2 = outerArray.map(innerArray => {
  return innerArray.filter((innerArrayItem, index) => index === 1);
});
```

What we're doing is looping through the outside array using a map. Then for each  of the inner arrays within it, we are picking out the item with the relevant index. So for arrayOne we want all of the numbers as strings, which are the first elements in each array.

## Array looping - for loops
If you're not familiar with map and filter you can use two for loops:
```js
let arrayOne = []
let array2 = []
for (let i = 0; i < outerArray.length; i++) {
  for (let j = 0; j < outerArray[i].length; j++) {
    if (j === 0) {
      arrayOne.push(outerArray[i][j]);
    }
    if (j === 1) {
      array2.push(outerArray[i][j]);
    }
  }
}
```

The advantage of this is that you can push to both arrays at the same time. But the first example is easier to scale up - you can easily put it in a function if your inner array has three elements that you want to pull out into three arrays.
JS Arrow Function
Tags: javascript, webdev, programming, react
Published: 2022-06-05 07:30:22

In JavaScript, we often don't need to name our functions, especially when passing a function as an argument to another function. Instead, we can create **inline functions**. We don't need to name these functions because we don't reuse them anywhere else.

There're two ways to use arrow functions. Let's see the syntax.

## Syntax
```javascript
const ArrowFun = function() {
     const myVar = 'Value'
     return myVar
}
```

We can omit the _**function**_ keyword. See the below syntax which results similar to above

```javascript
const ArrowFun = () => {
     const myVar = 'Value'
     return myVar
}
```

Also, there's this other way to write down an arrow function in JavaScript. Like, when there's no function body, and only a return statement, arrow function syntax allows to omit the keyword return as well as the brackets surrounding the code. Have a look on to a below code snippet. 🔽
```javascript
const myFunc = () => 'Value'
```
The above mentioned code will still return the strong value by default.
```javascript
const magic = {} => new Date() //returns a Date
```

Moreover, just like any other function, you can pass Params and other operators to the arrow functions in JavaScript.
Generate Random Gradients for HTML
Tags: html, css, javascript, webdev
Published: 2022-06-05 07:20:35

Lately, I had been a bit away from active development, which had a really adverse effect on my coding, programming and logic building skills. So now I am trying to come out of that phase, which is keeping me away from coding.
Here is React Application I created today. I know it's a pretty dumb application as it only gives you a random gradient as output, along with the ability to copy the gradient code to your clipboard if needed, and also tells you the specs of that particular gradient on your screen. I have also integrated React-Toasts to notify the user about the status of your copy-to-clipboard request.

Being an avid open-source contributor, I couldn't help but upload the code to GitHub and share it with the world. Attaching links to code and live demonstration as well.

Code: https://github.com/mursalfk/Random-Gradients-for-HTML
Live Demo: https://random-hex-gradient.netlify.app/

Below is also attached a short demonstration video for the project.

P.S. I am trying to better my coding techniques. So if you find anything worth sharing about my code do share openly ❤ I am open to all constructive suggestions. Also, do show your love by following me on GitHub and by sharing this piece of code with others.
React - Stateless function
Tags: react, webdev, javascript, reactfunctions
Published: 2022-06-05 07:17:12

Stateless functions are a brilliant way to define highly reusable components. They don't hold state; they're just functions.

```
const MyExample = () => <div>Hello World!</div>
```

They get passed props and context.
```
const MyExample = (props, context) => {
    return <div style={{color: context.color}}>Hi {props.name}</div>
}
```

They can define local variables, where a function block is used.
```
const MyExample = (props, context) => {
    const style = {
        fontWeight: "bold",
        color: context.color,
    }

    return <div style={style}>{props.name}</div>
}
```

But you could get the same result by using other functions.
```
const getStyle = context => ({
    fontWeight: "bold",
    color: context.color,
})

const MyExample = (props, context) => {
    return <div style={getStyle(context)}>{props.name}</div>
}
```

They can have defined _defaultProps_, _propTypes_ and _contextTypes_.
```
MyExample.propTypes = {
    name: PropTypes.string.isRequired
}

MyExample.defaultProps = {
    name: "Guest"
}

MyExample.contextTypes = {
    color: PropTypes.string
}
```