teleren/devto huggingface dataset:
Find position of an element of array using binary search
Tags: php, programming, binary, search
Published: 2022-03-13 16:02:41

Here is details of problem description.

```
/** write a function to search a value in an array and return index or position of array element,
 * if not found return -1.
    * for example, you have given an array like $array=[1,2,3,5,9,11,14,19];
 * $search=11; find the position of 11 in the array.
 * use binary search only.
 */
function binaySearch($array, $value)
{
    // write your code from here

    return 0;
}

$array = [1, 2, 3, 5, 9, 11, 14, 19];
$search = 11;
echo binaySearch($array, $search);
```
Here one important thing is that "Binary search can be implemented only on a sorted list of items". If the elements are not sorted already, we need to sort them first.
Here is the solution.

```
function binaySearch($array, $value)
{
    // write your code from here
    $position = -1;
    //check the array is empty or not. If the array is empty then, return -1;
    if (count($array) == 0) {
        return $position;
    }
    $low = 0;// declare low as zero which is first index
    $high = count($array) - 1;//declare high which is last index
    while ($low <= $high) {
        $mid = floor(($low + $high) / 2);//declare middle and assign average of $low and $high
        if ($array[$mid] == $value) {
            $position = $mid;//found the searching value
            break;
        } elseif ($array[$mid] > $value) {
            $high = $mid - 1;//reassign high, may be the searching value is on left side from the middle.
        } else {
            $low = $mid + 1;////reassign low, may be the searching value is on right side from the middle.
        }
    }
    return $position;
}
```
If you run this code then you will get 5 as output. change the searching value and run again to understand the logic.
If you found any issue contact with me (talemulwi@gmail.com).
Here is full source code link- [https://github.com/talemul/Problem-Solving/blob/main/find-position-using-binary-search.php](https://github.com/talemul/Problem-Solving/blob/main/find-position-using-binary-search.php)
Thank you.
#66 Days of Data
Tags: python, datascience, 100daysofcode, ankitgupta
Published: 2022-03-13 15:52:03

## **Learning Python**  👨‍💻

D 29 of #66daysofdata 📈

Today I have learnt Python Collection Module - String, List and Tuples ✌️

Checkout 👉 [My #66 Days of Data timeline on Github](https://github.com/mrankitgupta/66DaysOfData)

Say me Hi! 
I'll be glad to connect on 
👇

**Twitter** @ [Mr_AnkitGupta01](https://twitter.com/Mr_AnkitGupta01)

**Github** @ [MrAnkitGupta](https://github.com/mrankitgupta)
Curso grátis de Docker
Tags: docker, tutorial, mongodb, mysql
Published: 2022-03-13 15:36:06

## Aprenda como utilizar Docker

  Vários exemplos de como utilizar MySQL, PostgreSQL, MongoDB e outras ferramentas diretamente no Docker.

   O código fonte (docker-compose) para os exemplos está disponível no Github [Feltex](https://github.com/feltex/UsandoDocker). Aproveitem e compartilhem com os colegas! 

 
1. Como instalar o Docker no Ubuntu
{% embed https://www.youtube.com/embed/4ogLjOiLsXs %}

2. Aprenda vários comandos
{% embed https://www.youtube.com/embed/RRpPqNB4UhQ? %}

3. Utilizando Docker Compose
{% embed https://www.youtube.com/embed/OX0UHHOpkrw %}

4. A melhor forma de usar Docker
{% embed https://www.youtube.com/embed/vramc8g9h_s %}

5. Docker Machine
{% embed https://www.youtube.com/embed/186q72hsDwk %}
Open Graph As A Service
Tags: html, social, opengraph, vercel
Published: 2022-03-13 15:33:55

The other day I was looking through a repo and stumbled across someone using Vercel’s open graph image generator (https://og-image.vercel.app/), something I had no idea existed. I was able to set it up and replace my own implementation of something similar on my blog in an evening. My implementation involved generating images at build time with Gatsby, why I ever thought that was a good idea is beyond me.

This allows you generate unique open graph images for each one of your blog posts or pages and set it in meta tags. The meta tag in my blog posts now looks like this:

```html
<meta
  property='og:image'
  content={OpenGraph.generateImageUrl(post.frontmatter.title)}
/>
```

Small tip here is to fork and deploy your own version of this repo (https://github.com/vercel/og-image#deploy-your-own) so you can change the default image. Change this line in your forked copy: 
```js
// api/_lib/parser.ts
if (!images[0].startsWith('https://assets.vercel.com/') && !images[0].startsWith('https://assets.zeit.co/'))
```
Either remove the check altogether or change it to your own URL.

P.S. Also a friendly reminder that this will not work if your pages are not viewable server-side meaning you’re using straight Vue or React to render your entire site. Each page needs to have a viewable html file stored, this is static generation or server side generation.
A Huge Selection of FREE and high-quality Web Services!
Tags: beginners, github, webdev, free
Published: 2022-03-13 15:33:41

![Image description](https://img.freepik.com/free-vector/office-work-school-education-man-writing-chart-board-woman-designer-drawing-graphic-tablet-teacher-stand-knee-giving-book-little-girl-with-schoolbag_33099-2516.jpg)
GENERATORS:

Text Content Generator - http://www.lipsum.com

Favicon Generator - http://tools.dynamicdrive.com/favicon

Data Generator - https://mockaroo.com/

Mobile Mockup Generator - https://mockuphone.com

Logo Generator - https://www.logaster.com

UUID Generator - https://www.uuidgenerator.net/

Hash Generator - https://passwordsgenerator.net/sha256-hash-generator/

Ultimate Code Generator - https://webcode.tools/

IMAGE RESOURCES:

Free Stock Images - https://www.pexels.com

Free Stock Images With Great API - https://unsplash.com/

Free Vectors, mockups - https://www.freepik.com

Dummy Image Placeholders - https://source.unsplash.com/

Dummy Image Placeholders - https://placeholder.com

Free Icons - https://www.iconfinder.com

CODE OPTIMIZATION:

Minify JS & CSS - http://minifier.org

Code Optimization Tools - https://codebeautify.org

Code Diff Checker - https://www.diffchecker.com

CONVERTERS:

ES6+ & JSX Compiler - https://babeljs.io/repl

Sass Converter - https://www.sassmeister.com/

Less Converter & More - http://www.webtoolkitonline.com

Markdown Editor - https://stackedit.io

Jade Converter - http://www.html2jade.org/

IMAGE COMPRESSION:

Compress All Images - https://compressor.io/compress

Compress JPG - http://jpeg-optimizer.com/

Compress PNG - https://tinypng.com/

VALIDATION & COMPATIBILITY:

Validate HTML - https://validator.w3.org

Validate CSS - https://jigsaw.w3.org/css-validator

Check Browser Compatibility - https://caniuse.com/

ES6+ Compatibility Table - https://kangax.github.io/compat-table/es6/

IN BROWSER CODING:

Client Side Code - https://codepen.io

Client Side Code - https://jsfiddle.net

Client Side Code - http://liveweave.com

Server Side Code - https://repl.it

SNIPPET TOOLS:

Snippet Manager - https://gist.github.com

Snippet Manager - https://pastebin.com

COLOR & DESIGN:

Create Color Schemes - https://color.hailpixel.com

Get Color Schemes of Websites - http://stylifyme.com

Create Gradients - https://uigradients.com

CSS Button Generator - http://css3buttongenerator.com

HTML Entity Lookup - http://entity-lookup.leftlogic.com/

RESPONSIVENESS:

Device Testing - http://www.responsinator.com

What's My Browser Size - https://www.webpagefx.com/tools/whats-my-browser-size/

WIREFRAME:

In Browser Wireframing - https://app.moqups.com

Very Basic In Browser Wireframing - https://wireframe.cc

SPEED TEST:

Speed & Performance Testing - https://tools.keycdn.com/speed

Pingdom Speed Test - https://tools.pingdom.com/

OTHER:

Public API Resources - https://github.com/toddmotto/public-apis?utm_source=mybridge&utm_medium=blog&utm_campaign=read_more

Organized Docs for all Popular Web Technologies - https://devdocs.io

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/phx0v6f7wolfow66aqxo.png)
Sorting One Array With Another in JavaScript
Tags: javascript, programming, arrays
Published: 2022-03-13 15:28:41



Recently I needed to sort one array I had no control of to show specific categories in a specific order. Any items in the array of categories that I had not specified in my order array I needed to go at the end of my list. No other order mattered.

I solved this with a simple JS sort function and a little extra code for handling items not in the list.

```js
const categoriesArray = [
  { category: 'stuff' },
  { category: 'things' },
  { category: 'unknown' },
  { category: 'important' },
];
const order = ['important', 'things', 'stuff'];

const sortedArray = categoriesArray
  .slice()
  .sort(({ category: categoryA }, { category: categoryB }) => {
    const indexA = order.indexOf(categoryA);
    const indexB = order.indexOf(categoryB);
    return (
      (indexA > -1 ? indexA : Infinity) - (indexB > -1 ? indexB : Infinity)
    );
  });

// Returns:
// ​[
//  { category: "important" },
// ​ { category: "things" },
// ​ { category: "stuff" },
// ​ { category: "unknown" }
// ]
```
Dart basics - Variables
Tags: dart, beginners
Published: 2022-03-13 15:24:56

original posted here: [https://pedromsluz.com/posts/2022/dart-basics/](https://pedromsluz.com/posts/2022/dart-basics/)

There are several ways of declaring variables. This can be done using one of:

* var
* final
* const
* dynamic

Examples:
```dart
final String name = 'Darth Vader';

var colour = 'Blue';

dynamic isReal = false;
```

## What is the diference between them?

### Var

`var` allows us to defined a variable that can change its value over time. It's `MUTABLE`

```dart
var balance = 100.0;
balance = 300.0;
```

> TIP: avoid has much as possible to use `var`.

In the case where you dont assign a value to the variable in the same line:

```dart
var myString;
myString = 'Darth Vader'; // <-- this variable will be set to `dynamic`
```

Instead of the above is better to give it the type:

```dart
String myString;
myString = 'Dart Vader'; // <-- variable will be of type String
```

---

### Final

`final` means `read-only` (can only be set once), where it is defined. It's `IMMUTABLE`

```dart
final String gender = 'Male'; // <--  `final`variables need to be assigned in the same line.
gender = 'Female'; // <-- not possible will throw an error
```

> TIP: prefer final to var whenever possible

> NOTE: `final` variables need to be assigned in the same line.

---

### Const

`const` defines a compile-time constant

> TIP: const's are very good for performance, since dart can optimise generated coded


> TIP: Prefer to use `const` over `final` over `var`

---

### Dynamic

`dynamic` allows us to `opt-out` of type safe features.

```dart
var x = 10;
x = true; // <--- not valid

dynamic y = 10; // <--- Dart.. trust me. I know what I'm doing.
y = true; // <--- VALID
```

> NOTE: Only use `dynamic` in extreme cases when there is no alternative, or for specific use cases.
create-react-app not working
Published: 2022-03-13 15:18:38

**<u>  If you are facing this version issue follow the below steps</u>**
**In your new folder**

1.npm init

2.npm install create-react-app

3.npx create-react-app myapp

 
**<u>Conclusion :</u>**
     There are many ways to solve this error, Above mentioned steps are one of the method that help you to solve this error
Pro Rect Admin -- Open source scaffolding based on the latest technologies like React
Published: 2022-03-13 15:09:15

Promotion Web
---
1. 基于 Antd 实现亮白及暗黑两套主题
2. 基于 React 最新版本，拥抱 Hooks
3. 基于 React Router V6, 实现嵌套路由更方便
4. 基于 Webpack 最新版本，实现多环境打包部署，代码分割优化，结合官方分析工具，实时优化代码
5. 基于 Faker 实现 Mock Server,不依赖后端实现模拟数据更加方便
6. 封装 Fetch, 实现 useFetch, 请求更加方便，取消请求，实现请求及响应拦截，方便数据处理及统一报错提示
7. 支持 TypeScript, 一切变得可控，扼杀错误于摇篮之中
8. 支持多页签，提升效率
9. 代码风格统一，项目统一配置 ESLint/Prettier/Husky/EditorConfig
10. 配置 Commit message， 使用标准 commit 生成 change log 标准化
11. 配置 Sentry，方便日志追踪，及时发现问题
12. 基于 React Redux Hooks, 状态管理更加方便
13. 实现 ErrorBoundary,方便定位问题，避免不可预知的问题导致系统崩溃
14. 代码分割，组件懒加载，Loading 垂直水平居中
15. 更多特性请 fork 项目，相信我，你会有意想不到的收获

Github: [https://github.com/wkylin/promotion-web](https://github.com/wkylin/promotion-web)

Demo: [https://wkylin.github.io/promotion-web/](https://wkylin.github.io/promotion-web/)


本地启动项目：
  1. git clone https://github.com/wkylin/promotion-web.git
  2. cd promotion-web
  3. 可以选择以下两种方式的任一方式启动项目, 其他 cli 参考 package.json 中的 scripts
    - npm start
    - npm run dev:faker 与后端接口约定后，在没有提供接口时前端可以来模拟后端返回数据
    - npm run dev:server


Give a ⭐️ if this project helped you!
useScrollTrigger in MUI
Tags: codesandbox
Published: 2022-03-13 14:54:44

**Link**
https://mui.com/components/app-bar/#elevate-app-bar

**codes**
```js
import useScrollTrigger from '@mui/material/useScrollTrigger';
```

**Preview**
{% codesandbox sryifu %}

**Issues**
1. I found this `useScrollTrigger` function and made the navbar elevated through the webpage when scrolling down. But I don't use what this function does exactly in the code. The MUI document doesn't provide any information about this function too.
Converting a callback to a promise
Tags: javascript, webdev
Published: 2022-03-13 01:45:42

Sometimes you want your synchronous function to run asynchronously. Perhaps you want to run multiple functions asynchronously using something like `Promise.allSettled` or `Promise.all`.

I have a number of setup functions that dont depend on each other in an application and I was curious how hard it would be to convert the setup functions to async functions without touching their internal code. (Some functions come from libraries)

The TLDR is that yes, I managed to do it.

```js
function asPromise (callback, ...args) {
  return new Promise((resolve, reject) => {
    try {
      resolve(callback(...args))
    } catch(e) {
      reject(e)
    }
  })
}
```

Now for some examples:

```js
function greet (greeting, name) { return "${greeting}, {name}" } 
await asPromise(greet, "hi", "konnor") 
// => "hi, konnor"
```

Now what if we pass an object?

```js
function greet ({greeting, name}) { return "${greeting}, {name}" } 
await asPromise(greet, {greeting: "hi", name: "konnor"}) 
// => "hi, konnor"
```

And finally, what about an array?

```js
function greet (ary) {
  return `${ary[0]}, ${ary[1]}`
}

await asPromise(greet, ["hi", "konnor"])
// => "hi, konnor"
```

Are there edge cases? Probably. Mostly around `this`

if your function calls rely on `this` make sure to bind within the Promise like so:

```js
await asPromise(myFunction.bind(myThis), "arg1")
```

And that's all for today! Short and sweet.
Improving Language Accessibility in Programming
Tags: webdev, beginners, programming, tutorial
Published: 2022-03-13 14:31:35

The English language continues to dominate science and technology. Nearly all documentation and the majority of programming languages are written in English. Stack Overflow and many free educational software programs use it as their official language. End users do not perceive translations as being of the same quality as the original. Prof. Phillip J. Guo found this to be true in a survey he conducted. In addition to communication barriers, the survey found that usage of colloquial language greatly affects a person's ability to comprehend concepts. Among the native French respondents, "The technical terminology associated with programming can be difficult to assimilate, particularly in the middle of explanations if you do not know the equivalent word in your native language." A single technical term can sometimes obscure the meaning of an entire phrase. 

The subject-verb-object relationship is another problem for most non-native speakers. Many complex computer programming languages include terms like if, until, unless, etc. that are often difficult to translate for non-native speakers since they do not have a literal translation. Additionally, non-native speakers can have difficulty understanding the difference between objects, classes, and instances, all of which are core coding concepts. This also results in issues with colloquial variable naming conventions. Based on Guo's survey, "I have noticed users struggle with naming variables. They tend to use meaningless (or worse) names like "table". Problems occur when natural human language meets the code...

In December 2020, progress had begun to make programming education more widespread and accessible. The company ‘Techie Tessie’ was established, with a focus of helping everyone, regardless of language or background, learn about programming. Through multilingual tutorials, 24/7 social media support, and an incredible team, people all over the world are now learning how to program quickly and for free. By producing tutorials in English, Hindi, and Spanish, Techie Tessie are tearing down the language barriers which often hinder education.

Following many studies which have been conducted during the COVID-19 pandemic, it is clear there is still a lot of work to do. With remote, global tech teams becoming the norm, it is vital that language accessibility be at the fore-front of corporate agendas. By providing programming materials in a variety of languages, it will allow for more productive and diverse teams. 

Next time you see a non-native speaker struggling to understand a programming concept, take a moment. Try explaining it in their first language, there are countless free translation apps out there for you to use. Let’s make language a tool, not a barrier.

> You can now extend your support by buying me a Coffee.😊👇

<a href="https://www.buymeacoffee.com/muthuannamalai" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>

Thanks for Reading 😊
CSS Scroll Snap
Tags: css, html, webdev, beginners
Published: 2022-03-13 14:25:06

The CSS Scroll Snap property allows you to adjust the scrolling behaviour of the browser to better align with your content.

The desired effect can be seen here: [scroll-snap-demo.vercel.app](https://scroll-snap-demo.vercel.app)

The most straightforward way to achieve this is to have child elements that make up the page content, along with a parent element that wraps the content.

```html
<div class="scroll-parent">
  <div class="scroll-child">
    <p>Child 1 Content</p>
  </div>
  <div class="scroll-child">
    <p>Child 2 Content</p>
  </div>
  <div class="scroll-child">
    <p>Child 3 Content</p>
  </div>
</div>
```

In the above example, `.scroll-parent` and `.scroll-child` are used. Next, you need to apply the following two sets of styles to the container and the child elements, respectively:

```css
/* the container element */
.scroll-parent {
  /* make the container overflow vertically */
  height: 100vh;
  overflow-y: auto;

  /* define scroll snap behaviour */
  scroll-snap-type: y mandatory;
}

/* the child element */
.scroll-child {
  /* adjust based on desired behaviour */
  scroll-snap-align: start; /* start or center or end */

  /* add for a slideshow-like feel */
  height: 100vh;
}
```

You can view the source code on [GitHub](https://github.com/nico-bachner/scroll-snap-demo). Feel free to copy as much as you want.

In terms of edge cases, please bear in mind that you should exercise caution when modifying the scroll behaviour of your page, as it can lead to some unintended side effects, such as the user not being able to scroll to certain parts of your page, a behaviour which [CSS Tricks](https://css-tricks.com/practical-css-scroll-snapping/#aa-scroll-snap-type-mandatory-vs-proximity) explains well.
navbar design with MUI
Tags: mui, uiweekly
Published: 2022-03-13 14:19:09

**Document**
https://mui.com/components/app-bar/

**modules**
```bash
npm i @emotion/styled
npm i @emotion/react
npm i @mui/material
npm i @mui/icons-material
```
MUI uses `emotion` to style components.

**Code**
{% codesandbox bgqmv3 %}

**Components**
1. Box
2. AppBar
3. ToolBar
4. IconButton
5. MenuIcon
How to get query params from a URL in JavaScript
Tags: javascript
Published: 2022-03-13 14:13:46

Use the property searchParams from URL interface to get the query params from a URL.

## Examples:

In the following example, we have a URL with name and lastname as query params.

```js
const url = new URL('https://example.com/path?name=Ian&lastname=Felix');

// using method get from searchParams

const name = url.searchParams.get('name');
const lastName = url.searchParams.get('lastname');

console.log(name); // 'Ian'
console.log(lastName); // 'Felix'

const myName = `${name} ${lastName}`;

console.log(myName); // 'Ian Felix' - this is my name :)
```

We can use some methods from the searchParams to help us to handle with the query params.

## Methods:

Below is a list of some methods from the searchParams property.

```ts
URL.searchParams.get();
// returns the value of the first query parameter with the given name

URL.searchParams.getAll();
// returns an array of all query parameters with the given name

URL.searchParams.has();
// returns true if the given query parameter exists

URL.searchParams.set();
// sets the value of the first query parameter with the given name
```

You can find more information about interfaces and type aliases in the official TypeScript documentation. - [MDN Docs](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#methods)

Thank you for reading this article.
If you enjoy this article, please upvote and comment.
Follow me on [Twitter](https://twitter.com/_ianfelix)
AgnosticUI + Vest
Tags: svelte, css, webdev, frontend
Published: 2022-03-13 13:35:30

---
title: AgnosticUI + Vest
published: true
description: Demo form using Svelte package of [AgnosticUI](https://agnosticui.com/) — a UI component library that works with React, Vue 3, and Svelte — with Vest for form validation.
tags: svelte, css, webdev, frontend
//cover_image: https://direct_url_to_image.jpg
---

I had the pleasure of playing with [Vest](https://vestjs.dev/) (a form-validation framework inspired by unit testing libraries like Mocha or Jest) over the weekend and was able to hook it up with the [Svelte package](https://www.npmjs.com/package/agnostic-svelte) of my [AgnosticUI](https://agnosticui.com/) UI component library.

Here's the [AgnosticUI + Vest Demo](https://developtodesign.com/agnosticui-examples) :beers:
___

![Example signup form using AgnosticUI and Vest](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z07zztfqmwh23oem2r14.png)
 
___

## First Impressions of Vest

I really love that Vest is so modular and cohesive with its declarative validation style that feels just like you're using a familiar unit testing library :heart:

Hats off to [Evyatar Alush](https://ealush.com/) — Vest's creator — for making such a pleasure to use form validation library :fire:

The demo I've linked above features a bit of custom code to only kick in field validation if a field has been _touched_ (aka _blur_). Otherwise, I think it's a pretty standard signup form and the GitHub source code is all linked — I gotchu :muscle: 

Let me know what you guys think :pray: