teleren/devto huggingface dataset:
High order functions in Javascript
Tags: javascript, tutorial, webdev, programming
Published: 2022-05-05 13:03:35

High order functions are functions that take another function as a paramater or return another function.
You see in javascript functions can be treated as variables as well so it makes it possible to return them or pass them as params.

## Implementing a high order function
Let's implement a simple high order function that takes another function and call it inside it's body
```javascript
function doSomething(action) {
    action(); // Hi
}

function actionFunction() {
    console.log("Hi");
}

doSomething(actionFunction);
```
we called the doSomething function and gave it the function actionFunction as param and it simply called it inside it's body and that's perfectly fine in javascript

let's create anothet high order function but now we will instead return a function from it
```javascript
function getAction() {
  return function() {
    console.log("Hi");
  }
}

const action = getAction();

action(); // hi
```
we stored the function returned by getAction then called it afterwards to log hi to the console

## Existing high order functions in Javascript
javascript has a lot of high order functions built in the language, now let's see some of them that are array methods

### the forEach method
```javascript
let arr = [1, 2, 3, 4, 5];

function log(x) {
  console.log(x); // 1, 2, 3, 4, 5
}

arr.forEach(log);
```
the forEach function loops through the array and each time it calls the passed function and give it the element currently iterating on

### the map function
```javascript
let arr = [1, 2, 3, 4, 5];

function double(x) {
  return x * 2;
}

const newArr = arr.map(double);

console.log(newArr); // [ 2, 4, 6, 8, 10 ]
```
the map method replaces the value that is currently iterating on with the value that the passed function returns and then returns the new array

### the filter method
```javascript
let arr = [1, 2, 3, 4, 5];

function isPair(x) {
  return x % 2 == 0;
}

const pairs = arr.filter(isPair);

console.log(pairs); // [ 2, 4 ]
```
the filter method will only keep array elements that are passed to the function and returns true
React Redux Tutorial Part 5 -- useSelector の使い方の復習
Tags: redux
Published: 2022-05-05 13:03:33


## why

https://react-redux.js.org/api/hooks#useselector-examples

React Redux で connect の代替となる useSelector の説明があったが、チュートリアルとしてはなかったので、実際に動かしてみる

---

## connect の時の流れ

https://dev.to/kaede_io/react-redux-tutorial-part-4-connect-api-woshi-tute-todo-apuriwozuo-ru-23f9

この記事の時は

redux/actions -> reducers -> redux/store -> src/index/Provider

と

redux/store -> redux/selectors.js -> Components/.../connect(mapToStateProps) 

これで取ってきている

---

## useSelector での流れ

reducers -> redux/store -> Components/.../useSelector

これで取って来れると予測する。

---

## CRA with TS して store と reducers を作成する

```ts
npx create-react-app redux-useselector --template typescript
```

CRA with TS で redux-useselector という名前で React アプリを作成

https://dev.to/kaede_io/react-redux-part-1-react-redux-nodao-ru-5o1

これの流れの通りに再びやってみた。

```ts
const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload
    },
  },
})
export const { increment, decrement, incrementByAmount } = counterSlice.actions
// exporting increment and decrement

export default counterSlice.reducer
// exporting counter state
```

改めてみると、slice ファイルでグローバルステート定義して
export default で出して

```ts
export function Counter() {
  const count = useAppSelector((state) => state.counter.value)
```

useSelector (をラップしたもの) でグローバルステートを持ってきている。
HELP!!!! Python Error
Tags: python, beginners
Published: 2022-05-05 12:55:40

**No module named 'PyQt5.QtWebEngineWidgets'**

I tried reinstalling PyQt5 And PyQtWebEngine
but still its not working

_This is my code_
```
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.browser = QWebEngineView()
        self.browser.setUrl(QUrl('http://google.com'))
        self.setCentralWidget(self.browser)
        self.showMaximized()


app = QApplication(sys.argv)
QApplication.setApplicationName('Pheonix Browser')
window = MainWindow()
app.exec()
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o0p8gn8ytkj4ga5bmr8c.PNG)
💬NodeJs WebSocketS Chat App
Published: 2022-05-05 12:43:32

If you want create a super simple chat application, of course you must use socket.io, which is the absolute number one, 
you can also use WebSocket API on frontend and in the backend.

### WebSocket Client

The WebSocket object provides the API for creating and managing a WebSocket connection to a server, 
as well as for sending and receiving data on the connection.

In the client side first of all you need to create a WebSocket connection

```
const socket = new WebSocket('ws://localhost:8080');

