teleren/devto huggingface dataset:
LeetCode #1 Two Sum with JavaScript
Tags: javascript, leetcode, algorithms
Published: 2023-01-12 00:04:42

Solutions to LeetCode's [1. Two Sum] (https://leetcode.com/problems/two-sum/) with JavaScript.

Solution 2 also addresses the following follow-up.
**Follow-up: Can you come up with an algorithm that is less than O(n^2) time complexity?**

An easy one to come up with is a nested for loop.

## Solution 1: Nested for loop
``` js
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const twoSum = (nums, target) => {
  for (let i = 0; i < nums.length; i++) {
    for (let j = i + 1; j < nums.length; j++) {
      if (nums[i] + nums[j] === target) {
        return [i, j];
      }
    }
  }
};
```
- Time complexity: O(n^2)
- Space complexity: O(1)

This solution has O(n^2) time complexity because of nesting loops, so I want to find another way.

## Solution 2:Using object
```js
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
const twoSum = (nums, target) => {
  const hash = {};
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (hash[complement] !== undefined) {
      return [i, hash[complement]];
    }
    hash[nums[i]] = i;
  }
};
```
- Time complexity: O(n)
- Space complexity: O(n)

Store the nums value in the keys of the hash and the index in the value.
```js
hash[nums[i]] = i;
```
Then, in each loop, check whether the target minus the nums value exists in the hash.
If it exists, it returns the index of the current loop and the value of the matching hash (index of the stored nums).
```js
const complement = target - nums[i];
if (hash[complement] !== undefined) {
  return [i, hash[complement]];
}
```

In many cases, we want to avoid Time complexity: O(n^2), so I think solution 2 using hash is better.
XRPL Mementoes
Tags: nft, xls20, xrpl, xrp
Published: 2023-01-12 00:02:18

2022 was an exciting year for the XRP Ledger community, as a proposal to add a new functionality, XLS-20, was successfully voted on and implemented. This proposal allows for the minting and trading of non-fungible tokens (NFTs) on the ledger, enabling digital collectibles to exist alongside other forms of tokenized assets. To celebrate this milestone, a group of XRP Ledger developers and advocates created a series of collectibles to commemorate important moments in the history of the ledger.

A first batch of these collectibles celebrates the launch of XLS-20 itself. 32 NFTs were minted and distributed to attendees and organizers of the XRPL Zone event in London.

You can see them and trade them on xrp.cafe https://xrp.cafe/collection/mementoes

XRPL Zone is an initiative to gather community members and projects to learn from each other and build innovative prototypes using XRPL. At the London event, the community discussed the XLS-20 standard and exchanged ideas about how to grow the NFT ecosystem on the XRP Ledger. The minted collectible  features the artwork of Chef Cecy, a prominent creator in the XRP Ledger and WEB3 communities.

We are excited to see continued innovation and developments on the XRP Ledger and look forward to capturing more of these important moments as NFTs in the future.
What is the best solution to host a simple JSON and fetch it for free?
Tags: discuss
Published: 2023-01-11 23:55:50

---
title: What is the best solution to host a simple JSON and fetch it for free?
published: true
tags: discuss
---

I'd like to host a simple JSON (which I will probably change only 2 or 3 times a year manually) and have a fetch endpoint to retrieve it in my app.

What would be the best solution out there for this case without maintaining my own server?

Free options are even better
Mejoras en las tablas
Tags: filament, php, table, tips
Published: 2023-01-11 22:53:16


## Algunas mejoras en las listas de Filament.

### Description (o linea adicional en la celda) 

```php
 Tables\Columns\TextColumn::make('name')->searchable()->sortable()->wrap()
                ->description(fn (Repository $record): string => $record->institution->name??'')

```

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

### Badges (distintivo) en campo de tipo texto

```php
//campo type tiene varios valores definidos en un array (ojs->OJS, etc) 
Tables\Columns\BadgeColumn::make('type')->enum(Repository::$typesform),
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8j5qneesz8sucmhgm9lk.png)

### Ocultar columnas 

con el método ->toggleable(isToggledHiddenByDefault: true) se puede ocultar la Columna y luego activarla desde el ícono de la derecha.

### Actualizar valor desde la tabla

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

Con el método action se puede disparar una actualizacion en la celda. 

```php
    ->action(function($record, $column) {
        $name = $column->getName();
        $record->update([
            $name => !$record->$name
        ]);
    });
