teleren/devto huggingface dataset:
Find the Town Judge
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 12:00:48

In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge.

If the town judge exists, then:

1.  The town judge trusts nobody.
2.  Everybody (except for the town judge) trusts the town judge.
3.  There is exactly one person that satisfies properties **1** and **2**.

You are given an array `trust` where `trust[i] = [ai, bi]` representing that the person labeled `ai` trusts the person labeled `bi`.

Return _the label of the town judge if the town judge exists and can be identified, or return_ `-1` _otherwise_.

**Example 1:**

**Input:** n = 2, trust = \[\[1,2\]\]
**Output:** 2

**Example 2:**

**Input:** n = 3, trust = \[\[1,3\],\[2,3\]\]
**Output:** 3

**Example 3:**

**Input:** n = 3, trust = \[\[1,3\],\[2,3\],\[3,1\]\]
**Output:** -1

**Constraints:**

*   `1 <= n <= 1000`
*   `0 <= trust.length <= 104`
*   `trust[i].length == 2`
*   All the pairs of `trust` are **unique**.
*   `ai != bi`
*   `1 <= ai, bi <= n`

**SOLUTION:**

    class Solution:
        def findJudge(self, n: int, trust: List[List[int]]) -> int:
            trustedGraph = {}
            trustingGraph = {}
            for a, b in trust:
                trustedGraph[b] = trustedGraph.get(b, 0) + 1
                trustingGraph[a] = trustingGraph.get(a, 0) + 1
            for i in range(1, n + 1):
                if trustedGraph.get(i, 0) == n - 1 and trustingGraph.get(i, 0) == 0:
                    return i
            return -1
Free Review Copies of "The C# Workshop"
Published: 2022-06-14 11:57:23


Packt is planning to publish **"The C# Workshop"** in July this year. 
As part of our marketing activities, we are offering free digital copies of the book in return for unbiased and honest feedback in the form of a reader review. 
Here’s what’s included in the book: 

1. Understand the fundamentals of programming with C# 10 and.NET6  
2. Build your familiarity with .NET CLI and Visual Studio Code  
3. Master the fundamentals of object-oriented programming (OOP)  
4. Understand and implement concurrency to write more efficient code  
5. Create a database and handle data using C#, SQL, and Entity Framework  
6. Build web applications using the ASP.NET framework  
7. Run automated unit tests with NUnit to validate your code  
8. Use principles including SOLID, KISS, ACID, DRY, and design patterns  


If you feel you might be interested in this opportunity, please comment below on or before 30 June 2022.
50+ hints JS(ES6+) developer must know (10th part)
Published: 2022-06-12 01:46:28

My thanks to everybody who follows to this tenth, the last blog of JS hint.
Today we are going to see some useful cases of Accessors, Events, and JQuery.
**1. Accessors**

Do not use JavaScript getters/setters as they cause unexpected side effects and are harder to test, maintain, and reason about. Instead, if you do make accessor functions, use getVal() and setVal('hello').
```
// bad
class Dragon {
  get age() {
    // ...
  }

  set age(value) {
    // ...
  }
}

// good
class Dragon {
  getAge() {
    // ...
  }

  setAge(value) {
    // ...
  }
}
```
If the property/method is a boolean, use isVal() or hasVal().
```
// bad
if (!dragon.age()) {
  return false;
}

// good
if (!dragon.hasAge()) {
  return false;
}
```
It’s okay to create get() and set() functions, but be consistent.

```
class Jedi {
  constructor(options = {}) {
    const lightsaber = options.lightsaber || 'blue';
    this.set('lightsaber', lightsaber);
  }

  set(key, val) {
    this[key] = val;
  }

  get(key) {
    return this[key];
  }
}
```

**2. Events**
When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass an object literal (also known as a "hash") instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event. For example, instead of:

```
// bad
$(this).trigger('listingUpdated', listing.id);

// ...

$(this).on('listingUpdated', (e, listingID) => {
  // do something with listingID
});
```

```
// good
$(this).trigger('listingUpdated', { listingID: listing.id });

// ...

$(this).on('listingUpdated', (e, data) => {
  // do something with data.listingID
});
```

**3. jQuery**