```

### Events

You need to create three event listeners using addEventListener(),
1. the first one for the 'open' event,
fired when a connection with a WebSocket is opened,

2. the second one for the 'close' event
fired when a connection with a WebSocket is closed,

3. and the last one for the 'message' event,
fired when data is received through a WebSocket.

```
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

```

### WebSocket on the Server Side

In the backend you can also use WebSocket tecnology, in NodeJs you can install 
[ws library](https://www.npmjs.com/package/ws)
it is very easy to implement, to install it perform this command

> npm i ws

import and crete the WebSocket Server 'wss'

```
import WebSocket, {WebSocketServer} from 'ws';

const wss = new WebSocketServer({port:8080});

``` 
listen for connection and send a string or an object welcome message

```
wss.on('connection', (ws, req)=>{

 ws.send(JSON.stringify({time: datetime, message:`💬 Welcome from the Server 🎉.`}));
});

```

In this video guide you can see a super simple implementation, have a nice day!

[Video Guide](https://youtu.be/qJ2SfFcYUrM)
🆗 👋
Python 2.7 was removed from macOS in this update and how to fix it
Tags: python, programming, macos, news
Published: 2022-05-05 12:42:46

---
title: Python 2.7 was removed from macOS in this update and how to fix it
published: 6 May 2021
tags: python, programming, macos, news
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekh3fe5avaioyaam4ilg.png
published: true
---

I was quite surprised this morning to find out that some of my apps stopped working. All of them rely on Python 2.

## Who deleted my Python?

It took me a moment to realize that a new Mac OS 12.3.1 was installed overnight, so I thought it might be a reason.
And here it is.

Python 2.7 was officially gone from the system. Starting from version 12.3 Apple is not going to ship this version of Python anymore as a part of [Mac OS](https://developer.apple.com/documentation/macos-release-notes/macos-12_3-release-notes#Python).

> Python 2.7 was removed from macOS in this update. Developers should use Python 3 or an alternative language instead.

The reason is that [Python 2.x no longer maintained](https://www.python.org/doc/sunset-python-2/)

However apps that rely on Python 2.x are tightly coupled with that version so having Python 3 won't really help.

## So how would you fix it?

Here are a few simple steps that I followed.
First, install [Homebrew](https://brew.sh/) if you haven't got it installed yet. Make sure that it works.

Now we need to get [pyenv](https://github.com/pyenv/pyenv). Pyenv is a Python version manager that will help to manage Python versions. Once pyenv installed we needed to configure Python 2.7, and that is it.

Here are the terminal commands for that.

`brew install pyenv
pyenv install 2.7.18
ln -s "${HOME}/.pyenv/versions/2.7.18/bin/python2.7" "${HOMEBREW_PREFIX}/bin/python"`

Additionally you can set the Python2.7.18 as global by running this command:

`pyenv global 2.7.18`

So, with these simple steps now I’ve got Python 2 back on my system and I hope this article will help someone too.

>_My name is Aliaksei Kuncevič. I am teaching Angular and Web Technology. Helping dev teams to adopt Angular in the most efficient way. GDE, member of the NGXS Core Team._

>_Thanks for reading, and ask your questions in the comments or contact me directly via [linkedin](https://www.linkedin.com/in/kuncevic) or DM me on [twitter](https://twitter.com/kuncevic)_

>_I hope you find this content helpful and if so, please help to spread this article so more people can benefit from it._

>_Additionally you may want to checkout my [podcast](https://angularrocks.com/subscribe) where I am sharing cool tips and insights about Angular and interviewing an awesome guests 🎙_
C++da Operators
Published: 2022-05-05 12:06:37


_Operatorlar ikkiga turga bo'linib, ular quyidagilar:
binary(+,/,*,-)_

**unary**

_Arithmetic operators_
_/ amalini bajarayotganda, ma'lumotni turi muhim bo'lib, kasr son kasr songa, butun son butun songa bo'linayotganini bilish kerak, yo'qsa misolni javobida o'zgarish bo'ladi._

`modulus faqat butun sonlar ustida amallarni bajaradi.`

`amallar matematika bn bir xildek ketma ketlikda bajariladi.`

shortcuts

a += 1
a *(/, -, %)= 4
faqat ushbu qiymatlar uchun shortcut mavjud:
* a += 1* --> a++;
* a -= 1* --> a--;
Danger
++x --> increase x by 1 and do other operations
x++ --> do other operations and increase by 1
--x --> decrease x by 1 and do other operations
x-- --> do other operations and decrease by 1

sample int x =5; int y =x++;
cout << x << y << endl;

after running, the answer is---> 6 5

Relational operator
relationship between left and right sides
result is always either True(1) or False(0)
operators-- <, <=, ==, >=, >, !=
Logical operators
!=not
&&=and--> hammasi to'g'ri bo'lishi shart.
||=or --> 1tasi to'g'ri bo'lsa ham, hisobga o'taveradi.
Thank You
Published: 2022-05-05 11:37:37

Thank you @ben @karanpratapsingh @juniordevforlife  @vaarun_sinha @josafebalili @dinerdas  @sherrydays and lots of others that I couldn't mention. Thank you for helping get back on my feet.
![New PC](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a1sq6j3oduchri1eor8.jpg)
A Gaze Into the salted World of Docker
Tags: docker, beginners
Published: 2022-05-05 11:19:34


In the ’90s the internet was so simple. The only thing that was necessary was to know a few HTML codes that to prepare a web page. In those days, political matters, financial developments, or a new single by Nirvana were readen from a newspaper, on a tv screen. The agenda was set by newspapers or tv shows. The internet was not able to affect social life. However, with technological results...

[A Gaze Into the salted World of Docker
](https://medium.com/@yusufocaliskan/a-gaze-into-the-salted-world-of-docker-55c595d33eeb)
How to create a debouncing timer in Swift
Tags: swift, ios
Published: 2022-05-05 11:14:16

One common problem people tends to underestimate is when users decide to stress a heavy functionality within your app, for example by pressing a button numerous times in a small span, resulting in crashes and undefined behaviors.

One way to overcome this problem is to create a _debouncing timer_. We do that by defining a couple of variables inside the class where the functionality is used:

```
private var debouncingTimer: Timer? = nil
private let DEBOUNCE_TIME: TimeInterval = 0.5
```

The debounce time is the minimum interval for the heavy code to occur. Within that time span other user interactions will be ignored.

Then, from within the outlet of the button who triggers your heavy functionality we perform the following:

```
if debouncingTimer == nil || debouncingTimer?.isValid == false {
    self.debouncingTimer = Timer.scheduledTimer(
        withTimeInterval: DEBOUNCE_TIME,
        repeats: false) { [weak self] timer in
                timer.invalidate()
                self?.debouncingTimer = nil
            }

    // your heavy functionality
}
```

By doing this, we set a timer every time the heavy code is triggered and we protect it until the timer keeps running.

When the timer is invalidated, the functionality becomes available for the user again.
HTML is Amazing. Here are three common UI components that you actually don't need JavaScript for
Tags: html, webdev, beginners
Published: 2022-05-05 10:46:23

A great paradigm in programming is "don't reinvent the wheel". The implementation of this sentiment often takes form in the usage of libraries. Don't get me wrong, libraries are great and can be invaluable, but here's the thing: you don't always need them.

JavaScript is cool and all, but I'm still on the fence. HTML is actually pretty amazing, and can totally be the right tool for the job without having to get stuck in dependency hell.

Instead of using a bloated library, why not try your hand at what vanilla HTML has to offer?  Here are my top three components for UI design I commonly see implemented with JavaScript, but that actually work with good ol' vanilla HTML and that can be used to create interactive HTML elements without any JavaScript.

### Dropdowns

The `<select>` element is commonly used in forms, but with a bit of imagination you can use it for a bunch of other things. How about a language selector, page switcher, or a version menu for documentation pages?

```html
<select>
	<option value="en">English</option>
	<option value="sv">Swedish</option>
	<option value="es">Spanish</option>
	<option value="fr">French</option>
	<option value="de">German</option>
