teleren/devto huggingface dataset:
Find a Corresponding Node of a Binary Tree in a Clone of That Tree
Tags: leetcode, dsa, theabbie
Published: 2022-06-16 23:00:45

Given two binary trees `original` and `cloned` and given a reference to a node `target` in the original tree.

The `cloned` tree is a **copy of** the `original` tree.

Return _a reference to the same node_ in the `cloned` tree.

**Note** that you are **not allowed** to change any of the two trees or the `target` node and the answer **must be** a reference to a node in the `cloned` tree.

**Example 1:**

![](https://assets.leetcode.com/uploads/2020/02/21/e1.png)

**Input:** tree = \[7,4,3,null,null,6,19\], target = 3
**Output:** 3
**Explanation:** In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.

**Example 2:**

![](https://assets.leetcode.com/uploads/2020/02/21/e2.png)

**Input:** tree = \[7\], target =  7
**Output:** 7

**Example 3:**

![](https://assets.leetcode.com/uploads/2020/02/21/e3.png)

**Input:** tree = \[8,null,6,null,5,null,4,null,3,null,2,null,1\], target = 4
**Output:** 4

**Constraints:**

*   The number of nodes in the `tree` is in the range `[1, 104]`.
*   The values of the nodes of the `tree` are unique.
*   `target` node is a node from the `original` tree and is not `null`.

**Follow up:** Could you solve the problem if repeated values on the tree are allowed?

**SOLUTION:**

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
            if not p or not q:
                if p or q:
                    return False
                return True
            if p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right):
                return True
        
        def getTargetCopy(self, original: TreeNode, cloned: TreeNode, target: TreeNode) -> TreeNode:
            nodes = [(original, cloned)]
            while len(nodes) > 0:
                og, cl = nodes.pop()
                if self.isSameTree(og, target):
                    return cl
                if og and cl:
                    nodes.append((og.left, cl.left))
                    nodes.append((og.right, cl.right))
            return None
Remove Duplicate Letters
Tags: leetcode, dsa, theabbie
Published: 2022-06-17 11:30:39

Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.

**Example 1:**

**Input:** s = "bcabc"
**Output:** "abc"

**Example 2:**

**Input:** s = "cbacdcbc"
**Output:** "acdb"

**Constraints:**

*   `1 <= s.length <= 104`
*   `s` consists of lowercase English letters.

**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/)

**SOLUTION:**

    class Solution:
        def removeDuplicateLetters(self, s: str) -> str:
            lastIndex = {}
            for i, c in enumerate(s):
                lastIndex[c] = i
            used = set()
            stack = []
            for i, c in enumerate(s):
                if c in used:
                    continue
                while len(stack) > 0 and s[stack[-1]] > c and i < lastIndex[s[stack[-1]]]:
                    curr = stack.pop()
                    if s[curr] in used:
                        used.remove(s[curr])
                stack.append(i)
                used.add(c)
            return "".join(s[i] for i in stack)
CORS Error in 5 minutes
Tags: webdev, beginners, javascript, tutorial
Published: 2022-12-25 16:42:39

![PAIN](https://images.unsplash.com/photo-1534343133720-0c20dba3a360)


## So What is CORS ?
 
CORS stands for [Cross Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) is mechanism that allows a website on one url to request data from another url . This error has been a pain for both front end and backend developer from start . Your webpage might be trying to fetch data from another url and end up with a error in the console

Trust me sometimes CORS Error is a huge pain for web dev out there :
![apin](https://c.tenor.com/lNVQihuFBvYAAAAC/monkey-computer.gif)

Something like this :


![error](https://i.stack.imgur.com/LY5mG.png)


Well this happen because of the browser's security policy 

## Well what is this policy in simple words :
This policy allows a webpage from its own url but blocks anything from another url unless certain conditions are met.
Well if you open up the devtools you might be able to view the headers of request in which there is a origin header which specifies origin url if that request goes to the server in the same origin then its allowed by the browser 

## What happens when request goes to a different url :
This type of request is known as [Cross Origin Requests](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#:~:text=The%20CORS%20mechanism%20supports%20secure,of%20cross%2Dorigin%20HTTP%20requests.)
After reciving the request by the server it adds a 
``Access-Control-Allow-Origin`` header in the response .

If  `` Access-Control-Allow-Origin `` does not match with ``Origin`` Header then browser prevents the response from being used by the client side app

## So What's the solution ? 
Well we can solve this issue at the backend side . We only need to set backend to respond with the proper header 

If your express.js this issue can be solved using [cors](https://www.npmjs.com/package/cors) module 

Install module by npm :

```
npm i cors
```
Usage :
```
var cors = require('cors') 
```

We can set express js to respond with a proper header with a 1 line middleware code


```
app.use(cors({origin:'http://yourawesomeurl.net'}))
```


When facing a CORS Error 

Step 1 :
Open up network tab of devtools find the response and check for ``` Access-Control-Allow-Origin ```header . If it doesnt exist then you have to enable cors on server side 
other wise the url might be a mismatch 

Well if you dont own the server then you're doomed
![doomed](https://c.tenor.com/JIS_KDKKsgYAAAAd/guaton-computadora.gif)

And thats CORS Error in 5 minutes hope this articles helps you out 





## Conclusion :

Don't Worry Just Stay Awesome :D & Merry Christmas!!

## Keep Coding !!!

## 🙏 Share with your friends on [Twitter](https://twitter.com/intent/tweet?text=%22CORS%20Error%20in%205%20minutes%22%20by%20%40alestor123%20%23DEVCommunity%20https%3A%2F%2Fdev.to%2Falestor_123%2Fcors-error-in-5-minutes-317n-temp-slug-9838531)
Java 8 to Kotlin, Clojure and Java 17 - Part 1 Java 8
Tags: kotlin, java, clojure, refactorit
Published: 2022-06-18 14:10:00

#100DaysOfCode #Java
Implementing java 8 example. BookParser

Next step: move the code to Java 17, then Kotlin and Clojure
https://github.com/jorgetovar/from-java-8-to-java-17-kotlin-clojure/pull/1/files
Reverse Phone API: The Future of preventing fraudulent phone calls
Tags: webdev, javascript, devops, opensource
Published: 2022-06-20 04:32:19

Reverse Phone API is a new and revolutionary way to prevent fraudulent phone calls. This technology allows you to receive real-time alerts when someone tries to call you from a fraudulent or spoofed number. When combined with other security measures, Reverse Phone API can be an incredibly powerful tool in protecting your privacy and preventing fraudsters from getting through to you.

Reverse Phone API helps to prevent fraudulent phone calls by giving real-time alerts when someone tries to call from a spoofed number. [Reverse Phone API](www.numverify.com) is a new phone service that helps to prevent fraudulent phone calls by giving real-time alerts when someone tries to call from a spoofed number. The service is simple: when someone receives a call from a suspected spammer, they can enter the number into the reverse phone API website and receive an instant report on whether or not the number is legitimate. This way, users can avoid being scammed by fake calls, and businesses can protect their customers' information.

This technology can be used in combination with other security measures to further protect your privacy and prevent fraudsters from getting through to you. When it comes to privacy and security, there are a few things more important than keeping your phone number safe. That's why reverse phone API can be such a valuable tool. By using this technology, you can keep your number hidden from public view, making it much harder for anyone to try and fraudulently reach you. And while no security measure is foolproof, combining reverse phone API with other steps (like not sharing your number publicly) can go a long way toward protecting your privacy and keeping you safe from unwanted calls. To know more about it a visit https://numverify.com/
Paracetamol.js💊| #173: Explica este código JavaScript
Tags: javascript, spanish, webdev, programming
Published: 2022-07-22 19:40:27

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
const f = () => {
  let num = 5;
  function g(){
    let num = 10;
    console.log(num);
  }
  g();
}

console.log(f());
```

A. `10`
B. `5`
C. `undefined`
D. `null`

Respuesta en el primer comentario.

---
Roundup of .NET MAUI Videos - Week of June 20, 2022
Tags: beginners, dotnet, programming
Published: 2022-06-27 16:10:50

Another week, and round of new content for .NET MAUI learners! This week I also found content in Dutch, Hindi, Spanish, and Arabic. In no particular order:

## Build Your .NET MAUI Android App with GitHub Actions

{% embed https://youtu.be/GQuQPm40kys %}

## Token Based Authentication

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

## Johnny does DOTNET

{% embed https://youtu.be/qzZdzz0jk6s %}

[Dutch Version](https://youtu.be/xndh-IJyIEg)

## Getting Started

Claudio Bernasconi

Walks you through installation and then updates the template .NET MAUI app to display currency exchange rates from an HTTP request. Jump right into the meat of that below:

{% embed https://youtu.be/pkKwjGWKfco?t=325 %}

## [Hindi] Tutorial for Beginners

{% embed https://youtu.be/mumMwE5H-0I %}

## SignalR Chat App

I haven't had a chance to watch this one, but chat and SignalR with .NET MAUI is a great hook. Will def have to revisit this one.

{% embed https://www.youtube.com/watch?v=r-Rm9YJzE24 %}

## [Spanish] Web, Desktop, and Mobile with Blazor and .NET MAUI

This is a meetup recording of Latino .NET Online featuring this presentation by Jose Columbie.

{% embed https://www.youtube.com/watch?v=9iWS-kShEvM %}

## Local Storage in .NET MAUI

Suthahar Jegatheesan succinctly introduces you to storing data with a variety of options focusing on the Preferences API, and the video has an [accompanying blog](https://www.msdevbuild.com/2022/06/net-maui-store-local-data-with.html).

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

## .NET MAUI AMA with James Montemagno

Does this even need a description? :) 

{% embed https://youtu.be/5cFZJGEmji0 %}

## [Arabic] .NET MAUI Blazor - TabbedPage Navigation

{% embed https://youtu.be/7NaQKkz7MH0 %}
Build and Deploy an ASP.NET Core app in a Docker container
Tags: docker, dotnet
Published: 2022-06-24 06:03:05

.NET is a free, open-source development platform for building numerous apps, such as web apps, web APIs, serverless functions in the cloud, mobile apps and much more. .NET is a general purpose development platform maintained by Microsoft and the .NET community on GitHub. It is cross-platform, supporting Windows, macOS and Linux, and can be used in device, cloud, and embedded/IoT scenarios.

Docker is quite popular among the .NET community. .NET Core can easily run in a Docker container. .NET has several capabilities that make development easier, including automatic memory management, (runtime) generic types, reflection, asynchrony, concurrency, and native interop. Millions of developers take advantage of these capabilities to efficiently build high-quality applications.

## Building the Application

In this tutorial, you will see how to containerize a .NET application using Docker Compose. The application used in this blog is a Webapp communicating with a Postgresql database. When the page is loaded, it will query the Student table for the record with ID and display the name of student on the page.

[Read the Complete Blog](https://www.docker.com/blog/building-multi-container-net-app-using-docker-desktop/)
Password generator in javascript
Tags: javascript, css, html, webdev
Published: 2022-07-31 13:12:21

In this post we are going to make a password generator in javascript

Install uuid

`npm i uuid`

Create a file named index.html, style.css, index.js.

index.html full source code: 

```
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Password Genenrator</title>
  </head>
  <body>
    <h1>Password Generator</h1>
    <input
      type="text"
      id="keyword"
      placeholder="Enter a keyword"
      maxlength="30"
    />
    <button id="generate">Generate Password</button>
    <h3 id="password">
      When you enter a keyword and click the button the password will be
      generated here
    </h3>
    <script src="index.js"></script>
  </body>
</html>

```

style.css full source code:

```
* {
  padding: 0px;
  margin: 0px;
}
h1 {
  text-align: center;
  color: blueviolet;
  font-family: cursive;
}
#keyword {
  width: 1000px;
  height: 35px;
  text-align: center;
  border: 3px solid #111;
  font-family: 'Courier New', Courier, monospace;
  background-color: #333;
  border-radius: 10px;
  color: white;
  margin-left: 150px;
  margin-top: 5px;
}
#generate {
  margin-top: 20px;
  display: block;
  margin-left: 580px;
  border: none;
  background: none;
  font-size: 20px;
  cursor: pointer;
}
#password {
  /*margin-left: 0px;
  margin-right: 0px;*/
  margin-top: 50px;
  text-align: center;
  padding: 20px;
  color: #333;
  font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
  font-size: medium;
  background-color: #f2f2f2;
}
```

index.js full source code:

```
import { v4 as uuidV4 } from 'uuid';
import './style.css';
const keyword = document.getElementById('keyword');
const generate = document.getElementById('generate');
const password = document.getElementById('password');

generate.addEventListener('click', function () {
  if (keyword.value == '') {
    password.innerText = 'Keyword is needed';
  } else {
    const text = `${keyword.value}`;
    const modifiedText = text.replace(' ', '-');
    password.innerText = modifiedText + '-' + uuidV4();
  }
});

document.addEventListener('dblclick', function () {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen();
  } else if (document.exitFullscreen) {
    document.exitFullscreen();
  }
});

```

Live demo: https://passwordgeneratorrishikesh.stackblitz.io/
source code: https://stackblitz.com/edit/passwordgeneratorrishikesh

Thank you!!!
[vue-router] Active route, subpath
Tags: vue
Published: 2022-06-26 18:06:55

Hi all, 

I have the following routes:

```
{ path: '/offers/',                 component: OfferList,           name: 'offerList' },
{ path: '/offers/:id',              component: OfferView,           name: 'offerView'}

```
And the following link:

```
<router-link :to="{ name: 'offerList'}" custom v-slot="{ navigate, href, isActive, isExactActive  }">
      <li class="menu-item" :class="{ 'active': isActive }">
        <a :href="href" class='menu-link'><span>Offres partenaires</span></a>
      </li>
    </router-link>

```
According to the documentation, when I load the offerView url, the router-link should have `isActive == true` but it doesn't

Can you tel me what's wrong with that ?

Thanks
Are you a CMS developer?
Tags: api, cms, headless, jamstack
Published: 2022-06-27 07:56:18

Take part in our 10-minutes CMS survey, get 30$ as voucher, help us understand the importance of CMS for your profession.
[https://relevantive.typeform.com/to/n60EE5Zs?utm_source=devto](https://relevantive.typeform.com/to/n60EE5Zs?utm_source=devto)
How to Install Kubernetes Cluster in Linux
Tags: devops, docker, kubernetes, linux
Published: 2022-06-28 10:51:10

https://www.linuxtechi.com/install-kubernetes-k8s-on-ubuntu-20-04/

refer this link if installation getting  error 
https://github.com/containerd/containerd/issues/6970

do this command solve：
rm /etc/containerd/config.toml
systemctl restart containerd

https://www.howtoforge.com/tutorial/install-laravel-on-ubuntu-for-apache/
Active Record Sessions Additional Functionality
Published: 2022-07-29 20:46:00

For my phase 4 project, my idea was to have a social-media-like app where the user logged in from a specific location. A user's interacting network would be limited to only the location they are logged in from. Because location was part of the login process, the session needed to store location data as well as user data. And then passing this to the client side becomes more difficult since two objects are passed.

To start from the basics, I setup an auto-login route based on the session. I knew this would need to be a custom route, given my output would need to return user data and location data, so I opted to create a custom controller function instead of the standard show function. My GET route in ruby would be:

`get '/me', to:'users#auto_login'`

And my client side would run a useEffect to fetch this route. Now, if I only needed user data, my auto_login function could be:

`
def auto_login
     user = User.find_by(id: session[:user_id])
     if user
          render json: user
     else
          render json: { error: 'User not found'}, status: :unauthorized
     end
end
`

How could I get the location of the last session for the auto-login to function? I'm not passing any parameters at the moment... Location is tied to the User through relationships, but this would give me all locations, not the one of the last session. Currently, my function works because I am able to get the user id from the session data. If I stored the location id to session, I could do the same thing. So I go back to my sessions controller create method.

Nothing too complicated, the same way I stored my user to the session, I will store the location to the session. If the password is authenticated, it will stored the location id from params to session[:location_id]. 

`
def create
        user = User.find_by(username: params[:username])
        location = Location.find(params[:location_id])
        if user&.authenticate(params[:password])
            session[:user_id] = user.id
            session[:location_id] = location.id
            render json: user, status: :created
        else
            render json: { errors: "Invalid username or password" }, status: :unauthorized
        end
    end
`

Now, going back to my UsersController where I have my auto_login method, I am able to get the session location by running:

`
Location.find_by(id: session[:location_id])
`

Now I just need to return both objects to the client. I think the cleanest way would be to create a new, nested object, and then render as json. My final auto_login function is:

`
def auto_login
     user = User.find_by(id: session[:user_id])
     location = Location.find_by(id: session[:location_id])
     if user
          result = {user: user, location: location}
          render json: result
     else
          render json: { error: 'User not found'}, status: :unauthorized
     end
end
`
Templating in SvelteKit
Tags: jamstack, svelte, tutorial, beginners
Published: 2022-08-01 01:40:52

---
canonical_url: https://cloudcannon.com/community/learn/sveltekit-beginner-tutorial/templating-in-sveltekit/
series: SvelteKit Beginner Tutorial
--- 
By [Mike Neumegen](https://cloudcannon.com)

_Brought to you by [CloudCannon](https://cloudcannon.com/sveltekit-cms/), the Git-based CMS for SvelteKit._

In this tutorial we'll go over basic SvelteKit templating concepts and see how you can use templating on your site.

Svelte gives us complete control over how pages and components are rendered. We can loop over content, output variables, run logic statements, or pull in data from external sources. We’ve already encountered some templating — the curly braces `{ }` to output the className in the previous lesson.

## How do I use templating in SvelteKit?

Templating is one of the most common things you’ll be doing in SvelteKit, so let’s go through some examples to demonstrate how it works.

### Output a string

```html
    <p>You can write normal HTML, and when you want to switch to Svelte, 
    you can use single curly braces like this: { "Hello!" }</p>
```

### Output prop value

```html
    <script>
      export let favorite_treat = 'bone';
    </script>

    <p>My favorite treat is a { favorite_treat }</p>
```

### Conditions

```html
    <script>
      export let goodBoy = true;
    </script>

    {#if goodBoy}
      <p>One treat please.</p>
    {:else}
      <p>No treats for me.</p>
    {/if}
```

### Looping

```html
    <script>
      export let whoLetTheDogsOut = [
        'Bryan',
        'Sally',
        'Garry'
      ];
    </script>

    <ul>
    {#each whoLetTheDogsOut as name}
      <li>{name}</li>
    {/each}
    </ul>
```

### Interactive element

```html
    <script>
      let count = 0;

      function handleClick() {
        count += 1;
      }
    </script>

    <button on:click={handleClick}>
      clicks: {count}
    </button>

    <!-- When you click the button it will run the handleClick function
    and live update {count} -->
```

That gives you some of the basic tools to play with. You’ll be using these concepts over and over again through your SvelteKit journey.

## Putting it all together

We’ve seen a lot of different concepts here. Let’s put it into practice by adding a footer to the website the date and time the page was rendered.

First, we’ll create a component for the footer. Create `/src/lib/Footer.svelte` with the following content:

```html
    <script>
      let now = new Date();
    </script>

    <footer>
      Website was generated { today }
    </footer>
```

Just like we did earlier, now we can import `Footer` into our layout and render the component:

```html
    <script>
      import Nav from '$lib/Nav.svelte';
      import Footer from '$lib/Footer.svelte';
    </script>

    <h1>Svelte's space</h1>
    <Nav className="alt" />

    <slot></slot>

    <Footer />

    <style lang="scss">
        :global(body) {
        width: 400px;
        margin: 0 auto;
        font-family: sans-serif;
      }
    </style>
```

## What’s next?

Let’s put our templating knowledge to the test by creating a blog.