teleren/devto huggingface dataset:
Analysis of the relationship between SAE-J1939 and CAN2.0B
Published: 2023-07-28 08:18:27

1. What is SAE-J1939?

SAE-J1939 (hereinafter referred to as J1939) is the recommended standard of the American Society of Automotive Engineers (SAE), widely used in commercial vehicles (heavy trucks, buses and other road vehicles and construction machinery, agricultural machinery, rail locomotives, ships and other non-road vehicles and equipment) ) Digital communication between electronic components.

2. The relationship between SAE-J1939 and CAN2.0

CAN2.0 (previous guide) is a bus specification and a data link layer technology. J1939 is a specification defined by SAE (American Automobile Association) based on the CAN bus, and is mainly used to solve compatibility issues between different engine manufacturers and different ECU manufacturers.

J1939 defines a series of PGNs and SPNs. These PGNs contain information on various parts of the car such as engines, transmissions, and axles; the representation method (state and value) of parameters defines SLOT (Scaling-proportion, Limit-boundary, Offset—offset, Transfer—transfer). ECU manufacturers should follow this specification when developing equipment. ECU modules have different functions and different manufacturers. On the basis of J1939, they show their diversity: support or not support some PGN, SPN and SLOT; add some PGN and SPN that are not defined by J1939.

3. SAE-J1939 and CAN2.0B message frame format

The CAN2.0 specification includes CAN2.0A (standard frame format) and CAN2.0B (extended frame format), both of which use different frame format bitcodes. J1939 is further packaged on the basis of CAN2.0B, redefining the 29-bit ID of the arbitration field. Only standardized communication is defined for the extended frame format in SAE-J1939, therefore, SAE-1939 equipment must use the extended frame format.

**_Ebyte Electronic Technology Co., Ltd. specializes in R&D and production of wireless data transmission modules with various functions in various frequency bands. The products have been widely used in various application scenarios such as the Internet of Things, consumer electronics, industrial control, medical care, smart home, and highways. If you have any needs, please contact email: 