</select> 
```

![Screenshot of a dropdown menu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kietixwmmyfp53uxltxs.png)

### Searchable inputs
As you can see, select elements are great when you want to limit selections to a predefined list, but can become quite overwhelming when you have a large list of options.
 
You can use the `<datalist>` element to create a set of values that the browser can then use for autocompletion.

```html
<input type="text" list="common-search-values" placeholder="Search...">
<datalist id="common-search-values">
	<option>George Orwell</option>
	<option>Daniel Handler</option>
	<option>Neil Gaiman</option>
	<option>Ernest Hemingway</option>
	<option>Virginia Woolf</option>
</datalist>
```
![Screenshot of an input with a datalist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pb5bhk2cbetxsxqk4wzi.png)

### Vanilla HTML datetime picker
This one is my favorite. I spend too much time trying out JavaScript datetime pickers before realizing that HTML already has one. All you need is the following snippet:

```html
<input type="datetime-local">
```

![Screenshot of the datetime-local date picker](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0m38mr2pzcyeke7gxdk.png)

### Learn more
You can try all of the examples shown here on CodePen, https://codepen.io/stresseddev/pen/zYRGgrN


And here are some links to the MDN resources.
- [Dropdowns](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select)
- [Search with autocomplete](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist)
- [Date picker](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local)

What are your favorite HTML elements? When does it make sense to use JavaScript, and when is it best to stick to HTML? Let me know in the comments!
Simple qr/barcode scanning with svelte and Html5Qrcode
Tags: svelte, javascript
Published: 2022-05-05 10:36:21

---
title: Simple qr/barcode scanning with svelte and Html5Qrcode
published: true
description: 
tags: svelte, javascript
cover_image: https://cdn.pixabay.com/photo/2014/04/02/16/19/barcode-306926_960_720.png
---

Ever wanted to scan qr and barcodes using your mobile but didn't want to write a full blown native app just to get camera access? 

Use your mobile browser! Html5 now supports it.

Open the [demo](https://qrcode-scanner-psi.vercel.app/) in your mobile browser - chrome, safari, firefox all worked for me!

Honestly, I couldn't believe how easy it was! Check out the code:

```js
<script>
    import { Html5Qrcode } from 'html5-qrcode'
    import { onMount } from 'svelte'

    let scanning = false

    let html5Qrcode

    onMount(init)

    function init() {
        html5Qrcode = new Html5Qrcode('reader')
    }

    function start() {
        html5Qrcode.start(
            { facingMode: 'environment' },
            {
                fps: 10,
                qrbox: { width: 250, height: 250 },
            },
            onScanSuccess,
            onScanFailure
        )
        scanning = true
    }

    async function stop() {
        await html5Qrcode.stop()
        scanning = false
    }

    function onScanSuccess(decodedText, decodedResult) {
        alert(`Code matched = ${decodedText}`)
        console.log(decodedResult)
    }

    function onScanFailure(error) {
        console.warn(`Code scan error = ${error}`)
    }