```
### Definir orden default

```php 
// en la definición del recurso 
protected function getDefaultTableSortColumn(): ?string
        {
            return 'id';
        }
        
    protected function getDefaultTableSortDirection(): ?string
        {
            return 'desc';
        }
```

### Enlazar a otro modelo 
Se puede crear una macro en el método Boot de AppServiceProvider y enlazar entre modelos usando la función linkRecord luego. [Fuente](https://filamentphp.com/tricks/link-to-related-model-from-table) (el modelo dependiente está conectado al modelo institution con la columna name)
en lugar de 
```php
Tables\Columns\TextColumn::make('institution.name')
->url(fn (Library $record): string => route('filament.resources.institutions.view', ['record' => $record->institution_id]))
```
Se puede usar 

```php
Tables\Columns\TextColumn::make('institution.name')->linkRecord('view')

```
PHP-like namespaces in JavaScript using Unicode identifiers + variadic function (2.2 ed.) | 2024 revision
Tags: programming, computerscience, php, javascript
Published: 2023-01-11 22:25:01

 Using unicode ["U+3035"](https://unicodeplus.com/U+3035) i.e. "vertical kana" symbol that bears resemblance to `\` i.e. backward slash we can produce something like this :

**Example 1**
```js
〵App〵Console〵Logger = console.log
〵App〵Console〵Logger("Hello World") // "Hello World"
```

**Example 2**
```js
〵Window〵document = window.document // # ~ one-line
// # ~ multiple-line
〵WindowBase = window 
〵Document = document
〵WindowBase .〵Document // # PAY ATTENTION at dot (.) between "namespaces"
```

User defined snippet 

> **How to**: write one of the prefixes in your IDE .js |.ts files e.g. kana and press tab (make sure `"editor.tabCompletion": "on"`)
```js
{
	// @https://code.visualstudio.com/docs/editor/userdefinedsnippets
	// Place your global snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and 
	// description. Add comma separated ids of the languages where the snippet is applicable in the scope field. If scope 
	// is left empty or omitted, the snippet gets applied to all languages. The prefix is what is 
	// used to trigger the snippet and the body will be expanded and inserted. Possible variables are: 
	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. 
	// Placeholders with the same ids are connected.
	"namespace_seperator_javascript": {
		"scope": "javascript,typescript",
		"prefix": ["sep", "kana", "js-namespace", "ts-namespace"],
		"body": [
			"〵$0"
		],
		"description": "JS, TS friendy unicode-based namespacing-like char"
	}
}
```

Practical example – variadic function returning value of single type (filter_-ish_) function :

{% embed https://replit.com/@projektorius96/variadic-fnjs %}

If you think it could be applicable, use it !

Cheers !
What is Callback Hell?
Tags: callback, javascript, callbackhell, beginners
Published: 2023-01-11 22:16:42

📌 Before understanding what callback hell is, make sure to get familiar with the [callback](https://dev.to/catherineisonline/javascript-callbacks-24cp) first.




In programming, callback hell refers to an ineffective way of writing asynchronous code. It takes place when you nest functions and create too many levels of nesting. This makes it harder to control access to the specific function and it becomes harder to debug the issues.
Nesting means placing one function in another, then placing the third function in the second, then the fourth in the third one, and so on. By placing callback in the callback and callback in the callback, with more complex applications callback logic might get too messy! This type of nesting visually looks like a pyramid which is why callback hell is also called a pyramid of doom. 👹


Let’s remember what the callback function is in action while we prepare some Italian Moka coffee.

**Buy some coffee before filling the boiler**

![Buy some coffee before filling the boiler](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vaj1528xx8e87zqrtmdd.png)

**Fill the boiler before filling the funnel**

![Fill the boiler before filling the funnel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2an8xpb77rxa1gassg9.png)

**Fill the funnel before placing the pot on stove**

![Fill the funnel before placing the pot on stove](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bcs718asotovzrizu1j1.png)

**Place the pot on the stove before removing it**

![Place the pot on the stove before removing it](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trxktk92pe36d1tg82bq.png)

**Remove the pot before pouring coffee**

![Remove the pot before pouring coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00tlc7jfoi3xo0zgqgmj.png)


There you go, we made some coffee by using a callback function named nextAction in each of the functions. So each step will lead to the next, then to the next and so on - one actions will not start until the previous one is done.

But what if I start preparing some salad where I have to go though 10x more steps? And what if I want to prepare soup as well? And maybe some more meals because of I have many guests?

That’s why I will wrap all actions into one function and delegate this function task to my husband -  so everything will be done by only him.


![Callback hell](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lot3o9txl0tkepza9h3g.png)
 


And here we got some callback hell where **finalStep** is nested inside **startPreparing** which is nested instead **prepareFunnel** which is nested inside prepareBoiler which is nested inside **prepareMoka**… And things can get even worse sometimes!

As a beginner, you might not stumble upon a callback hell anytime soon however do not fret! Once you do, as long as you know what it is you will be partly prepared. There are some ways to avoid this which I will explain later. For now, enjoy some coffee! ☕️




📌 Enjoyed the post? Please let me know in the comment down below!
JWT Authentication Using Express.js & MongoDB With TypeScript
Tags: typescript, javascript, mongodb, node
Published: 2023-01-11 21:57:49

# Auth-TS

JWT Authentication Using TypeScript, Express.js, & MongoDB

## Features:

- Authentication

## Technology Stack:

- TypeScript
- Node.js
- Express.js
- MongoDB
- JWT

## Default urls:

- Login User : POST METHOD <br/>
  localhost:5000/api/auth
- Register User : POST METHOD <br/>
  localhost:5000/api/auth/register
- Get All Users : GET METHOD <br/>
  localhost:5000/api/auth/

## Usage

### Env Variables

Create a .env file in then root and add the following

```
PORT = 5000
MONGO_URI = your mongodb uri
JWT_SECRET = 'abc123'

