teleren/devto huggingface dataset:
Wilson's Primality Test to check whether a number is prime or not?
Tags: cpp
Published: 2022-10-22 14:19:52

```cpp
#include <bits/stdc++.h>
using namespace std;

int fact(int n){
	if(n<=1){
		return 1;
	}
	else{
		return n*fact(n-1);
	}
}

bool isPrime(int p){
	int w=p-1;
	if(p==4){
		return false;
	}
	else{
		if((fact(w)+1)%p==0){
			return true;
		}
		else{
			return false;
		}
	}
}


int main(){

	isPrime(7) ? cout << " true\n" : cout << " false\n";

	return 0;
}
```cpp
HTTP Get and Delete from AWS Lambda
Tags: aws, javascript, httpmethods, lambda
Published: 2022-10-22 14:15:28

## TL;DR
Use Node.js runtime "https" library to perform HTTP operations in AWS Lambda.

## Problem:
Node.js developers tend to use [axios](https://www.npmjs.com/package/axios), [node-fetch](https://www.npmjs.com/package/node-fetch) or other modules to make HTTP calls like Get, Delete, Post etc.
Though same approach works in AWS Lambda (Node.js), but these 3rd party modules adds extra cold start time.

## Solution:
Node.js runtime's https library can be used to trigger HTTP Get, Delete and Post etc. 

#### Code block 1
```
const http = require('https');
let callHttpMethod = function (/* Pass params as needed */) {
    const headers = {
        'Content-type': 'application/json',
        Authorization: 'Bearer authCode'
    }

    let options={
        host: '/* HOST NAME */',
        path: '/* PATH */',
        method: '/* GET or DELETE */', 
        headers: headers
    };

    const promise = new Promise((resolve, reject) => {
        let req = http.request(options, (res) => {
            const chunks = []; 
            res.on('data', chunk => chunks.push(chunk));
            res.on('error', reject); 
            res.on('end', () => {
                const { statusCode, headers } = res;
                const validResponse = statusCode > 200 && statusCode <= 299; 
                const body = chunks.join('');
                if (validResponse) resolve({ statusCode, headers, body }); 
                else reject(new Error(`Request failed. status: $statusCode), body: $(body)`));
            });
        });
        req.end();
        req.on('error', reject);
    });
    return promise;
};

let to = function (promise) {
  return promise.then(data => {
    return [null, data];
  }).catch(err => [err]);
};

let [err, data] = await to(callHttpMethod(/* Pass params as needed */));
```
The "Code block 1" works only for Get and Delete methods (not works for Post operation).

I will update this blog with Post operation code.

Use Node.js runtime libs wherever required to save the size of AWS Lambda code that may help saving the cost as well.

Image by <a href="https://pixabay.com/users/padrinan-1694659/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3813616">Miguel Á. Padriñán</a> from <a href="https://pixabay.com//?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3813616">Pixabay</a>
Reduct Storage Python Client Release v1.0.0
Tags: reductstorage, python, database, opensource
Published: 2022-10-22 14:10:13

Hello dev.to, 

This post is an announcement for the release of v1.0.0 of our Python client for Reduct Storage.

The client has ben updated for compatibility with v1.0.0 of the storage engine's API, which is described [here](https://github.com/reduct-storage/reduct-storage/releases/tag/v1.0.0).