> service-es-@cdebyte.com
 or visit the website: [https://www.es-ebyte.com/Module-SPISOCUART](https://www.es-ebyte.com/Module-SPISOCUART)_**
Staying Safe Online: Expert Tips for Cybersecurity
Tags: mlimavirtual
Published: 2023-07-28 07:54:11

**In recent news, Kenya experienced a suspected DDoS (Distributed Denial-of-Service) attack that affected several of its services. Cybercriminals used this attack to overwhelm the country's digital infrastructure, causing disruptions and potential data breaches. This incident highlights the growing need for robust cybersecurity measures to protect against such threats.**

This post offers expert tips and strategies to help you stay ahead in the cybersecurity race and maintain a secure online presence.

**Understanding Cyber Threats**

Before we delve into cybersecurity best practices, let's grasp the basics of the cyber threat landscape. Cybercriminals use various tactics like phishing, ransomware, and DDoS attacks to target individuals, businesses, and governments. Knowing common cyber threats empowers us to defend against them effectively.

Top Cybersecurity Tips

1. **Strong, Unique Passwords**: Protect online accounts with strong passwords, combining letters, numbers, and symbols. Never reuse passwords and consider using a password manager.

2. Two-Factor Authentication (2FA): Enable 2FA for an extra layer of security. It requires a second form of verification, reducing unauthorized access risks.

3. Regular Software Updates: Keep your software up-to-date to prevent cybercriminals from exploiting vulnerabilities.

4. **Beware of Phishing Scams**: Be cautious with unfamiliar links and emails, and avoid sharing sensitive information on unsecured websites.

5. **Secure Your Home Network**: Secure your home network by changing router passwords, using strong Wi-Fi passwords, and updating firmware.

6. **Backup Your Data**: Regularly back up your data to protect against ransomware attacks and ensure you can restore it if needed.

**Stay Informed and Keep Learning**

Stay updated on the latest threats and best practices in cybersecurity. Follow cybersecurity news, experts on social media, and join online communities. Consider online courses and certifications to expand your knowledge and skills.

**Conclusion**

Taking a proactive approach and staying informed are vital to staying safe online. By understanding cyber threats and implementing expert tips, you can reduce the risk of falling victim to cyberattacks and maintain a secure online presence. 


**#Cybersecurity #StaySafeOnline #OnlineSecurity**

_Mlima Virtual is a member of Kenya CyberSecurity & Forensics Associations_
How & When To Use JavaScript Array.from() Method
Tags: javascript, beginners, tutorial, programming
Published: 2023-07-28 08:03:00

This is a quick demo explaining when & how to use JavaScript Array.from() method.

Suppose you want to write an array containing numbers from 1 to 100. It's probably a bad idea to write that manually. 

This is a use case for using Array.from() method.

``` js
const array = Array.from({ length: 100}, (_, index) => index + 1);
console.log(array);
```

We pass on two arguments:

In the first argument, we create an object mentioning the length of an array in key/value pair. This will create an empty array with 100 undefined items. 

In the second argument, we pass an arrow function to map all the items in the created array to a new array that the Array.from() method going to return instead of the old array. 

We're essentially passing an Array.map() method as the second argument since we're performing that action on an array containing 100 undefined items.

We keep the first parameter of Array.map() method blank using underscore, this is the item that the method is currently looping through.

In the second parameter, we receive the index of the currently looped item. We're using that index and adding one to it since the array start from index zero.

Let me illustrate what is happening a little better:

``` js
const array = [1, 2, 3];
const newArray = array.map((item, index) => item + index);
console.log(newArray)

// output: [1, 3, 5];
```
Here we're performing the map method on an array.

What happens is we pass a function (also known as a callback function) in the map method as an argument, that function receives the first element of the array as the first argument which is 1 and its index as the second argument which is 0. 

Then it proceeds to create a new array and push the value that it returns in that in each iteration. It keeps looping through all the array items and pushes whatever it returns to the new array and after the whole iteration is done it returns the new array.

For those who are confused, argument is the what we pass in a function and the parameter is the defined variable name for the argument.

Follow me: @wasimapinjari 

Links: [wasimapinjari.bio.link](https://wasimapinjari.bio.link)
Kotlin Code Smell 23 - Singletons
Tags: kotlin, codesmells, cleancode, programming
Published: 2023-07-30 05:36:30

---
title: Kotlin Code Smell 23 - Singletons
published: true
date: 2023-07-28 08:00:09 UTC
tags: kotlin,codesmells,cleancode,programming
canonical_url: https://yonatankarp.com/kotlin-code-smell-23-singletons
---

## Problem

- [Coupling](https://maximilianocontieri.com/coupling-the-one-and-only-software-design-problem)

- Testability

- Accidental implementation problems

- Multi-threading issues

- Static methods polluting

- Object creation contract violation

- [Bijection](https://mcsee.hashnode.dev/the-one-and-only-software-design-principle) mismatch

- Memory issues

- Premature Optimization

## Solution

1. Avoid singletons altogether.

2. Use contextual unique objects instead of relying on a global instance.

3. Benchmark object creation to ensure performance is not adversely affected.

## Examples

- Database Access

- Globals

- Loggers

- Helper classes

## Sample Code

### Wrong

```
// God is the archetypal singleton example
class God {
    // In Kotlin, the companion object is always a singleton
    companion object {
        private var instance: God? = null

        fun getInstance(): God {
            if (instance == null) {
                instance = God()
            }

            return requireNotNull(instance)
        }
    }
}

// Why should we be aware of getInstance when creating an object?
val jewishGod = God.getInstance()

```

### Right

```
interface Religion {
    // Define behavior
}

class God {
    // There can be as many as you wish
}

class PolytheisticReligion(private val gods: Collection<God>) : Religion
class MonotheisticReligion(private val godAllMighty: God) : Religion

// According to Judaism, there's only one God,
// but this does not hold in other religions.
// Under this context, God is unique. We cannot create or change
// a new one.
val jewishGod = God()
val judaism = MonotheisticReligion(jewishGod)

val jupiter = God()
val saturn = God()
val mythologicalReligion = PolytheisticReligion(listOf(jupiter, saturn))

// Gods are unique (or not) according to context.
// We can create test religions with or without unicity.
// This is less coupled since we break the direct reference to the
// God class.
// The God class has the single responsibility to create gods, not
// to manage them.

```

## Conclusion

The use of singletons is a historical mistake that has already been acknowledged by the community. Nevertheless, lazy developers bring it up again and again. We need to reach a consensus on its drawbacks and strive for better design patterns.

* * *

I hope you enjoyed this journey and learned something new. If you want to stay updated with my latest thoughts and ideas, feel free to register for my [**newsletter**](https://yonatankarp.com/newsletter). You can also find me on [**LinkedIn**](https://www.linkedin.com/in/yonatankarp/) or [**Twitter**](https://twitter.com/yonatan_karp). Let's stay connected and keep the conversation going!

* * *

## Credits

- [Code Smell 32 - Singletons](https://maximilianocontieri.com/code-smell-32-singletons) by [Maxi Contieri](https://hashnode.com/@mcsee)
Weekend challenge: Building a ChatGPT bot with Laravel
Published: 2023-07-28 07:50:40

Half asleep, with my brain not completely switched off, thoughts of all the new cool things announced at Laracon US last week swirled round in my head.

But being a busy startup developer/founder, finding time to play with these new toys is always a challenge. Even though I know that some of these new advances will only help me build better products.

So I thought, why not do the learning on top of what I already know! Which is why this weekend I'm going to re-build a small part of my [own product](https://clarify.pdf) with the latest and greatest from Laravel.

I'll be building a video summariser and chatbot for all of the Laracon videos.

{% embed https://twitter.com/farez/status/1684714891947765760 %}

I only have a weekend. Let's see where this thing goes!

As always, I'll be building in public. If you want to follow along, [follow me on Twitter](https://twitter.com/farez) for the play-by-play, or just read the summary and results in [my newsletter](https://https://farez.substack.com/).
Leveraging Service Workers for Advanced Caching Strategies in PWA: A Deep Dive for Beginners
Tags: javascript, cachestorage, beginners, serviceworkers
Published: 2023-07-28 07:31:01

## Introduction

So far, we've been exploring the use and management of JavaScript's CacheStorage for Progressive Web Apps (PWA). Now it's time to take one step further and delve into advanced caching strategies, using Service Workers.

## What are Service Workers?

Service Workers are scripts that the web browser runs in the background. They enable features such as resource caching, push notifications, and background sync to work outside the web page's lifecycle.

## Cache First Strategy

One of the caching strategies is the "Cache First Strategy". In this strategy, we first check the cache, use it if it exists, and only fetch the resource from the network if it doesn't exist. Here's the corresponding code:

```javascript
self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        return response || fetch(event.request)
          .then(function(response) {
            return caches.open('my-cache')
              .then(function(cache) {
                cache.put(event.request, response.clone());
                return response;
              });  
          });
      })
  );
});
```

## Network First Strategy

Another strategy is the "Network First Strategy". Here, we first try to fetch the resource from the network and only use the cache if the network is not available. Here's the code:

```javascript
self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request)
      .catch(function() {
        return caches.match(event.request);
      })
  );
});
```

## Conclusion

In this article, we learned how to implement advanced caching strategies by combining JavaScript's CacheStorage and Service Workers. Caching strategies play a major role in user experience, so choose the one that best suits the nature of your application.

Stay tuned for more techniques in PWA development!

---

これで、CacheStorageとService Workerを組み合わせた高度なキャッシュ戦略について解説したdev.toの記事が完成しました。これらの記事を通じて、読者はPWAのキャッシュ戦略の基礎から高度な戦略までを学び、自身のウェブアプリケーションに応用することができるでしょう。
A Weekly Rust🦀 Pill #2
Tags: rust, programming
Published: 2023-07-28 07:24:21

**A Weekly Rust🦀 Pill** is a post series where on a weekly base, I share some implementations of the most popular algorithms and data structures to share my learnings on **Rust 🦀**.

##Fisher-Yates Shuffle
With the term shuffling, we referee the procedure to randomise a deck of playing cards. It is a crucial task in online gambling, so using an unbiased algorithm to produce a random permutation of the virtual cards’ deck is essential.

One of the most elegant and efficient methods for achieving true randomness is the Fisher-Yates Algorithm, also known as the Knuth Shuffle.

The Fisher-Yates Algorithm, devised by Ronald A. Fisher and Frank Yates in 1938, is a remarkably simple and efficient method to randomly shuffle elements in an array. Unlike naive shuffling approaches that use a random number generator and multiple iterations, the Fisher-Yates Algorithm achieves a uniform and unbiased distribution with a single pass through the array.
The algorithm can be summarised in the following steps:

1. Start with an array containing elements to be shuffled.
2. Initialize an index `i` to the last element of the array.
3. Repeat the following steps until `i` reaches `0`:
   - Generate a random index `j` between `0` and `i`.
   - Swap the element at index `i` with the element at index `j`.
   - Decrement `i` by 1.

## Implementation
To use random number generation in our code, we must add the rand crate to our project, using `cargo add`:

```bash
cargo add rand
```

Here  below the code:

```rust
use rand::distributions::{Distribution, Uniform};

/// Implementation of Durstenfeld variant of Fisher-Yates shuffling algorithm
/// Computational complexity: O(n)
/// See: https://en.m.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
fn fisher_yates<T>(array: &mut Vec<T>) {
    let mut rng = rand::thread_rng();
    for i in (1..array.len()).rev() {
        let dist = Uniform::from(0..i);

        let j = dist.sample(&mut rng);
        array.swap(j, i);
    }
}
```

We pass to our function `fn fisher_yates<T>(array: &mut Vec<T>)` a mutable reference to a list of generic items in this way, we perform an in place shuffle of original vector.
At line `let mut rng = rand::thread_rng();` we initialise our random number generator then in the loop starting from the last item `i` we sample a value `j` from a uniform distribution from `0` to `i`, and we swap the element at position i and j.

To test the function, we can run the following main code:

```rust
fn main() {
    let mut items: Vec<i32> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
    println!("Before shuffling: {:?}", items);
    fisher_yates(&mut items);
    println!("After shuffling: {:?}", items);
}

```

### References
- [Fisher-Yates Algorithm] (https://en.m.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)
- [Rand crate](https://docs.rs/rand/latest/rand/#)
Handlebars-- I'm unable to use If condition for two dynamic values that is current reference and current page number to
Published: 2023-07-28 07:21:49

{% <div class="pagination_numbers">
                        <nav aria-label="Page navigation example">
                            <ul class="pagination">
                                    {{#each pages_count}}

                                    <li class="page-item "><a class="page-link" href="{{this}}">
                                            {{#if (eq {{current_page}} this )}}

                                                <ul class="page-item " ><button class="page-item active">xxsdasdsssx{{this}}</button></ul>

                                                {{current_page}}
                                                {{else}}
                                                <button class="page-item">sss{{this}}</button>
                                                {{/if}}
                                    </a></li>
                                    {{/each}}
                            </ul>
                        </nav>
Here I'm unable to use If condition for two dynamic values that is current reference and current page number to highlight the current page number

If you have any suggestion please do let me know%}
Enterprise DB : About it.
Tags: edb, bitnine
Published: 2023-07-28 07:21:20

**About EDB:**
Enterprise DB is a company that provides enterprise-class services and products - most of which are based on open-source PostgreSQL DBMS. EDB's main objective is to promote the use of PostgreSQL, and make it suitable for much complex applications.

**EDB offerings includes:**
1. EDB Postgres Platform, which includes tools for performance monitoring and database management.
2. EDB Postgres Advanced Server: This is a flagship product, and provides additional features such as Oracle compatibility, improved security, and better performance for complex workloads.
3. EDB Postgres Ark Platform: This is a Database-as-a-Service (DBaaS) which allows users to manage postgreSQL-based databases in a cloud based environment.
4. EDB Postgres Tools, which are used to make management, monitoring and modification of postgreSQL Databases easier.

**A Recap on Bitnine:**
Bitnine is a different company, which is a pioneer in graph database technologies. Bitnine's flagship product is AgensGraph, which is used for graph database management, and it is built on top of PostgreSQL. Bitnine provides its users an access to its own graph query language, "Agens Query Language (AQL)".


**How are they related?**
EDB and Bitnine both offer different types of services, as well as focus on different grounds. EDB focuses on postgreSQL for general enterprise use, whereas Bitnine focuses on specializing the graph database technology. Apart from the fact that both of these organizations work on the same grounds of PostgreSQL, there is no collaboration between them.
Jest - Else path not taken !!!
Published: 2023-07-28 07:21:14

Is there any way to ignore the 'else path not taken' error while running the coverage report in jest in typescript.
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/83l0i3fqceqoriygxnz2.png)

Because of this problem, I was unable to cover my test coverage by 90%. There were solutions to fix this 🙄.
Easy Peasy! Managing CacheStorage in JavaScript for PWA: A Guide for Beginners
Tags: javascript, pwa, cachestorage, beginners
Published: 2023-07-28 07:19:59



## Introduction

In the previous article, we explored the basics of using CacheStorage in JavaScript from the perspective of Progressive Web Apps (PWA). This time, we'll go into the specifics of managing CacheStorage's lifecycle. While caching is a handy feature, if not managed properly, users might continually see outdated data.

## Updating the Cache

First, let's look at updating the cache. The example below shows how to delete old resources when new ones are added to the cache.

```javascript
caches.open('my-cache').then(function(cache) {
  // Add a new resource
  cache.add('https://example.com/my-new-image.png')
    .then(function() {
      // Delete the old resource
      cache.delete('https://example.com/my-old-image.png');
    });
});
```

Keeping only the necessary resources in the cache and regularly deleting the old ones is crucial.

## Versioning the Cache

A more advanced approach involves versioning the cache. The example below shows how to include version information in the cache name, creating a new version of the cache while deleting the old version.

```javascript
// New version of the cache name
var CACHE_NAME = 'my-cache-v2';

// Create new cache and delete existing ones
caches.open(CACHE_NAME).then(function(cache) {
  // Add new resource to the cache
  cache.add('https://example.com/my-new-image.png')
    .then(function() {
      // Delete all old versions of caches
      caches.keys().then(function(cacheNames) {
        return Promise.all(
          cacheNames.map(function(cacheName) {
            if (cacheName !== CACHE_NAME) {
              return caches.delete(cacheName);
            }
          })
        );
      });
    });
});
```

## Conclusion

In this article, we've dug deeper into managing CacheStorage in JavaScript for PWA development. Proper cache management prevents old data from continuously being displayed to users and allows only the latest and most optimal content to be served, improving user experience. 

In our next installment, we'll learn how to build more advanced caching strategies by combining CacheStorage with Service Workers. Stay tuned!
Mastering CacheStorage in JavaScript for Beginners: A PWA Guide
Tags: javascript, cachestorage, pwa, beginners
Published: 2023-07-28 07:16:55



## Introduction

In today's world, web performance is crucial. Fast and efficient websites provide a better user experience, improve search engine ranking, and increase overall user engagement. But, how can we make websites faster? One method is by leveraging browser cache, and in the context of Progressive Web Apps (PWA), JavaScript's CacheStorage is the go-to solution.

## What is CacheStorage?

The CacheStorage API provides a storage mechanism for Request / Response object pairs that are cached as part of the Service Worker lifecycle. It's mainly used in the development of Progressive Web Apps (PWA) for resource caching, allowing for offline availability and performance optimization.

## Using CacheStorage

Let's see how we can open a cache, add resources to it, retrieve the resources, and remove them when no longer needed. Here's a simple example:

```javascript
// Open (or create) a cache
caches.open('my-cache').then(function(cache) {
  // Add a resource to the cache
  cache.add('https://example.com/my-image.png');
});

// Fetch a resource from the cache
caches.match('https://example.com/my-image.png').then(function(response) {
  // Use the resource
  console.log(response);
});

// Delete a resource from the cache
caches.open('my-cache').then(function(cache) {
  cache.delete('https://example.com/my-image.png');
});
```

## Conclusion

Using CacheStorage properly is key to building effective PWAs. Not only can it drastically improve your web app's performance by reducing server requests, but it also allows the app to function even when offline. 

Stay tuned for the next article, where we'll dive deeper into managing the lifecycle of caches in your PWA.