teleren/devto huggingface dataset:
Algorithm Techniques: Two Pointers
Tags: algorithms
Published: 2024-05-15 15:53:44


## What is the two pointers technique?
A more flexible variation of the sliding window technique, the two pointers used in this technique can move independently or in tandem through data structures. 
<br />

## When is this technique useful?
This is a common pattern that can be used in a wide range of algorithms. Each pointer refers to an index and travels through the array/string/linked list in order to solve a problem. If the problem requires finding pairs, a specific subsequence, or checking for a palindrome, consider using the two pointer technique. 

In the examples below, two pointers are used to accomplish a variety of tasks.

## Common examples:

* Sorting Colors (with JS)
This function uses two pointers to sort an array of integers in-place. 
```
function sortColors(nums: number[]): void {
    // two pointers
    let left = 0, mid = 0;
    let right = nums.length - 1;

    while (mid <= right) {
        if (nums[mid] === 0) {
            [nums[left], nums[mid]] = [nums[mid], nums[left]];
            left++;
            mid++;
        } else if (nums[mid] === 2) {
            [nums[mid], nums[right]] = [nums[right], nums[mid]];
            right--;
        } else {
            mid++;
        }
    }
};
```

* Merging Arrays
In this simple array merging algorithm, a two pointers travel down two separate sorted arrays, while a third one inserts the larger of the pair. This maintains the nondecreasing order while merging. 
```
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
    let mPointer = m - 1;
    let nPointer = n - 1;
    let insertionInd = m + n - 1;

    while (nPointer >= 0) {
        if (nums1[mPointer] > nums2[nPointer]) {
            nums1[insertionInd] = nums1[mPointer];
            mPointer--;
        } else {
            nums1[insertionInd] = nums2[nPointer];
            nPointer--;
        }
        insertionInd--;
    }
};
```

* Finding Palindromic Substrings
Finally, two pointers are used in this example to identify palindromes. After successfully identifying one, the pointers move to the left and right sides to search for an even longer palindrome.
```
function countSubstrings(s: string): number {
    let count = 0;

    for (let i = 0; i < s.length; i++) {
        expand(i, i); // check for odd-length palindromes
        expand(i, i + 1); // check for even-length palindromes
    }
    return count;

    function expand(left, right) {
        while (left >= 0 && right < s.length && s[left] === s[right]) {
            count++;
            left--;
            right++;
        }
    }
};
```
Setting ChrisTitusTech powershell profile for Terminal and VS Code
Tags: christitustech, powershell, ohmyposh, nerdfonts
Published: 2024-05-15 15:49:08

Execute the following command in an elevated PowerShell window to install the PowerShell profile:
```powershell
irm "https://github.com/ChrisTitusTech/powershell-profile/raw/main/setup.ps1" | iex
```

## Terminal

1. Open the Terminal app and navigate to ``Settings``
2. Under the **Profiles** section click ``PowerShell``
3. Under **Additional Settings** click ``Appearance``
4. Change ``Font face`` to *"CaskaydiaCove Nerd Font"*

## VS Code

1. Open VS Code and navigate to ``File``->``Preferences``->``Settings``
2. In the search bar write *"terminal font"*
3. Write *"CaskaydiaCove NF"* in the text area under ``Font Family``

![Image of the Font Family text area value after the operations in the VS Code section](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zbsb46ziu3aei37b3eeh.png)
Testing in Node.js: Mocha and Chai
Published: 2024-05-15 15:10:03

# Testing in Node.js: Mocha and Chai

Testing your code is an essential part of software development. It helps ensure that your application behaves as expected and catches any bugs or errors before they reach users. In this guide, we will explore how to write tests for your Node.js applications using two popular testing frameworks: Mocha and Chai.

## Setting Up Mocha and Chai

Before we begin writing tests, let's set up Mocha and Chai in our Node.js project:

1. Open your terminal or command prompt.

2. Navigate to the root directory of your Node.js project.

3. Run the following command to install Mocha as a dev dependency:
    
    ```shell
    npm install --save-dev mocha
    ```

4. Similarly, install Chai by running the following command:
   
   ```shell
   npm install --save-dev chai
   ```

## Writing Your First Test with Mocha

Now that we have installed the necessary dependencies, let's create our first test case with Mocha. 