```
// bad
const sidebar = $('.sidebar');

// good
const $sidebar = $('.sidebar');

// good
const $sidebarBtn = $('.sidebar-btn');
```

```
// bad
function setSidebar() {
  $('.sidebar').hide();

  // ...

  $('.sidebar').css({
    'background-color': 'pink',
  });
}

// good
function setSidebar() {
  const $sidebar = $('.sidebar');
  $sidebar.hide();

  // ...

  $sidebar.css({
    'background-color': 'pink',
  });
}
```
For DOM queries use Cascading $('.sidebar ul') or parent > child $('.sidebar > ul'). jsPerf

Use find with scoped jQuery object queries.

```
// bad
$('ul', '.sidebar').hide();

// bad
$('.sidebar').find('ul').hide();

// good
$('.sidebar ul').hide();

// good
$('.sidebar > ul').hide();

// good
$sidebar.find('ul').hide();
```
Thanks for your time.
Best regards.
What is kern.ai ?
Tags: datascience, ai, devops, productivity
Published: 2022-06-14 11:48:00


Warm greetings to everyone reading this from the kern.ai team 😊

We at kern.ai provide a tool for machine learning practitioners and datascientists to manage their labeling process.

Labeling is not a one-time job and this usually results in a lot of manual effort for both annotating and managing your data. In our experience, companies used their own resources implementing an in-house labeling solution that is specific to one task only. With kern we offer data management, concurrent labeling objectives and multi-user operation for any domain that works with structured data or text.

With labeling functions, active transfer learners and weak supervision, our users programmatically label tens of thousands of records within hours, while simultaneously improving the data quality.


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

We look forward to all the data scientists and AI enthusiasts checking out our platform 😊 Your support reinforces our mission to make labeling and data enrichment efficient, scalable and accessible for everyone. 

Thank you for your time and we wish you a great day !