</script>

<style>
    main {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 20px;
    }
    reader {
        width: 100%;
        min-height: 500px;
        background-color: black;
    }
</style>

<main>
    <reader id="reader"/>
    {#if scanning}
        <button on:click={stop}>stop</button>
    {:else}
        <button on:click={start}>start</button>
    {/if}
</main>
```

Special thanks to the author of the wonderful [Html5Qrcode](https://github.com/mebjas/html5-qrcode) lib. 

Honorable mention to [quagga](https://serratus.github.io/quaggaJS/). No longer actively maintained, but there is an active fork [quagga2](https://github.com/ericblade/quagga2).

asaf! thanks for reading🥰

[update]: the demo is not a pwa, but the scanner lib and camera access will work if you decide to make a pwa for your own project.
Types of Linked List
Tags: linkedlist, c
Published: 2022-05-05 10:14:25

There are various types of linked list as follows:

1. Singly Linked List
2. Doubly linked List
3. Circular Linked List
4. Doubly Circular Linked List

**Singly Linked List** **:**

Singly linked list is a most common type of linked list in which each node consists of two parts :
 1. Information or data part
 2. Pointer to the next node. 

If suppose the singly linked list consists of four(4) nodes then it is represented as,

![image](https://i.ibb.co/fGHfcLF/IMG-20220425-132020.jpg)

In this type of linked list, each node contains a single pointer to the next node hence it is called as singly linked list. 

Only **forward sequential traversal** is possible in singly linked list because pointer points to the next node in sequence.

C code for a node in the singly linked list is as follows ,


```
struct node
{
  int data;
  struct node *next;
}
```
**Doubly Linked List** **:**

 

In this  type of linked list, each node contains two pointers i.e., one points to the next node in sequence and the other points to the  immediate previous node.

A node in doubly linked list contains three information,

1. Data information
2. Pointer to the next node
3. Pointer to the previous node

If suppose, the doubly linked list contains four nodes, then it is represented as,
![image](https://i.ibb.co/gSGpDDm/IMG-20220425-130742.jpg)

First node has no previous node hence the pointer to the previous node is NULL.

Both **forward** and **reverse sequential traverse** is possible in doubly linked list.

C code for a node in the doubly linked list is represented as follows,
```
struct node
{
  int data;
  struct node *next;
  struct node *prev;
}
```
**Circular Linked List** **:**

In circular linked list, the last node's pointer points to the first or head node in the list making it a circular path as shown below. 
![image](https://i.ibb.co/k0NsG97/IMG-20220425-132341.jpg)

**Doubly Circular Linked List** **:**

A node in  doubly circular linked list contains three information i.e.,

1. Data information
2. Pointer to the next node
3. Pointer to previous node

The last node's pointer points to first or the head node and the first node's pointer points to the last node in the list making it a circular path.

 

![image](https://i.ibb.co/GJN0xv5/IMG-20220425-131350.jpg)




I own a website **www.coderlogs.com** where in I write similar blogs so do visit this website for more such blog posts.
Free Resume Feedback
Tags: discuss, resume, help, beginners
Published: 2022-05-05 10:13:01

Check out the #Resume-Feedback channel in the Hackpack discord channel. There are over 2K engineers (beginners to big tech) who are currently studying for programming interviews. 

If you need any feedback, feel free to throw your resume in the channel! 

Join Here: https://discord.gg/ywWG3DhA
Do you know anything about Vycoffee?
Published: 2022-05-05 10:10:40

[Vycoffee](https://vycoffee.com/) was founded by people who enjoy both programming and coffee, and we are always eager to share our knowledge and passion with others. Let's work together to make Vycoffee. Bring a lot of joy! The editorial staff is working hard to provide users with the finest value while also saving you time.

**What is the best way to utilize Vycoffee?**

Go to Google and type in the keyword you're looking for, then click on Vycoffee's results.
Find and read the answers we provide by searching for a keyword. You may rest confident that we will provide you with the most accurate results.
You might also be interested in some of the top keywords or trending keywords found on the Vycoffee page.


**Why isn't Vycoffee a coffee discussion board?**

We believe that creating a website will provide a few more benefits. Timeliness: You can search for an answer to your issue right now, without having to wait for an administrator to accept your query on the forum or for someone to be available to answer you; all it takes is a few minutes and a mouse click!"
Tuple and usage
Tags: tuple, python, beginners, tutorial
Published: 2022-05-05 10:06:50

**## Pyhton Tuples **
tuple like as stone you can't change the values , it is immutable 
**___usage of Tuple___**
-creating a color scheme for your web site
-a list that you to stay constant

[
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5voqmc4i95fib6jxyamq.jpg)](url)
>to convert in list
list(my_tuple)
Loop increments
Tags: solidity, gasoptimization, bestpractice
Published: 2022-05-05 10:01:54

---series: Gas Optimization techniques---
This is a very simple technique which many of us might be using without knowing it's gas efficient.

Consider the following contracts:

```solidity
contract Inc1{
    uint[] public arr = [0,1,2,3,4,5,6,7,8,9,10];
    uint total;

    function something() external {
        uint sum;
        uint[] memory _arr = arr;
        for (uint i; i < _arr.length; i += 1) {
            sum += _arr[i];
        }
        total = sum;
    }
}

contract Inc2{
    uint[] public arr = [0,1,2,3,4,5,6,7,8,9,10];
    uint total;

    function something() external {
        uint sum;
        uint[] memory _arr = arr;
        for (uint i; i < _arr.length; i++) {
            sum += _arr[i];
        }
        total = sum;
    }
}
```

Both the contracts have function `something` which iterates through the array to sum all the elements. But the difference is in the increment style of loops. **Inc1** has `i +=1` while **Inc2** has `i++`


**Inc1**

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


 
**Inc2**

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