1. Create a new file called `test.js` in your project's root directory.

2. Inside `test.js`, require the necessary modules:

    ```javascript
    const assert = require('chai').assert;
    const myFunction = require('../myFunction');
    ```

   Here, `myFunction` refers to the module or function you want to test from your application.
   
3. Define a test suite using `describe()`:

   ```javascript
   describe('My Function', function() {
       // Tests will go here...
   });
   ```

4. Within the test suite, define individual test cases using `it()`:

   ```javascript 
   it('should return true', function() {
       // Test logic goes here...
       assert.equal(myFunction(), true);
     });
  ```
  
5. To run our test, open your terminal or command prompt and navigate to your project's root directory. 

6. Run the following command:

   ```shell
   npx mocha
   ```

7. Mocha will execute your test case(s) and display the results in the terminal.

## Using Chai Assertions

Chai provides a set of powerful assertions that make it easy to write expressive tests.

- `assert`: This is a simple assertion style provided by Chai, which allows for basic equality checks using methods like `equal()`, `notEqual()`, etc.
- `expect`: This assertion style uses natural language constructs to create readable tests.
- `should`: Should-style assertions provide an expressive way of testing with chained property comparison.

Let's take a look at an example using Chai's expected assertion:

```javascript
describe('My Function', function() {
  it('should return true', function() {
    expect(myFunction()).to.equal(true);
  });
});
```

You can use any of these assertion styles depending on your preferences and requirements within each test case.

## Conclusion

In this guide, you learned how to set up Mocha and Chai for testing Node.js applications. We covered writing your first test case with Mocha, as well as using different types of assertions provided by Chai. Remember, thorough testing helps ensure the reliability and stability of your application, so invest time into writing effective tests for better software quality!
Olive Green Lehenga
Published: 2024-05-15 15:34:40

Olive Green Lehenga Choli Buy latest Green Lehenga 
Choli online from top brands at best price. Shop for Green 
Lehenga Choli Online.An olive green lehenga exudes a 
captivating blend of elegance and earthiness, perfect 
for those seeking a unique and sophisticated look.creating a 
stunning and unforgettable look that captures the essence of 
understated glamour.
https://www.asthanarang.com/products/olive-green-lehenga-set
New integration with GitLab: Replaces user-generated plug-in
Tags: gitlab, productivity, integration
Published: 2024-05-15 15:32:20

Link your software development roadmap in OpenProject closely to planning and specifications in GitLab with our new integration.

Universities, [like Temple](https://www.openproject.org/blog/temple-uni-blog/), love it.

> OpenProject: What features matter most to you and your team?

> Brent Whiting: We love the work packages, but the big one for us is coming in your next release! The integration with GitLab. In higher education, we use GitLab more than GitHub.

## Getting started

First, [configure all the things](https://www.openproject.org/docs/system-admin-guide/integrations/gitlab-integration/#configuration).

## Features

Then, [learn how to use the features](https://www.openproject.org/docs/system-admin-guide/integrations/gitlab-integration/#using-gitlab-integration), like creating merge requests in GitLab and linking them to work packages in OpenProject.
Google I/O Explained: Nutshell
Tags: webdev, google, java, ai
Published: 2024-05-15 15:24:16

_**1. A.I. in Searches:**_
It refers to integration of artificial intelligence technologies directly into the core functionalities of the search engine. This means that AI isn't just an add-on or an external tool but is embedded within the search engine itself, enhancing its existing capabilities such as _**_Natural Language Processing (NLP)_**_

**_2. VEO A.I. Generator:_**
Data Input: Users provide raw data or input parameters.
AI Processing: The AI processes this data using advanced algorithms.
Output Generation: The system generates the desired output (text, image or any video in 1080p Version etc.).

**_3. Project Astra_**
This feature is similar to Apple's Siri in which the personal A.I. agent can see and hear and accordinly perform tasks for us, which will create easy life for us.

**_4. Gemeni 1.5 Pro_**
Google made a series of quality improvements across key use cases, such as **translation, coding, reasoning and more**. You’ll see these updates in the model starting today (IST), which should help you tackle even broader and more complex tasks.

_**_5. Gemini 1.5 Flash _**_
This smaller Gemini model is optimized for narrower or high-frequency tasks where the speed of the model’s response time matters the most.
Hackathon (PHP-PDO)
Published: 2024-05-15 15:21:23


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdvw1inlc765ryagu3dz.PNG)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/juyiwdtrcshl5375amxp.PNG)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/34rjyk4um4ihy1hjc7at.PNG)
`this` Used In Objects
Published: 2024-05-15 15:16:05