Are you interested in state-of-the-art technology and enhancing your knowledge base regarding the latest development’s in AI ? Here’s the link to our blog: [kern.ai/blog](https://www.kern.ai/blog)  

We are releasing new features every other week. So if you want to stay updated regarding our product, company and content, subscribe to our newsletter for free at [kern.ai](https://www.kern.ai/pages/open-source)
How to calculate the distance between two points, using the MapQuest API
Tags: javascript, maps, mapquest
Published: 2022-06-14 11:41:39

Previously, we looked at [how to calculate the distance between two points using just math](https://dev.to/steinbring/how-to-calculate-the-distance-between-two-points-using-math-27gh).  The problem with that is that the distance is calculated "as the crow flies".  Calculating the distance between Milwaukee and Chicago is close enough but the distance between Milwaukee and Ludington could be a problem (since Lake Michigan is a thing).

If we modify the example from last week to [look at the distance between Ludington and Milwaukee](https://codepen.io/steinbring/pen/jOZvEdb), you can see what I mean.

{% codepen https://codepen.io/steinbring/pen/jOZvEdb %}

The result comes back as 96.6 miles but if you take the [ferry from Milwaukee to Muskegon](https://www.lake-express.com/), it is really 148 miles and if you go around the bottom of the lake, the distance is 333 miles.  The difference is significant.

Luckily, there are services out there that you can use to do these calculations.  For [today's demo](https://codepen.io/steinbring/pen/RwQYPmW), we are going to look at [MapQuest](https://developer.mapquest.com/) and specifically the [the Route end-point](https://developer.mapquest.com/documentation/directions-api/route/get) of [the Directions API](https://developer.mapquest.com/documentation/directions-api/).

{% codepen https://codepen.io/steinbring/pen/RwQYPmW %}

As you can see, the API takes an API key, the origin of the trip, and the destination of the trip.  It returns all of the details of the trip but for this example, we only really care about the distance.  For more complex queries, MapQuest also offers a [Route Matrix API](https://developer.mapquest.com/documentation/directions-api/route-matrix/post).  That one can go beyond a point-to-point trip and handle many more destinations.

Have any questions, comments, etc?  Feel free to drop a comment, below.
Uncommon Words from Two Sentences
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 11:30:43

A **sentence** is a string of single-space separated words where each word consists only of lowercase letters.

A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence.

Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_. You may return the answer in **any order**.

**Example 1:**

**Input:** s1 = "this apple is sweet", s2 = "this apple is sour"
**Output:** \["sweet","sour"\]

**Example 2:**

**Input:** s1 = "apple apple", s2 = "banana"
**Output:** \["banana"\]

**Constraints:**

*   `1 <= s1.length, s2.length <= 200`
*   `s1` and `s2` consist of lowercase English letters and spaces.
*   `s1` and `s2` do not have leading or trailing spaces.
*   All the words in `s1` and `s2` are separated by a single space.

**SOLUTION:**

    from collections import Counter
    
    class Solution:
        def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
            ws = Counter(s1.split()) + Counter(s2.split())
            op = []
            for w in ws:
                if ws[w] == 1:
                    op.append(w)
            return op
Displaying TwicPics Images When Working Offline With Nuxt.js
Tags: vue, nuxt, javascript, image
Published: 2022-06-14 11:28:01

TwicPics is an image transformation and optimization SaaS. It works in the cloud, and front-end developers interact with the API via the JavaScript library. But when working in local, you might not want (or be able) to connect to the Internet. 

This happened to me, so I wrote a wrapper component around TwicPics that allows me to fallback to local images when necessary. Obviously, this means skipping any image optimization or  transformation. But it provides a quick toggle for switching it off and on, which can be useful when working locally.

## Adding a on/off switch for local images

First, we’ll add a configuration entry to our Nuxt configuration to be able to easily toggle TwicPics.

```js
// nuxt.config.js

export default {
	publicRuntimeConfig: {
		enableOptimization: process.env.NODE_ENV !== 'development'
	}
}
```

In this example, we configure the app to default to local images when we’re in development mode. But we could choose any conditions we like or use a specific environment variable.

## Wrapping our image in a component

Now that we have a configuration toggle, let’s create an component that makes use of it. We’ll go with the straightforward approach: when `enableOptimization` is `false`, we’ll simply display the image; otherwise, we’ll process it with TwicPics.

```html
<!-- components/BaseImage.vue -->
<template>
	<img 
		v-if="$config.enableOptimization"
		:src="src"
	/>
	<img
		v-else
		:data-twic-src="`image:${src}`"
	/>
</template>

<script>
export default {
	props: {
		src: { type: String, required: true }
		// In reality, you'd probably have more props to handle transformations, etc.
	}
}
</script>
```

And that’s it! 

Your `BaseImage` component will load your local image whenever  `enableOptimization` is false. You don’t have to change your code to keep using TwicPics in production.

Obviously, that's a simplified example. In reality, you'd probably be wrapping a `<TwicImage/>` component instead of base `<img>`. But the overall logic is the same. Read more about `@twicpics/components` in [the documentation](https://www.twicpics.com/docs/components/overview).

---

To go further:
- [Nuxt.js docs](https://nuxtjs.org/)
- [TwicPics docs](https://www.twicpics.com/docs/getting-started/overview)
- Or just ask a questions in the comments!

I’m a web developer working with Nuxt.js & serverless. I’m writing about the stuff I learn. Follow [@StriftCodes](https://twitter.com/StriftCodes) on Twitter for more.

Cheers,
A list of free & open-source apps I use on Windows
Tags: productivity, tooling, opensource, windows
Published: 2022-06-14 11:27:58

I’ve been a Windows power-user for a decade, and throughout the journey, I found tools and apps which made me work more efficiently on Windows.

There are 40+ apps I mentioned in the below article. All tools are free to use (or freemium with a generous free version), and many of them are open-source (source code links are provided where applicable).

Some of my favorite tools are Ditto clipboard manager, QuickLook, Clover, ImageGlass, ShareX, and Notepad2-mod.

https://gourav.io/blog/windows-free-apps

what are your favorite apps for Windows?
Solve network errors with PDFKit and wkhtmltopdf
Tags: 10stips, rails, wkhtmltopdf
Published: 2022-06-14 11:24:43

In today's _#10stips_ (where you learn how to solve coding issues within 10 seconds) we talk about the lovely [PDFKit gem](https://github.com/pdfkit/pdfkit).

I've been using it since I was a child (ehm no.. since the gem was born around 12 years ago). It creates PDFs using plain old HTML+CSS.

PDFKit requires `wkhtmltopdf` library which renders HTML using Webkit.

Now, Webkit is a rendering engine and depending on your system configuration you may stumble upon compatibility issues loading resources or **unsolicited network errors that might drive you crazy**, especially when you have HTML pages with lots of images.

```
PDFKit::ImproperWkhtmltopdfExitStatus UnknownNetworkError
Exit with code 1 due to network error: UnknownNetworkError
Exit with code 1 due to network error: ContentNotFoundError
Warning Failed to load
```

Basically, wkhtmltopdf fails to load CSS, JS or IMG files.

There are several factors playing a role...

- PDFkit 0.13 seems to work, while 0.12.5 does not.
- loading images from a web server with TLSv1, it works.
- on a modern server with TLS 1.2, it breaks but not for all resources.
- better to use absolute paths instead of relative ones
- _who knows, who cares!?!?!?!_

So, I give you a quick and final solution.

Ready?

**Turn off the computer and go on a hike. Seriously, it helps your mental and physical health.**

But if you're still interested to solve the problem, this is what I suggest...

1. If possible, update your wkhtmltopdf to the latest version
2. Check wether external resources in your HTML comes from a TLSv1 or TLSv2 server (newer versions of wkhtmltopdf work best with TLSv2).
3. Try to switch URLs from HTTPS to HTTP (and viceversa)
4. Set `config.default_options[:ignore_load_errors] = true` in your PDFKit.configure block

Obviously, using HTTP versus HTTPS presents a security concern. Unfortunately, we have very few options and I'm a guy who prioritize sanity over bugfixing.

And remember, sometimes it's OK to pretend bugs are features.

![Bugfixing](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oy6u9i3tm01c6h3ml7qt.jpeg)

Leave a thumbs up and comment if you wish.
Kth Largest Element in a Stream
Tags: leetcode, dsa, theabbie
Published: 2022-06-14 11:00:44

Design a class to find the `kth` largest element in a stream. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.

Implement `KthLargest` class:

*   `KthLargest(int k, int[] nums)` Initializes the object with the integer `k` and the stream of integers `nums`.
*   `int add(int val)` Appends the integer `val` to the stream and returns the element representing the `kth` largest element in the stream.

**Example 1:**

**Input**
\["KthLargest", "add", "add", "add", "add", "add"\]
\[\[3, \[4, 5, 8, 2\]\], \[3\], \[5\], \[10\], \[9\], \[4\]\]
**Output**
\[null, 4, 5, 5, 8, 8\]

**Explanation**
KthLargest kthLargest = new KthLargest(3, \[4, 5, 8, 2\]);
kthLargest.add(3);   // return 4
kthLargest.add(5);   // return 5
kthLargest.add(10);  // return 5
kthLargest.add(9);   // return 8
kthLargest.add(4);   // return 8

**Constraints:**

*   `1 <= k <= 104`
*   `0 <= nums.length <= 104`
*   `-104 <= nums[i] <= 104`
*   `-104 <= val <= 104`
*   At most `104` calls will be made to `add`.
*   It is guaranteed that there will be at least `k` elements in the array when you search for the `kth` element.

**SOLUTION:**

    import heapq
    
    class KthLargest:
    
        def __init__(self, k: int, nums: List[int]):
            self.k = k
            self.heap = nums
            heapq.heapify(self.heap)
            while len(self.heap) > k:
                heapq.heappop(self.heap)
    
        def add(self, val: int) -> int:
            heapq.heappush(self.heap, val)
            if len(self.heap) > self.k:
                heapq.heappop(self.heap)
            return self.heap[0]
    
    
    # Your KthLargest object will be instantiated and called as such:
    # obj = KthLargest(k, nums)
    # param_1 = obj.add(val)
Важность выслушивать коллег, важно ли?
Tags: russia, productivity, discuss
Published: 2022-06-14 10:59:34

Сегодня понял одну истину, оказывается я не умею выслушивать собеседника и не умею понимать, что он хочет до меня донести, а вместо этого я сразу подсознательно готовлю ответ. Пытаясь подставить его точку зрения не правильным. Вы тоже замечали в себе такие черты характера? Наше подсознание, сразу говорит нам Ты прав, а он нет. Он в большинстве случаев уверен в нашей собственной правоте. Почему так работает подсознание? И с сегодняшнего дня я попытаюсь воспринимать информацию по другому, не важно с кем я общаюсь, я попытаюсь вместо ответа выслушать моего собеседника и понять побыть так сказать в его шкуре и попытаюсь понять его точку зрения. Эти мысли появились у меня когда я читал книгу **Кови Стивена** "7 навыков высокоэффективных людей".

Вы только вдумайтесь в эти мысли писателя **Дэвида Таро**: 

> "На тысячу обрывающих листья с дерева зла находится лишь один, рубящий его под корень"

 И действительно, может проблема с некоторыми людьми с которыми я не могу вести нормальную коммуникацию заключается именно во мне? Нужно найти решения и найти корень зла, нежели искать причину обрывающих листьев.
Интрига взяла верх. Думаю стоит попробовать.

_P.S просьба маленькая. Кто общался со мной, дайте обратную связь, есть ли во мне выше перечисленные характер? Я не выслушиваю вас коллеги?)_

Всем продуктивного дня.
Occurrence of a Number in a Linked List.
Tags: c, linkedlist, beginners
Published: 2022-06-14 10:37:21

Let us write a function that prints the number of times a number has occurred in a given linked list. 

**Example 1 :**      

Linked list : 2 6 4 4 5
Occurrence of number `4` : 2

**Example 2 :** 

Linked list : 3 5 2 7 1 9
Occurrence of number  `8` : 0

 

## Steps :

* Declare an integer variable `item` to store a number  whose occurrence has to be found.

* Initialise an another integer variable `count` with `zero(0)` to store the number of times a number has occurred i.e., `count = 0`.

* Declare a temporary pointer `temp` of type `struct node` for traversing a linked list.

* Take the input(a number whose occurrence is to be found) from the user and initialise that user input to variable `item`.

* Start traversing a linked list until a number equal  to `item` is   found. 

* If a number equal to the `item` is found , then update count by `1`.

* After reaching the end of linked list, print `count` and exit the function.

**C program that finds the occurrence of number in a given linked list.**

```
#include <stdio.h>
#include <stdlib.h> 
 
struct node
{
   int data;
   struct node * next;
};  
  
void displayLL(struct node * head)
{
   int num = 0;
   struct node * temp;
   temp = head;
   temp=head;
   while(temp!=0)
   {
       printf("%d ",temp->data);
       temp = temp->next;
       num++;
   }
}
 
void occurrence(struct node *head)
{
   struct node *temp = head;
   int item, count = 0;
   printf("\nEnter the number whose occurrence is to find : ");
   scanf("%d", &item);
    
   while(temp != NULL)
   {
       if(temp->data == item)
           count++;
           temp = temp->next;
   }
   printf("Occurrence of number  %d : %d", item, count);
}
    
int main()
{
   struct node *head = 0, *newnode, *temp, *slow; 
   int n, choice, newdata;
 
// Create Linked List //
 
   printf("Enter the number of nodes in the list : ");
   scanf("%d", &n);
   for(int i = 1; i<=n; i++)
   {
   newnode = (struct node *)malloc(sizeof(struct node));
   printf("Enter the data%d : ", i);
   scanf("%d", &newnode->data);
   newnode->next = 0;
   if(head == 0)
    {
        head = temp = newnode;
    } 
    else
       { 
        temp->next = newnode;
        temp = newnode;
       }
 }
   printf("--------------------------------\n");
   printf("Linked list : ");
   displayLL(head);
   occurrence(head);
}
```

**I own a website www.coderlogs.com where in I write similar blogs so do visit the website for more such blog posts.**
125. leetcode solution in cpp
Tags: cpp
Published: 2022-06-14 10:36:57

```
class Solution {
 public:
  bool isPalindrome(string s) {
    int l = 0;
    int r = s.length() - 1;

    while (l < r) {
      while (l < r && !isalnum(s[l]))
        ++l;
      while (l < r && !isalnum(s[r]))
        --r;
      if (tolower(s[l]) != tolower(s[r]))
        return false;
      ++l;
      --r;
    }

    return true;
  }
};
```