teleren/devto huggingface dataset:
SamGIS - Alcuni appunti su Segment Anything
Tags: python, computervision, machinelearning, maps
Published: 2024-05-27 18:27:17

# SamGIS - Alcuni appunti su Segment Anything

Rimando alle mie note in inglese su [Segment Anything](/projects/notes-about-segment-anything).

## A proposito del riutilizzo degli embedding delle immagini e SamGIS

Dopo aver riletto questo paper ho capito che avrei potuto migliorare l'efficienza di SamGIS conservando e riutilizzando gli embedding delle immagini.

Ho implementato questa modifica in [SamGIS versione 1.3.0](https://docs.ml-trinca.tornidor.com/#version-1-3-0). Alcuni dati di test dalla [demo SamGIS](https://huggingface.co/spaces/aletrn/samgis) che ho utilizzato:

- prima chiamata: 5.42s
  - modello [fastsam](https://github.com/CASIA-IVA-Lab/FastSAM) istanziato
  - immagine creata dalla mappa web (uso OpenStreetMap come tile provider e Mapnik come layer della webmap)
  - creato il embedding dell'immagine
- seconda chiamata: 0,41 s
- dalla terza alla settima chiamata: ~0,34s

Si tenga presente che effettuando una chiamata immediatamente dopo l'altra la durata rimane bassa, probabilmente a causa dell'utilizzo della cache durante il download delle tile nel back-end. Aspettando più di 10 minuti sembra invalidare la cache, quindi [contextily](https://github.com/geopandas/contextily) (la libreria di GeoPanda che utilizzo come client di Tiles) ha impiegato da 0.5s a 1.5s di tempo, durante le mie prove, per il download delle tile.

<details>
    <summary><i>Espandere qui per il dettaglio del payload delle chiamate di test.</i></summary>

```json
{
    "bbox": {
        "ne": {
            "lat": 46.236615111857255,
            "lng": 9.519996643066408
        },
        "sw": {
            "lat": 46.13405108959001,
            "lng": 9.29821014404297
        }
    },
    "prompt": [
        {
            "id": 146,
            "type": "point",
            "data": {
                "lat": 46.18483299780137,
                "lng": 9.418864745562386
            },
            "label": 1
        }
    ],
    "zoom": 13,
    "source_type": "OpenStreetMap"
}
```
  
</details>

## A proposito della conversione "dal testo alla maschera" "zero shot": LISA e SamGIS

La versione originale di SAM può utilizzare anche semplici prompt testuali in linguaggio naturale. Per un uso pratico di questa funzionalità, si veda:

- [Grounded-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything)
- [LISA](https://github.com/dvlab-research/LISA)

Naturalmente potrebbe interessare anche il mio [lavoro di integrazione di LISA con SamGIS](https://trinca.tornidor.com/projects/lisa-adapted-for-samgis) e la corrispondente [demo](https://huggingface. co/spaces/aletrn/samgis-lisa-on-cuda). Devo tenerlo in pausa a causa dei costi, ma sto richiedendo l'uso di una GPU gratuita da HuggingFace.

Nel caso il mio [progetto](https://huggingface.co/spaces/aletrn/samgis-lisa-on-cuda) fosse interessante, metti "mi piace" o commenta il [thread di richiesta di risorse GPU di HuggingFace](https://huggingface.co /spaces/aletrn/samgis-lisa-on-cuda/discussions/1).
Javascript Coercion Corner Cases
Tags: webdev, javascript, programming
Published: 2024-05-27 18:22:39

Like any other language, JavaScript also has some corner cases, so it is a good idea to learn them. today I want to show you a corner case about auto coercion.
```
1 < 2 < 3 // true
```
In this code the answer is true. but how let's check it step by step.
```
step 1 -> (1 < 2) < 3  
step 2 -> (true) < 3
step 3 -> 1 < 3 // true
```

In this case, the answer becomes true by chance.
let's check another one
```
3 > 2 > 1; // false
```

Mathematically this should be true but the execution says it is false lets check the code step by step
```
step 1 -> (3 > 2) > 1
step 2 -> (true) > 1
step 3 -> 1 > 1 // one is not bigger than one so should be false
```

Whenever you do any calculation please keep in mind the auto coercion. because math and code do not always say the same thing
VanillaJS Lazy Load images/video/embed/youtube
Published: 2024-05-27 18:18:59

DEMO - https://codepen.io/ktr92/pen/qBGqRgZ

html example

```
<img data-src='https://placehold.co/600x400'>
<iframe width="560" height="315" data-src="https://www.youtube.com/embed/NpEaa2P7qZI?si=4Rq1E37zRobyhGRI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
```

JS

```
function lazyLoadSrc(selector) {
  const callback = (entries, observer) => {
    entries.forEach(entry => {
      const source = entry.target
      if (entry.intersectionRatio > 0) {
        if (!source.getAttribute('src')) {
            source.setAttribute('src', source.dataset.src)
            observer.unobserve(source)
        }
      }
    })
  }
  const target = document.querySelectorAll(selector)
  const options = {
    threshold: 0.4
  }
  let obs = new IntersectionObserver(callback, options)
  target.forEach(item => {
    obs.observe(item)
  }) 
}
```

```
// usage
document.addEventListener('DOMContentLoaded', function() {
  lazyLoadSrc('img');
  lazyLoadSrc('iframe');
})
```
Episode 24/21: Angular 18
Tags: webdev, javascript, programming, angular
Published: 2024-05-27 18:07:56

Angular 18 is out. For the first time, the main feature is an experimental one: the zoneless mode.

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

Until Angular 17, zone.js triggered Change Detection, which updates the DOM. Starting from Angular 18, we have a second trigger: the function `markForCheck()`, which runs automatically within the `async` pipe or when a Signal's value changes. That Signal must be used inside a template.

There are also other occurrences for `markForCheck()` like immutable property binding or handled DOM events.

`markForCheck()` triggering the Change Detection is not experimental but stable. It is a breaking change because the Change Detection might now also be triggered outside of zone.js.

Although that is a rare use case, we can also re-introduce the behavior as before via `provideZoneChangeDetection({ignoreChangesOutsideZone: true})`.

What is experimental, though, is that you can disable zone.js at all and only rely on `markForCheck()`.

That is done via `provideExperimentalZonelessChangeDetection()`.

---

Other features include the "Event Replay", which is important for server-side rendering. When the application hasn't hydrated, i.e. Angular hasn't been loaded yet, and users start clicking around, those events will be replayed after hydration.

`provideClientHydration(withEventReplay())`

---

The `redirectTo` property in the Router configuration accepts, next to the existing string, now also a function. That means, when logic is required for the redirection, one doesn't have to fallback to router guards.

```typescript
export const routes: Routes = [
  {path: '', component: HomeComponent},
  {
    path: '**',
    redirectTo: () => isNight() ? '/404-night' : '404-day'
  }
];
```

---

`<ng-content>` accepts a default value. It is actually very straightforward 😄:

```html
<ng-content>Nothing to see here :) </ng-content>`
```

---

`FormGroup`, `FormArray`, and `FormControl` expose an `events` property, which provides all important events as an `Observable`:

```typescript
export class AppComponent {
  name = new FormControl("", {validators: [Validators.required]})

  constructor() {
    this.name.events.subscribe((event: ControlEvent) => {
      if (event instanceof StatusChangeEvent) {
        console.log('status changed');
      }
      else if (event instanceof ValueChangeEvent) {
        console.log('value changed');
      }
      // ...
    })
  }
}
```

---

A lot of features, like `@defer`, `@if`, `@for` are now stable (`effect()` is still in developer preview).

According to Alex Rickabaugh, tech lead of the framework, we can expect new features in the next versions as well.

For more information, check out the various videos, blog posts from the community, and the official channels. 

**Angular 18 Release - Developer Event**

{% embed https://youtu.be/DK8M-ZFjaMw?si=svpiO2oh3Z10iIVq %}

**Official Blog Post**

{% embed https://blog.angular.dev/angular-v18-is-now-available-e79d5ac0affe %}
Javascript Boxing and Unboxing
Tags: javascript, webdev, programming
Published: 2024-05-27 18:03:59

## Boxing

Javascript primitive data types are not an object so it shouldn't have methods and properties right?

Did you know that number and string primitive values can act like reference types so we can use methods and properties with them?

By default when we run the javascript objects inside of the `__proto__` and we can use them in our code.
some of the objects inside are `String` and `Number` 

Whenever we want to use methods or properties on primitive types:
- if the type is a string  it will wrap it with the String object from proto
- if the type is a number  it will wrap it with the Number object from the proto

This is called auto-boxing, think of the objects as a big box and we put primitive types as small boxes inside of the objects so we can use all the methods and properties.

For some reason, we can use methods and properties with primitive types. The reason is called boxing and it is automatically applied to primitive types.

```
var car = "ford";

console.log(car);
car.length // 4
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/870ngfxwea8019d42ivw.png)

In this case, the type of the car is a string which is a primitive type
in the console.log(car) everything will be normal.
but in the next line we are using a method that only reference types have so behind the scenes javascript will put this variable inside of the String object from proto so we can access to the methods.

---
## UnBoxing

```
{a : 4} > {a : 5}
```
In this case, when we want to compare two objects we can't do that. we can only compare primitive types. 

To do this calculation we need to convert them to the primitive types. for this, we have a method which is ToPrimitive(). it will call this method default to convert them to primitive types.

So behind the scenes, the calculation will be like this 
```
ToPrimitive({a:4}) > ToPrimitive({a:5})  //false
```

Since we are converting reference types to primitive types that called un-boxing.
Explore National Highways & Motorway Police Jobs 2024
Published: 2024-05-27 17:58:13

dvantages of a Career with NHMP
Stability and Benefits: A career with the National Highways & Motorway Police (NHMP) offers unparalleled **[job](https://jobs2i.com/explore-national-highways-motorway-police-jobs-2024/)** security, a hallmark of government employment. Employees enjoy a range of benefits including pensions, healthcare, and housing allowances, ensuring a stable and secure future.

Career Growth: The NHMP is committed to the professional growth of its employees. With clear paths for promotion and advancement, individuals have the opportunity to rise through the ranks and achieve their career goals.

Professional Training: NHMP provides comprehensive training programs designed to enhance the skills and knowledge of its personnel. This continuous learning environment fosters expertise in various aspects of law enforcement and traffic management.

Service to the Nation: Perhaps the most rewarding aspect of working with the NHMP is the chance to serve the community. Employees take pride in their contribution to public safety, making a tangible difference in the lives of citizens every day.

Job Openings In 2024
The National Highways & Motorway Police (NHMP) has released a comprehensive list of job openings that reflect the diverse roles within the organization. These positions range from administrative support to active field duties, each contributing uniquely to the operations of the NHMP. The significance of these listings lies in their potential to attract a wide array of talents, essential for the multifaceted responsibilities of highway and motorway management.

Patrol Officer
Patrol Officers are the dynamic force of the NHMP, ensuring compliance with traffic laws and safety on the highways. They serve as first responders to incidents, providing aid and managing emergencies. Their role demands physical fitness, keen observation, and a commitment to public service.

Requirement	Description
Education	Intermediate, FA/FSc, Valid Driving License
Salary	40,000 – 75,000
Age Limit	Specified as per job criteria
Location	Various regions across Pakistan
Last Date to Apply	May 31, 2024
Terraform pipeline (IaC for AWS)
Tags: aws, devops, automation, iac
Published: 2024-05-27 17:42:57

## Automating Infrastructure Deployment for Static Websites with Terraform in AWS

**We'll leverage Terraform, an infrastructure as code (IaC) tool, to orchestrate the process. Here's a breakdown of the key steps involved:**

**1. Terraform Setup:**

Ensure Terraform is installed and configured locally.

**2. Configuring the AWS Provider:**

Terraform requires an AWS provider configuration file specifying the region and credentials for provisioning resources. We will create a **provider.tf** file for this. 

**3. Defining the VPC Network:**

We'll define the Virtual Private Cloud (VPC)in the **vpc.tf** file where the server on the EC2 instance will reside. This includes creating a public subnet for internet access.

Creating Internet Connectivity and Security:

An internet gateway is established (in **network.tf**) to enable internet access for the VPC. We'll also define a custom route table and associate it with the public subnet for proper routing. Finally, a security group is created to control inbound and outbound traffic for the Jenkins EC2 instance.

**4. Building the Terraform Configuration:**

The core Terraform configuration file (**main.tf**) defines the provisioning of our EC2 instance with through a user data script. Additionally, it creates an S3 bucket for hosting the static website and configures it for website hosting.

**5. Terraform Workflow:**

Once the configuration is complete, we'll use Terraform commands to initialize, plan, and apply the changes. This will provision the resources in our AWS environment.

`terraform init
terraform plan
terraform apply `


![terraform init](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7t3xe647pl3s42ly8oeh.png)


![terraform plan](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9m3848o6b0ovjgekoygx.png)



![terraform apply](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xyka30u61tcxtdm82s0g.png)


![terraform destroy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ut4hmzv7c8xlvufjg1mh.png)

**6. Validating Resources (Optional):**

You can now validate the created AWS resources like the EC2 instance, security group, VPC, and S3 bucket to ensure everything is set up correctly.
Learn SwiftUI (Day 8/100)
Tags: swift
Published: 2024-05-01 14:32:59

## Swift

* functions with throw Exceptions

```swift
import Cocoa

enum PasswordError: Error, LocalizedError {
    case TooShort
    case Obvious
    
    var errorDescription: String? {
        switch self {
        case .TooShort:
            return NSLocalizedString("Password is too short", comment: "Too short")
        case .Obvious:
            return NSLocalizedString("Password is too obvious", comment: "Obvious")
        }
    }
}

// although defined with `throws`,
// this function doesn't have to throw an exception
func checkPassword(_ pwd: String) throws -> Bool {
    if pwd.count < 6 {
        throw PasswordError.TooShort
    }
    if pwd == "123456" {
        throw PasswordError.Obvious
    }
    return true
}

do {
    let ok = try checkPassword("hello")
    print(ok)
} catch {
    print("Error happened: \(error.localizedDescription)")
}

// ## Checkpoints

/*
 write a function that accepts an integer from 1 through 10,000, and returns the integer square root of that number. That sounds easy, but there are some catches:

 You can’t use Swift’s built-in sqrt() function or similar – you need to find the square root yourself.
 If the number is less than 1 or greater than 10,000 you should throw an “out of bounds” error.
 You should only consider integer square roots – don’t worry about the square root of 3 being 1.732, for example.
 If you can’t find the square root, throw a “no root” error.
 */

enum RootError: Error, LocalizedError {
    case outOfBounds
    case noRoot
    
    var errorDescription: String? {
        switch self {
        case .outOfBounds:
            return NSLocalizedString("Out of Bounds", comment: "OOB")
        case .noRoot:
            return NSLocalizedString("No root", comment: "NR")
        }
    }
}

func sqroot(_ num: Int) throws -> Int {
    if num < 1 || num > 10_000 {
        throw RootError.outOfBounds
    }
    for i in 1...100 {
        if i * i == num {
            return i
        }
    }
    throw RootError.noRoot
}

do {
    print(try sqroot(9))
    print(try sqroot(25))
    print(try sqroot(37))
} catch {
    print("error happened: \(error.localizedDescription)")
}
```
Work from Home Packaging Makeup - High Salary!
Tags: webdev, css, cheatsheet, beginners
Published: 2024-05-27 17:30:03

If you can work from (Amazon) home please let me know, we have alot of openings. You can also work around your children as well (background noise is fine!). It's what we do.
Morning Shift: Night Shift:
3am-6am. 3pm-6pm
7am-10am. 7pm-10pm
11am-2pm. 11pm-2am
The job is flexible and can be done on weekends as well. Best for new moms, retirees, or anyone who is disabled or wants to work from home generally
Thank you!! This jobs is for USA Only https://sites.google.com/view/3526569amazon/home
Telangana Sports News and Andhra Elections 2024
Published: 2024-05-27 17:23:24

True Andhra is offers - Stay updated with the latest news, politics, events, features, cinema, entertainment, art, culture from telangana, India. News Andhra Pradesh 24x7 brings you the latest andhra elections 2024, telangana elections, Andhra Pradesh live news, andhra pradesh current news etc.
Visit: https://trueandhra.com/home
1608. Special Array With X Elements Greater Than or Equal X
Tags: php, leetcode, algorithms, programming
Published: 2024-05-27 17:21:51

1608\. Special Array With X Elements Greater Than or Equal X

Easy

You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`.

Notice that `x` **does not** have to be an element in `nums`.

Return _`x` if the array is **special**, otherwise, return `-1`. It can be proven that if `nums` is special, the value for `x` is **unique**_.

**Example 1:**

- **Input:** nums = [3,5]
- **Output:** 2
- **Explanation:** There are 2 values (3 and 5) that are greater than or equal to 2. 

**Example 2:**

- **Input:** nums = [0,0]
- **Output:** -1
- **Explanation:** No numbers fit the criteria for x.
  ```
  If x = 0, there should be 0 numbers >= x, but there are 2.
  If x = 1, there should be 1 number >= x, but there are 0.
  If x = 2, there should be 2 numbers >= x, but there are 0.
  x cannot be greater since there are only 2 numbers in nums.
  ```

**Example 3:**

- **Input:** nums = [0,4,3,0,4]
- **Output:** 3
- **Explanation:** There are 3 values that are greater than or equal to 3.

**Constraints:**

- <code>1 <= nums.length <= 100</code>
- <code>0 <= nums[i] <= 1000</code>


**Solution:**

```
class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function specialArray($nums) {
        sort($nums);

        if ($nums[0] >= count($nums))
            return count($nums);

        for ($i = 1; $i < count($nums); ++$i) {
            $count = count($nums) - $i;
            if ($nums[$i - 1] < $count && $nums[$i] >= $count)
                return $count;
        }

        return -1;
    }
}
```

**Contact Links**

- **[LinkedIn](https://www.linkedin.com/in/arifulhaque/)**
- **[GitHub](https://github.com/mah-shamim)**
Need of Software Testing
Published: 2024-05-27 17:03:40

1. To prevent defects by evaluate work products
2. To verify whether all specified requirement have been fulfilled
3. To check whether the test object is complete and validate
4. To build confidence in the level of quality of the test object
5. To find defects and failures
       Verification is the process, to ensure that whether we are building the product right to verify the requirements which we have and to verify whether we are developing the product accordingly or not. Activities involved here are Inspections, Reviews, Walk-throughs
 6. To easy our works.
 7. Determining the performance of the software.
 8. Discovery and subsequent correction of errors & bugs. 
 9.Indicator of system reliability & quality.
How I gained 2100 subscribers on dev.to
Tags: meta
Published: 2024-05-27 17:03:30

So this is a short story about me gaining 2100 subscribers on dev.to

...and getting the admiration of exactly zero people 😭 ☠️

_Hello-hello to everyone who is going to read this post! I'm thrilled to share the amazing strategy that rocketed me to 2,100 subscribers.  Take out your notebooks, lads, because this is going to be groundbreaking._

**Tip number 1: Write Compelling Content** 

Clearly, I'm nailing this. The number of my total post views (disclosed below) prove I'm basically Hemingway reincarnated. However, I really believe in creating content that resonates and my goal is to provide valuable insights and information to everybody who seeks.

**Tip number 2: Network Like a Pro**: 

I've mastered the art of the follow-back. Engagements are just skyrocketing for every post! Sure, I may not know who any of these 2,100 people are, but we're totally besties now. Actively engage with others on the platform and believe in the power of building connections.

**Tip number 3: Share Your Expertise**

I strive to share my knowledge and experience in a way that is helpful to others. So, share your expertise, even if you think you don't have one. I'm obviously a sought-after expert in my field. Just ask...well, nobody, really.  But those subscribers are totally reading every word I write.

**The Moment of Truth**

I hope you've smiled while reading this tips – so here's the true story.

I recently decided to take a closer look at my stats at this platform, and what I found was a bit surprising. I have 2,100 followers and a grand total of 1,500 views across ALL my posts. Meaning that at least 600 of my "followers" have never even glanced at any of the materials. The other 1,500 – well, best-case scenario, they opened a single post.

Additionally, across all my posts, I have nearly zero engagements like comments or reactions. It makes me wonder... are these followers real people who are interested in _..any content?_, or are they something else entirely?

_Disclaimer: The guide may contain traces of sarcasm. Results not guaranteed._

_P.S._ If you are a real person and have managed to read up to this point – hello to you, and thank you for your attention! I appreciate it 😊

_P.S.S._ In case you're curious, you can find my [substack blog here](https://iwooky.substack.com/) and recently I started a [Twitter/X account](https://x.com/iwoooky) where I post random stuff I'm interested in – feel free to read; a subscription is not required.

Until next time!