---
title: `this` Used In Objects
published: true
description: 
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-05-15 14:56 +0000
---
`this` is one of the most tricky concepts in JavaScript. Fully understanding this topic sets us apart from the other devs in job interviews.

Previsouly I wrote a post [Learn From Mistakes I Made With `this` in JS](https://dev.to/urmajesty516/learn-from-mistakes-i-made-with-this-in-js-31mm), which is about handling `this` used in a function passed as a reference to another function. Here is a continued part talking more about `this` when it's used with objects. Here's an example:

```js
function makeFox() {
  return {
    name: 'fox',
    ref: this
  }
}

const fox = makeFox();
fox.ref.name // what's the result?
```
The code results in an error calling `.name` on `undefined`. This is because `this` refers to the context of the function `makeFox`, not the object returned from it. Here's a way to fix this problem:
```js
function makeFox() {
  return {
    name: 'fox',
    ref() {
        return this;
    }
  }
}

const fox = makeFox();
fox.ref().name // 'fox'
```
By making `ref` a function, `this` becomes dynamic. Its value depends on the object which evokes this function. In this case, the calling object is `fox`.

### Takeaway
Ring off the alarm in your brain once you see `this` is exposed without being wrapped within a code block as a property of an object. For example,
```js
let obj = {
  prop: this
}
``` 
Chances are a mistake has been made unconciously.
Anonymous functions
Tags: dart, flutter, android, ios
Published: 2024-05-15 15:10:35

All the functions have a Name , such
as main, hello.
But not every function needs a name. If you remove the
return type and the function name, then what you have left
is an **_ anonymous function _**.

`Function myFunction = int multiply(int a, int b)
{return a * b; }; `
400+ Free Figma Doodle Icons Across 15 Categories
Tags: figma, ui, uidesign, uiweekly
Published: 2024-05-15 15:00:11

Are you looking for beautiful hand-drawn icons to enhance your designs? Look no further! Khushmeen Sidhu has created a stunning collection of 400 icons, divided into 15 categories, and they are absolutely free for personal use.

### Hand-drawn Icons with an Icon Grid
What sets these icons apart is the meticulous attention to detail and the use of an icon grid. Each icon has been carefully hand-drawn to ensure a consistent and visually pleasing look. The icon grid ensures that the icons align perfectly, making them easy to use in any design project.

### 400 Icons with 15 Categories
With 400 icons to choose from, you'll find everything you need to add that extra touch of creativity to your designs. The icons are organized into 15 categories, including technology, nature, food, and more. Whether you're working on a website, app, or presentation, these icons will help you communicate your message effectively.
![figma 400 Icons](https://neattemplate.com/wp-content/uploads/2024/05/Doodle-icons-Community-%E2%80%93-Figma-1.png)
And the best part? They are free for personal use! So go ahead and download this amazing collection of hand-drawn icons by Khushmeen Sidhu. Use them in your personal projects, spice up your social media posts, or add a unique touch to your personal blog. The possibilities are endless!

Author: Khushmeen Sidhu
[Download](https://www.figma.com/community/file/1019353050314527791)

### See Also
✍[10 Free Figma Landing Page Hero Section Templates](https://neattemplate.com/figma-templates/10-free-figma-landing-page-hero-section-templates)
✍[1440+ Free Figma Plugin 3D Icon Library](https://neattemplate.com/figma-icons/1440-free-figma-plugin-3d-icon-library)
✍[Free iOS Mobile App for Pokemon Gaming designed on Figma](https://neattemplate.com/figma-mobile-app/free-ios-mobile-app-for-pokemon-gaming-designed-on-figma)
✍[Free Figma iPhone 15 Mockup - Showcase Your Designs](https://neattemplate.com/figma-mockup/free-figma-iphone-15-mockup-showcase-your-designs)
✍[Incredible Free Mockups for Figma iPad, iPhone, Android, and Laptop](https://neattemplate.com/figma-mockup/incredible-free-mockups-for-figma-ipad-iphone-android-and-laptop)
✍[Free Figma Google Gemini UI Design Download](https://neattemplate.com/figma/free-figma-google-gemini-ui-design-download)
✍[Best Free Android UI Kit for Figma](https://neattemplate.com/figma-ui-kits/best-free-android-ui-kit-for-figma)
✍[Download Free Figma Mobile Game Quiz  UI](https://neattemplate.com/figma-mobile-app/download-free-figma-mobile-game-quiz-ui)
✍[iPhone 15 Pro 3D Mockups - Free Figma Download](https://neattemplate.com/figma/iphone-15-pro-3d-mockups-free-figma-download)
Tourist spot in china
Tags: china, tourist, architecture
Published: 2024-05-15 14:59:38

China is known for its rich history or its architecture and landscape

## 1.The Great wall of china

- Fun Fact
- Length: 21,196.18 kilometers (13,170.70 miles) in total.
- Construction: constructed during the Ming dynasty (1368–1644).

## 2. The Forbidden City & the Imperial Palace (Beijing)
Fun Fact

- Also known as the Palace Museum.
- the world’s largest imperial palace.
- European and Arabic-style buildings can be found within the Forbidden City.

## 3. The Terracotta Army (Xi’an)
Fun Fact

- Also known as the Terracotta Warriors and Horses.
- It has more than 8,000 soldiers, 130 chariots with 520 horses, and 150 cavalry horses.
For more information please visit our website Unique india blogs 
website link in bio
Learn From Mistakes I Made With `this` in JS
Published: 2024-05-15 14:53:48

---
title: Learn From Mistakes I Made With `this` in JS
published: true
description: 
tags: 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-05-15 14:39 +0000
---

Here I'd like to talk about the mistake I made in one of the online assessments for a job interview regarding `this` in Javascript.

Here's the question - What would be logged from below code?
```js
function Fox(color) {
  this.color = color;
}

Fox.prototype.speak = function () {
  console.log(`I'm ${this.color}`);
};

const myFox = new Fox('blue');
setTimeout(myFox.speak, 1000);
```
If you were like me, thought it would log "I'm blue", then congrats, you are perfectly wrong! The correct answer is "I'm undefined". 

So why did `this` lose its context? This is because `myFox.speak` is passed into `setTimeout` as a function reference only, without the correct calling context. To fix this problem, here are a few ways.

### Use arrow function
Arrow function does not have `this` and it takes the value of `this` from an outer context. In this case, the outer context refers to `myFox`.
```js
setTimeout(() => myFox.speak(), 1000)
```

### Use `bind`
The calling context is bound by using `bind`.
```js
setTimeout(myFox.speak.bind(myFox), 1000)
```

### Explicitly evoke speak()
```js
setTimeout(function() {
  myFox.speak()
}, 1000)
```

### Takeaway
Ring off the alarm in your brain whenever you see a function containing `this` is passed as a reference.
Best offline games for android
Tags: games, gamedev, android
Published: 2024-05-15 14:48:44

## Racing Games for android
If you’re looking for some thrilling racing games for your Android device, you’re in luck! because recently I found some good and good graphic games these are

- Asphalt 9: Legends
- CSR 2 Racing
- Hill Climb Racing 2
- Need for Speed™ No Limits
- Rally Fury: Extreme Racing

## Action Games for android
If you’re looking for some thrilling action games to play on your Android device

- Ailment and Endurance
- Bullet Hell Monday series
- Call of Duty: Mobile
- Dead Cells
- Soul Knight
For more information please visit our website

alltypestore.online
LOGIN SYSTEM IN PHP AND MYSQL: User Authentication system.
Tags: webdev, php, mysql
Published: 2024-05-15 14:41:18

**hackathon - OFPPT**

User **authentication** in web developemen is used to authorized and restrict users to certain pages in a web appplication.

here are the github repository
[github](https://github.com/salahghr4/hackathon)

### REGISTERATION SYSTEM
#### DATABASE TABLE IN MYSQL
The database used is MySQL, so you'll need a MySQL database to run create the users table.
Run the `hackathon.sql` file in MySQL database to create users table.

### CONFIGURATION FILE
The PHP script to connect to the database is in `config.php` directory.
Replace credentials to in `config.php` to match your server credentials.
```
<?php

$host = 'localhost';
$db   = 'Hackathon';
$user = 'root';
$pass = '';
$charset = 'UTF8';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";

// set the PDO error mode to exception and the default fetch mode to associative arrays
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];

try {
    $conn = new PDO($dsn, $user, $pass, $options);

} catch (PDOException $e) {
    echo 'Connextion failed' . $e->getMessage();
}
```

### REGISTERATION FORM AND SCRIPT
The `register.php` creates a web form that allows users to register themselves.
The script generates error if form input is empty and username is has been taking already by another user.

 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ba1ef6lh985zihemg4o.jpg)
## LOGIN SYSTEM

#### LOGIN FORM AND SCRIPT
`login.php` is the login script.
When a user submit a form with the input of username and password, these inputs will be verified against the credentials data stored in the database, if there is a match then the user will be authorized and granted access to site or page.


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5mlvbhvtg99e0u1gdsd2.jpg)

### DASHBOARD PAGE
User is redirected to `dashboard.php` if login is successful.


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

### LOGIN OUT
`logout.php` log out the user and destroy all his sessions.

### SECURITY
- always hash the password before stoke it in the database.
we use functions **password_hash()** for hashing
and **password_verify()** for check for the hashed password.

- we use the function **filter_input()** its similar to **htmlspecialchar()**, to validate variables from insecure sources, such as user input.

- use **sessions** to store and persist user-specific data across multipile pages.
Middlewares in Next JS
Tags: nextjs, learning, programming, webdev
Published: 2024-05-15 14:00:14

## Middleware in Next.js

Middlewares are code that runs before / after your request handler.

**Commonly used for**

- Analytics
- Authentication
- Redirecting [ In an Express App it is not applicables, cuz Express runs in backend ]
- Modifying the request/response

### How

Create an **`middleware.ts`**, in the top level of yourfresh Next.js app.
You can only one have one `middleware.ts` where all your middlewares are defined. But you can still organize your middleware logic modularly & then importing them in `middleware.ts` file.

A Simple Middleware to count the number of Visitors on your site -

```tsx
// This code will run on every request
import { NextRequest, NextResponse } from "next/server";

let requestCount = 0;
// Simply Define a function named middleware that takes req as parameter.
export default function middleware(req: NextRequest) {
	requestCount++;
	console.log("Number of Requests", requestCount);
	return NextResponse.next();
}
```

But there is a **problem**.
Every time we visit the app the count get increased by many times, not 1. This is because `Next.js` made many request which will cause counter to increase many times.

For Example this request
![Network Tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jt0jltunderpysulx12.png)

)

There are **2 ways** to avoid this

1. Using Custom Matchers
   `Matcher allows you to filter Middleware to run on specific paths.`

   ```tsx
   export const config = {
   	matcher: ["/api/:path*", "/"],
   	// matcher: "/api/:path*",
   };
   ```

2. Using Conditional Rendering
   ```tsx
   export default function middleware(req: NextRequest) {
   	//if (req.nextUrl.pathname === "/") {
   	//	requestCount++;
   	//	console.log("Number of Requests", requestCount);
   	//	return NextResponse.next();
   	//}
   	if (
   		req.nextUrl.pathname.startsWith("/") ||
   		req.nextUrl.pathname.startsWith("/services")
   	) {
   		requestCount++;
   		console.log("Number of Requests", requestCount);
   		return NextResponse.next();
   	} else if (req.nextUrl.pathname.startsWith("/admin")) {
   		if (req.body.name !== "Jayant") {
   			return NextResponse.redirect(new URL("/", req.url));
   		} else {
   			return NextResponse.next();
   		}
   	} else {
   		NextResponse.next();
   	}
   }
   ```
   Ref : [Next JS Middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware)
Webinar Cafe
Published: 2024-05-15 14:29:02

Discover [Webinar Cafe](https://webinarcafe.com), your complimentary newsletter and directory featuring upcoming webinars customized to your interests. Join our newsletter or list your upcoming webinar in our directory – all at no charge! Follow us on [twitter](https://twitter.com/jasenf)

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