```

## Install Dependencies

```
npm install

```

## Run App

```

# Run in dev mode

npm run server

```

- Version: 1.0.0
- License: MIT
- Author: Said Mounaim

Github Repo: https://github.com/saidMounaim/Auth-TS

For more projects, see my Github Profile
https://github.com/saidMounaim
How to translate web page titles with Angular
Tags: typescript, angular, webdev, tutorial
Published: 2023-01-11 21:53:39

Since Angular 15 we have the possibility to modify the title of the page from the routing. It is as simple as doing the following:

```typescript
const routes: Routes = [
	{
		path: 'login',
		component: LoginComponent,
		title: 'Login'
	}
];
```

It is a very comfortable way of giving a title to any page of our project and being able to know where you were when we changed tabs in the browser. What if we want to translate the title?

The best way is to create a resolver. What is an Angular resolver?
A resolver allows us to get data before navigating to the new route.

To make a resolver we have to implement the Resolve interface. We also need a service to translate our translations keys, in this case I am using the package **@ngx-translate/core**

**custom-title.resolver.ts**
```typescript
import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';

@Injectable({ providedIn: 'root' })
export class CustomTitleResolver implements Resolve<string> {
	constructor(
		private _translateService: TranslateService,
	) {}

	resolve(route: ActivatedRouteSnapshot): Promise<string> {
		if (!route.data.titleKey) {
			return Promise.resolve('Default title');
		}

		return Promise.resolve(
			this._translateService.instant(route.data.titleKey)
		);
	}
}