The released package and release notes can be found on [Github](https://github.com/reduct-storage/reduct-py/releases/tag/v1.0.0) or to use it right away you can:
```bash
pip install reduct-py
```
This version drops the `bucket.read_by` method in favour of `bucket.query` and a newly improved `bucket.read` method. 

`bucket.read` now returns an _asynchronous context_, within which data can be loaded from the storage at the desired point with the `Record.read()` or `Record.read_all()` methods: 

```python
async with bucket.read("entry-1", timestamp=1_000_000) as record:
  data = await record.read_all()
  print(data)
```
The perviously deprecated `bucket.list()` method has also been removed, it's functionality having been replaced by `bucket.query()`:

```python
records: List[Record] = [
        record
        async for record in bucket.query("entry-1", start=0, stop=5_000_000)
    ]
```

Think that's all for this post!

May your data storage be robust 🫡
Image Search
Tags: javascript, react, programming, opensource
Published: 2022-10-22 14:06:13



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



---
# Hey Everyone :wave:
## I'm Mahi.
I'm working on an open-source project called Image Search. 
A web-app created by myself and my team to explore and find images for your needs, as well as to offer free downloads with no restrictions and to upload your creativity. This web app is currently being updated, Also not yet finished. We are looking for collaborators on GitHub. You can help us to improve it and make it grow . If you want to contribute, you can look into the repo link given below.

**GitHub Repository:** [https://github.com/Mahich123/Image_Search](https://github.com/Mahich123/Image_Search)
**Preview Link:** [https://image-search-tan.vercel.app/](https://image-search-tan.vercel.app/)

*Your small contribution matters .*
async await in useEffect
Tags: reactversion, reactuseeffect, react182, asyncawait
Published: 2022-10-22 13:48:12

heyy guys.. after creating another project on MERN Stack i came to know that temporary way of using async await in useEffect in react were not working because of react new update and  also it was not the right way to use it


**this is the wrong way of using it :**

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

**So I use this right way :**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lvfpzq7msri9avv6xkhi.jpeg)
Hacktoberfest: Fixing a UI bug
Tags: opensource, beginners, telescope, hacktoberfest
Published: 2022-10-22 13:09:36

As a beginner, looking for a decent project to contribute to requires tremendous searching on my end. For my second [PR](https://github.com/Seneca-CDOT/telescope/pull/3691) for Hacktoberfest, I was able to find an Issue to work on in a project known as [Telescope](https://github.com/Seneca-CDOT/telescope).

## About Telescope
Telescope is an open-source [web application](https://telescope.cdot.systems) created by Seneca College students to aggregate and display a timeline of Seneca's open-source blogs. 

## Finding an Issue
I wanted my contribution to be meaningful, so I thoroughly browsed the open issues in the Telescope GitHub repo. I found one related to a bug in the user interface. I decided to work on this issue because I am familiar with [Material UI](https://mui.com/material-ui/), and the Telescope project is utilizing it in its front end. 

### About the [Issue](https://github.com/Seneca-CDOT/telescope/issues/3614)
Post authentication, hovering over the user avatar in the top navigation shows the user name overlapping with the tooltip.


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

## Fixing the Issue
If you are familiar with Material UI, this is not a difficult bug to fix. All I had to do was add the `marginTop` property to position the tooltip outside the avatar. I also made the value of the `marginTop` consistent with the side `navbar` that appears when you scroll down a page. 

### Challenge Encountered
When setting up Telescope on my local machine, I had a problem correctly seeding the PostgresSQL database. Since Telescope is a large project utilizing many technologies, setting it up locally could prove difficult for some developers. However, after connecting with the members of the Telescope community on Slack, I was able to resolve the problem.

## Outcome
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wwbbawgfcg3rx0qjj98s.png)
I was able to fix a potential accessibility bug in the UI. Now, when logged-in user hovers over their avatar in the top navigation, they see the "Sign out" tooltip appearing outside the avatar space.
The Difference Between ERC721 and ERC1155
Tags: web3, blockchain, nft, crypto
Published: 2022-10-22 12:04:18

When it comes to non-fungible tokens (NFTs), there are two major protocols that have emerged in the space: ERC721 and ERC1155. Both of these standards allow for the creation and management of NFTs on the Ethereum blockchain, but there are some key differences between the two.

## What is ERC721
ERC721 was the first major NFT standard to emerge and is currently the most popular protocol for NFTs. It was created in 2017 by the team at the Ethereum development studio ConsenSys. ERC721 tokens are unique and non-fungible, meaning that each token is distinct from every other token and cannot be interchanged.

ERC721 tokens are often used for collectibles, such as digital art or in-game items. One of the most popular examples of an ERC721 token is Cryptokitties, a virtual pet game where each kitty is a unique NFT. ERC721 tokens can also be used for other purposes such as identity verification, ticketing, and loyalty programs.

## What is ERC1155 
ERC1155 is a newer standard that was created in 2018 by Enjin, a gaming company that specializes in blockchain technology. ERC1155 tokens are also unique and non-fungible, but unlike ERC721 tokens, they can be fungible (interchangeable) or non-fungible. This means that ERC1155 tokens can be used for both collectibles and more traditional assets such as currency or commodities.

## Advantages of ERC1155
ERC1155 tokens have a few advantages over ERC721 tokens. 
1. They can be divided into smaller units, which makes them more versatile for use cases such as loyalty points or in-game currency. 
2. ERC1155 tokens can be traded on decentralized exchanges, whereas ERC721 tokens can only be traded on centralized exchanges.

## Conclusion
Overall, ERC721 and ERC1155 are both valid standards for NFTs. The main difference between the two is that ERC721 tokens are non-fungible and ERC1155 tokens can be either fungible or non-fungible. ERC721 is more popular for collectibles, while ERC1155 is more popular for traditional assets such as currency or commodities.
Set up Keyboard to Mac OS
Published: 2022-10-22 11:56:28

맥북 에어 M1 을 산지 한참이 지나서, 집의 모니터와 연결하기 위해 Belkin사의 USB-C 허브를 구매했고, 키보드와 마우스를 연결했다.

내가 사용중인 바밀로 키보드 모델은 VA87M으로, 맥 OS 지원이 된다고 한다.

나는 JohnGrib님의 HammerSpoon Config 깃헙 레포를 참고하여 동일한 해머스푼을 설정하였는데, 맥에서는 Windows Key와 Alt 키를 인식하지 못했다.

알고보니 바밀로의 윈도우 락 관련된 내용이었고, windows key + fn 키를 동시에 3초 정도 눌러주면 된다고 한다. 내가 본 블로그는 5초라고 하였고, 그래서 5초 누르니까 해결이 되었다.

키보드와 마우스도 동시에 설정하니까 좀 이상하긴 했는데, 여튼 맥의 트랙패드만의 장점이 있다는 것도 깨닫게 되었다.

내 키보드는 윈도우여서, `ctrl`, `windows`, `alt`로 되어있는데, `windows`키가 `command`, `alt`가 `option`키로 바인딩 되어있어서 `KaraBiner-Elements` 프로그램을 설치하여 command, option 키의 위치를 바꾸어주었다.
Top 3 Most Popular APIs at RapidAPI
Tags: beginners, opensource, hacktoberfest, rapidapi
Published: 2022-10-22 11:33:40

As per [this news article](https://techcrunch.com/2018/03/13/rapidapi-an-api-marketplace-that-processes-half-a-billion-api-calls-each-month-raises-9m-led-by-a16z/), RapidAPI gets more than 400 billion API calls per month. In this article, let’s talk about some of the popular APIs at RapidAPI. This write-up is for you if you’re finding APIs to integrate with your mobile apps or website. So, let’s begin!

## Skyscanner Flight Reach
[Skyscanner](https://help.skyscanner.net/hc/en-us/articles/201389882-What-is-Skyscanner-) is a free meta-search engine similar to Google Flights. Skyscanner is a one-stop shop when it comes to individual flight plans and prices. It aggregates all the information in one place so that you don’t have to visit from site to site to look for various flight information. It gives information regarding flight routes, hotels, car rentals, and much more. 

## OpenWeatherMap
[OpenWeatherMap](https://openweathermap.org/) is a service that gives you weather information including historical data and forecasts. OpenWeather Ltd owns this API service. OpenWeatherMap offers access to forecasts and weather maps of multiple cities throughout the world. OpenWeatherMap is fast and precise. It provides minute-by-minute hyperlocal forecasts of precipitation for any location.

## API-Football
[API-Football](https://www.api-football.com/) is one of the most popular RESTful APIs on RapidAPI for various sports data. It provides information regarding football, baseball, volleyball, rugby, Formula-1, hockey, handball, and basketball. You can get live match scores, event information, pre-match odds, historical data, standings, line-ups, stats, and lots more with API-Football.

## Conclusion
That’s about RapidAPI APIs. I hope you find this article interesting and I'll see you next time.
To delete element of an array in mongoose collection
Tags: javascript, mongodb, query, mongoose
Published: 2022-10-22 10:26:15

I'm having a Mongoose collection(Sparks) in this format:
{
    _id: ObjectId("id1");
    title: string;
    description: string;
    type: "USER" | "ADMIN";
    created_at: Date;
    status: "ACT" | "DEL";
    categories: {
        is_trending: boolean;
        is_top: boolean;
    };
    related_sparks: ["id2", "id3",..];
},
{
    _id: ObjectId("string");
    title: string;
    description: string;
    type: "USER" | "ADMIN";
    created_at: Date;
    status: "ACT" | "DEL";
    categories: {
        is_trending: boolean;
        is_top: boolean;
    };
    related_sparks: ["id1", "id2", "id3",..];
},
{
    _id: ObjectId("string");
    title: string;
    description: string;
    type: "USER" | "ADMIN";
    created_at: Date;
    status: "ACT" | "DEL";
    categories: {
        is_trending: boolean;
        is_top: boolean;
    };
    related_sparks: ["id1", "id2", "id3",..];
}

When I delete first spark with ObjectId("id1"), then the same "id1" should be removed from the related_sparks array of every other collection, if present. How is it possible?
Parallel Json Parser -claujson (scj3)
Tags: cpp, json, parallel, parsing
Published: 2022-10-22 10:05:28

This is Experimental.
using simdjson and multi-thread.

[https://github.com/vztpv/scj3](https://github.com/vztpv/scj3)

// test with citylots.json file (about 180mb)
// in intel 10th gen cpu (8core 16thread) and with mimalloc lib.
// my own json parser. - scj3, claujson.
109ms // load file + simdjson`s stage1
parse1 131ms // partial parsing - use multi_thread!
parse2 12ms // merge
Parse End 254 // 254ms (total)

// rapidjson
parse 640ms

// boost/json
parse 543ms

// yyjson
parse 235 125 360ms // immutable 235ms, convert to mutable 125ms
Django API Generator - Free PyPI Library
Tags: webdev, django, opensource, tools
Published: 2022-10-22 09:50:14

---
title: Django API Generator - Free PyPI Library
published: true
description: Simple tool that Generates Secure APIs on top of DRF with minimum effort - Released under the MIT License on Github.
tags: webdev, django, opensource, tools
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8512umci4ilxnxrtt2sa.jpg
canonical_url: https://blog.appseed.us/django-api-generator-free-pypi-library/
---
Hello Coders!

This article presents an open-source [API Generator for Django](https://github.com/app-generator/django-api-generator) that provides a simple way to **build APIs** on top of any model defined in the project. The configuration is minimal and the generated service is restricted to the registered users via JWT Tokens. `Sources`, released under the `MIT license` on GitHub, can be extended, incorporated into other projects, or simply used in eLearning activities. 

> Thanks for reading!

- 👉 [API Generator for Django](https://github.com/app-generator/django-api-generator) - `Source Code`
- 👉 [API Generator for Django](https://pypi.org/project/django-api-generator/) - `PyPi` Page

The tool once is installed using `PIP`, we need to follow up a few steps as described in the project [README](https://github.com/app-generator/django-api-generator/blob/main/README.md): update configuration and routing, generate the API using the CLI and start using the new API service.

![Django API Generator - DRF Interface (free tool for developers).](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xobnbicnvf39ccvi7yse.jpg)

--- 

## ✨ Generator Features

The library can be integrated with any [Django](https://appseed.us/admin-dashboards/django/) project using `PIP`:

```bash
$ pip install django-api-generator
```

Once the library is installed, we should be able to generate API services in no-time.

- ✅ `API engine` provided by `DRF`
- ✅ Secured by `JWT Tokens` (mutating requests)
- ✅ `Minimal Configuration` (single line in the config for each model)
- ✅ `Handles any model` defined across the project
- ✅ `GET` requests are public
- ✅ `Update`, `Delete`, and `Creation` requests are protected

A video material that explains the integration process can be found on YouTube and also the code is available for download from GitHub.

> 👉 [Django API Generator Sample](https://github.com/app-generator/core-django-api-gen) - published on Github

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

---

The video presents all the steps from cloning a simple Django project, to library installation, configuration, and usage for two different models.

In the end, the **Generated API Service** is tested in the browser and also in POSTMAN (all requests).

--- 

> **Thanks for reading!** For more resources and support please access:

- 👉 More [Developer Tools](https://appseed.us/developer-tools/) provided by `AppSeed`
- 👉 Free [support](https://appseed.us/support/) via `Email` & `Discord` (just in case)
Ultimate Guide to Recommendation Letters for UK Global Talent Visa
Published: 2022-10-22 09:28:54

Strong recommendation letters are a foundation of any successful UK Global Talent Visa case.

If you want to apply for Global Talent visa soon, watch this video to learn about the recommended structure of these letters, who can sign them and which mistakes to avoid to maximize your chances:

{% embed https://youtu.be/eDiQfmkPAAM %}
𝗚𝗼𝗼𝗴𝗹𝗲 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗚𝘂𝗶𝗱𝗲 (𝟮𝟬𝟮𝟮)
Published: 2022-10-22 09:20:10

## 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗣𝗿𝗼𝗰𝗲𝘀𝘀:
👉 𝗥𝗲𝗰𝗿𝘂𝗶𝘁𝗲𝗿 𝗣𝗿𝗲-𝘀𝗰𝗿𝗲𝗲𝗻 (20–30 mins) — Non-technical chat about your resume and background. Get ready to answer questions like Why #google? Why are you leaving your current job? What’s your biggest achievement?

👉 𝗧𝗲𝗰𝗵𝗻𝗶𝗰𝗮𝗹 𝗣𝗵𝗼𝗻𝗲 𝗦𝗰𝗿𝗲𝗲𝗻𝘀 (40–60 mins) — One or two phone screens with the hiring manager or a Google employee. You’ll solve a coding question related to #datastructures and #algorithms on a shared Google Doc. Some questions on your background.

👉 𝗢𝗻𝘀𝗶𝘁𝗲 𝗟𝗼𝗼𝗽 (4–5 interviews) — #coding and #systemdesign questions. Expect questions about slightly harder data structure, algorithms, and system design.

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

## Google evaluates candidates on 4 criteria:

𝟭) 𝗚𝗼𝗼𝗴𝗹𝗲𝘆𝗻𝗲𝘀𝘀
Googleyness means putting the user first, being friendly, approachable, humble, doing something nice for others, being proactive, and keeping your eye on the goal. You’ll be judged for being a team player and having a bias for action.

𝟮) 𝗚𝗲𝗻𝗲𝗿𝗮𝗹 𝗖𝗼𝗴𝗻𝗶𝘁𝗶𝘃𝗲 𝗔𝗯𝗶𝗹𝗶𝘁𝘆
Your ability to solve problems and explain your thought process. Expect open-ended questions like how would you optimize this further? The interviewer wants to know how you learn and adapt to a situation.
​
𝟯) 𝗟𝗲𝗮𝗱𝗲𝗿𝘀𝗵𝗶𝗽
Your ability to take on challenging problems and step back when it’s not needed. They’ll gauge if you can mobilize a team to solve a difficult situation. Get ready to answer questions like, how have you demonstrated leadership when you weren’t the manager? how have you dealt with trade-offs and ambiguity?
​
𝟰) 𝗥𝗼𝗹𝗲-𝗿𝗲𝗹𝗮𝘁𝗲𝗱 𝗸𝗻𝗼𝘄𝗹𝗲𝗱𝗴𝗲
Is your technical expertise sufficient to drive impact at Google? How will you grow and scale with the company? Questions: Tell me about a recent/interesting project you worked on. How would you design a task scheduling system?

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

## 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗶𝗽𝘀

- **Data Structures** — Practice Heaps, HashTable, Tree, Stack, Queue, Graph, and Trie.
- **Algorithm** — Practice Dynamic Programming, Quick-Sort, Breadth-first, and Depth-first search.
- **Explain your thought process** — Practice describing your design decisions clearly and concisely.
- **Collaborate** — Don’t forget to discuss tradeoffs, present multiple solutions, and take hints from the interviewer.

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

## 𝗧𝗼𝗽 𝗿𝗲𝗰𝗲𝗻𝘁 𝗚𝗼𝗼𝗴𝗹𝗲 𝘁𝗮𝗴𝗴𝗲𝗱 𝗖𝗼𝗱𝗶𝗻𝗴 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 𝗼𝗻 #𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲

- Happy Number (easy).
- Minimum Meeting Rooms (medium).
- Number of Islands (medium).
- Merge Intervals (medium).
- A number of Closed Islands (medium).
- Making a Large Island (hard).
- Employee Free Time (hard).
- Alien Dictionary (hard).

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

## 𝗧𝗼𝗽 𝗦𝘆𝘀𝘁𝗲𝗺 𝗗𝗲𝘀𝗶𝗴𝗻 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀

- Design a Web Crawler.
- Design Google Docs.
- Design a Messenger.
- Design YouTube.

**✅ Credits: [Arslan Ahmad](https://www.linkedin.com/in/arslanahmad/)**

𝗥𝗲𝗳:
1) Grokking the [**Coding Interview**](https://designgurus.org/course/grokking-the-coding-interview)
2) Grokking the [**System Design Interview**](https://designgurus.org/course/grokking-the-system-design-interview)
React Hooks Tutorials: Introduction
Tags: react, javascript, webdev, tutorial
Published: 2022-10-22 09:10:39

## Introduction to React Hooks
Welcome to the React hooks tutorials 1st tutorial, throughout this series I will try my best to convey the information I have in a very precise manner and in an easily understandable way.
 
Before diving into react hooks I would like to tell you the basic prerequisite and the rules/syntax for using react hooks.

#### I. create react app
First of all, you need to prepare the setup to work with react. For that, you simply need to create react app with your project name whatever you want,

##### Example:
```
create react app <project_name>
```
	

#### II. Remove unnecessary files
Every time we create react app it generates basic code and files. So remove them from the project
Especially remove the code from App.js file return statement 


The above are the basic requirements to start with react. Now I will enlist some basic rules or syntax to use the react hooks

#### 1. Import before use
Every time you will use any react hook it must be imported in that file from `react` by destructuring it out using curly braces.

##### Example:

```
	import React, {useState} form ‘react’
```

#### 2. Use Hooks only in functional components
The react hooks can only be used inside of functional-based components, we can not use them in class components. Since using react hooks we must use function class-based components. On other hand, in class-based components, we have a different approach to achieving the work which we can do with react hooks



#### 3. Define the Hooks at the top 
level of functional component
Using react hooks we must define it at the top level. Neither they can be in any conditional statement nor in any method inside the component.


So that is a really important thing to know about hooks before you start working with them. In future articles, I will discuss all the hooks one by one. Starting with the most used and important hooks.

<hr> 
Exploring new concepts in #JavaScript and sharing with others is my passion and it gives me pleasure to help and inspire people. If you have any questions, feel free to reach out!

Connect me on <a href="https://twitter.com/abidullah_786">Twitter</a>, <a href="https://www.linkedin.com/in/abidullah786/">Linkedin</a> and <a href="https://github.com/abidullah786">GitHub</a>!


<a href="https://www.buymeacoffee.com/abidullah786"><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--n7XsGLsY--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy-me-a-coffee" loading="lazy" width="545" height="153"></a>