```

Now we go back to our routing file, we add the resolver and we have to pass the key of our translation. It will look like this:

```typescript
const routes: Routes = [
	{
		path: 'login',
		component: LoginComponent,
		title: CustomTitleResolver,
		data: { titleKey: 'Login'}
	}
];
```

With all this, we now have a way to translate all the titles of our application, we just have to add the Resolver and the translation key to each of the routes. I hope it helps you, regards.
OOP; NOW I (kind of) get it
Tags: beginners, java
Published: 2023-01-11 21:50:21

I followed a tutorial to build a rudimentary mortgage calculator. It has objects and methods, which makes it OOP, right?

**Wrong**

Method A calls method B which calls method C... etc; which is procedural programming. Apparently, typing lines of code into IntelliJ does not qualify as Object Oriented Programming.  

This tutorial is having me refactor so that I have a single class dedicated to handling input, a separate class for doing math and a whole other class that handles displaying data. 

My brain hurts. I'm going to spend an extra day with this tutorial. This puts me a day behind schedule, but I'm not moving on without solidifying this concept.

98
Switch to Older PHP versions with Laravel Valet
Tags: php, laravel, webdev
Published: 2023-01-11 21:44:34

## The problem

Laravel Valet currently support PHP 8 and higher versions (8.1, 8.2), but if you try to switch from PHP 8.1 to PHP 7.4 for a legacy project (as an example) it would be a headache.

The problem would be, when you need to return to an updated PHP version... there would start the real mess...

## Solution

Lets supposed that we are currently in PHP 8.1 version, then to work on a legacy project you would require to switch to PHP 7.4 as an example:

```php
valet use php@7.4 
```

It would work, then to return to an updated PHP version (8.1 or 8.2), you would face an issue if you try to switch back with this command:

```php
// use to work with the most recent version
valet use php
```

## Fix the issue and go back to the most recent PHP version:

This command would unlink all 7.x versions, (but you can unlink only a specific one):

```php
brew unlink php@7.0 php@7.1 php@7.2 php@7.3 php@7.4
```

Install the most recent PHP version, (if the system does not have it):

```php
brew install php
```

Then it would link the most recent PHP version

```php
brew link php
```

If this last command does not work, you can use some flags to force it:

```php
brew link --force --overwrite php
```

Then just instruct Valet to use the most recent PHP version:

```php
valet use php --force
```


Hope it helps and thanks for reading, happy coding!
Retro Computing is Fun
Tags: retrocomputing, programming, basic, retro
Published: 2023-01-11 21:42:29

About a year ago I started a [retrocomputing newsletter/blog](https://www.goto10retro.com) that I call [Goto 10](https://www.goto10retro.com).

That is of course a play on the old-school BASIC programming languages that I used when first learning how to code. The canonical program is:

`10 PRINT "HELLO"
20 GOTO 10`

Not all the posts there are about software development or programming, but several of them have been about using BASIC or Pascal.

If you're interested in this sort of thing, I encourage you to check it out at:

[https://www.goto10retro.com](https://www.goto10retro.com)

Here are some posts that you might find interesting:
* [Archimedes Spiral in BASIC](https://www.goto10retro.com/p/archimedes-spiral)
* [Programming Pascal on the Atari ST](https://www.goto10retro.com/p/jumpstart)
* [Dragon and Snowflake Fractal Sweeps in BASIC](https://www.goto10retro.com/p/fractal-sweeps)
* [My First BASIC Programs](https://www.goto10retro.com/p/first-basic-programs)
* [Atari Painter in BASIC](https://www.goto10retro.com/p/basic-painter)
* [Pumpkin Man: A Simple BASIC Game](https://www.goto10retro.com/p/pumpkinman-a-simple-basic-game)
* [Drawing a Spiral in BASIC](https://www.goto10retro.com/p/drawing-a-spiral-in-basic)
* [Advent of Code 2022 in BASIC](https://www.goto10retro.com/p/advent-of-code-2022-in-basic)
* [BomBer: A BASIC Game](https://www.goto10retro.com/p/bomber-a-basic-game)
Day 5: The three steps to rapidly validate your startup idea on a shoestring budget.
Tags: startup, writing, productivity
Published: 2023-01-11 21:22:46

3 steps to validate your startup like a pro:

1) Build a landing page: use it to assess the general interest in your product.

2) Build a protoype: give your customers something that helps them

3) Engage your customers: get feedback, and see where to improve

---

## The significance of validating your idea

When developing your startup, validating your idea as soon as possible is critical!

Otherwise, you may spend time and money developing your product only to discover that there is no need for it and that no one wants to buy it.

Fortunately, you can easily create everything you need to validate your idea in a single day.

## Step 1: create a landing page.

Your landing page will be your customer's first contact with your product, your product's face, and your most important marketing tool.

As a result, creating a landing page for your product should be your priority. Use it to explain the concept behind your product, what problems it solves, and how much it costs.

Then include a Call to Action to encourage people to sign up for your product. The best part is that you don't need a working product; simply use the landing page to assess general interest.

With a website builder, you can easily create a landing page in an hour, allowing you to get your idea out there as soon as possible.

## Step 2: Create a simple prototype.

After your landing page has given your idea some traction, it's time to create a prototype for your customers.

You don't need a finished product at this stage, but it should be usable, solve the customers' pain points, and provide general value.

You can use no-code or low-code tools to create a prototype quickly. They enable you to quickly create a basic product without needing a developer.

At this stage of the product, another option I've seen is to do basic tasks by hand. Do whatever works best for your product.

## Step 3: solicit feedback and iterate

Once you've gotten your first customers, it's time to gather feedback and improve your product.

Look at what parts of your applications your users enjoy. Is one feature used twice as much as others? Enhance it or make it easier to access. Is there a pattern of complaints? You now know what you should work on next.

Having a close relationship with your customers at this point may convert them into loyal fans of your product. They will then provide additional ideas and even discuss your product with others.

Simply put, engage with your customers. After all, they are the most likely to know what they think about your product.
How I schedule my blogs
Published: 2023-01-11 21:01:18

## For those who are curious, here is how I will be scheduling my blog. 

Every Saturday, I will have a blog post up, It will either be one of my series like 52 weeks, or some one off blog on productivity for example. 

Throughout the week I will have these little discussion panels, really I just want to get to know my community more. 

If you have any blog recommendations put them in the comments. 

Also, thank 53 followers, and granting me nearly 1000 views, I have only been on this platform for 12 days so it's kinda insane. 

ps. Would you all like a blog on how I organize all my blogs in notion?
Strategy Design Pattern
Tags: webdev, designpattern, patternstrategy, loosecoupling
Published: 2023-01-11 20:43:49




Strategy Pattern

> “Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. ”

_Design Patterns: Elements of Reusable Object Oriented Software_

The 3 attack() methods represents a family of algorithms. Each algorithm is encapsulated in an independent class. 
The 3 classes implement the IWeapon interface, which is what renders the algorithms interchangeable.
The class StarwarsCharacter by using the IWeapon Interface it could access any algorithm without depending on the class.

This design is very powerful, it makes it possible to add algorithms as you go when needed without altering any existing code.

![Design pattern Strategy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aov19kl6ji2tjv05u3n9.png)

So in case the character is a Clone they could attack using a Blaster and if it is a Jedi they could attack using a Lightsaber. 

But what if it is Chewbacca ? 

In this case all we have to do is add a new class Bowcaster that implements the IWeapon Interface and overrides the method attack().

![Design pattern Strategy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zf4lsytpryhfbr9u7l2.png)

And now Chewbacca could use his Bowcaster.


![strategy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4td6blxyw8mko30g3uy.png)

Link to the source code

{% embed https://github.com/leriaetnasta/Strategy-Design-Pattern %}
Surprises when taking screenshots
Tags: webdev, windows, icc
Published: 2023-01-11 20:34:31

I was recently generating data and storing it into image RGB channels. My favorite "debugging" tools for this task are `Shift+Alt+S` and [paint.net](https://www.getpaint.net/). Feeding my despair, values in Color Picker were always off. After spending 3 hours triple checking my vector math that generated data, I decided to "Save images as...", opened it, and everything was correct. It was time to figure out what was going on with the rendering in the browser.

I created a completely green image, and in the table you can see what I expected when I took the screenshot and what I actually got.

 | Image | CSS `background`
--- | --- | ---
Expected (paint.net) | 0, 255, 0 | 0, 255, 0
Chrome and Edge | 34, 255, 42 | 34, 255, 42
Firefox | 32, 255, 39 | 0, 255, 0
Windows Photos | 32, 255, 39 | n/a

It is quite simple, I have a custom ICC profile for the main screen. In my mental model, this kind of post-processing should be happening OS wide in compositor, so screenshots are not affected (similar to Night light).

![My mental model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n7nj1517fmlkrt19z93q.png)

The reality is, every application is responsible to be color space aware individually. Browsers are aware, although for some reason colors in Chrome are different, Firefox applies it only to images.

Right now, I'm using a flag that forces Chrome to render in sRGB.

![Force color profile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rogupdu8shyl7o3mj1ji.png)