teleren/devto huggingface dataset:
Ultrasonic to Cumulocity IoT via RPi
Tags: iot, ultrasonic, raspberrypi, tutorial
Published: 2022-09-13 12:21:47

---
title: Ultrasonic to Cumulocity IoT via RPi
published: true
date: 2022-08-03 13:38:15 UTC
tags: iot, ultrasonic, raspberrypi, tutorial
canonical_url: https://tech.forums.softwareag.com/t/ultrasonic-to-c8y-via-rpi/259825
---

## How does Ultrasonic sensor work?

An ultrasonic sensor is an electronic device that measures the distance of a target object by emitting ultrasonic sound waves and converts the reflected sound into an electrical signal. Ultrasonic waves travel faster than the speed of audible sound (i.e. the sound that humans can hear). Ultrasonic sensors have two main components: the transmitter (which emits the sound using piezoelectric crystals) and the receiver (which encounters the sound after it has travelled to and from the target).

To calculate the distance between the sensor and the object, the sensor measures the time it takes between the emission of the sound by the transmitter to its contact with the receiver. The formula for this calculation is [D = ½ T x C] (where D is the distance, T is the time, and C is the speed of sound ~ 343 meters/second). For example, if a scientist set up an ultrasonic sensor aimed at a box and it took 0.00261 seconds for the sound to bounce back, the distance between the ultrasonic sensor and the box would be:

### D = 0.5 x 0.00261 x 343

### or about 44.7615 cm (about half the length of a baseball bat).
  
  

The Image is moving, click it and observe😁.

[![Picture1](https://aws1.discourse-cdn.com/techcommunity/original/3X/7/e/7e21e7fabcbbcbccd94b8834138f961ae2d74a89.gif)](https://www.maxbotix.com/wp-content/uploads/2020/03/How-Ultrasonic-Sensors-Work.gif)

[Ultrasonic to C8y Via RPi.pdf](https://tech.forums.softwareag.com/uploads/short-url/shp1AtwNxgy8scxJbHNjd2p20Yw.pdf) (540.3 KB)

[Read full topic](https://tech.forums.softwareag.com/t/ultrasonic-to-c8y-via-rpi/259825)
Cách sử dụng useMemo()
Tags: javascript
Published: 2022-08-03 13:32:00

useMemo() được build bởi React hook và chấp nhận 2 argument- một function và mảng dependencies.
`const memoizedResult = useMemo(compute, dependencies);`
Trong quá trình render lần đầu, `useMemo(compute,dependencies)` ngay lập tức gọi `compute`, ghi nhớ value đã return cho vào memorizes, và trả về component.
Nếu trong suốt quá trình renderings, các dependencies không thay đổi, `useMemo()` không gọi `compute` mà return memorized value.
Nhưng nếu các dependencies thay đổi trong quá trình re-rendering, `useMemo()` sẽ gọi `compute`, nó sẽ update một value mới vào memorizes, và trả về value đó.
**Ví dụ useMemo()**
Một component <CalculateFactorial/> nhằm tính giai thừa của một số.

```
import { useState } from 'react';
export function CalculateFactorial() {
  const [number, setNumber] = useState(1);
  const [inc, setInc] = useState(0);
  const factorial = factorialOf(number);
  const onChange = event => {
    setNumber(Number(event.target.value));
  };
  const onClick = () => setInc(i => i + 1);
  
  return (
    <div>
      Factorial of 
      <input type="number" value={number} onChange={onChange} />
      is {factorial}
      <button onClick={onClick}>Re-render</button>
    </div>
  );
}
function factorialOf(n) {
  console.log('factorialOf(n) called!');
  return n <= 0 ? 1 : n * factorialOf(n - 1);
}
```
Mỗi khi bạn thay đổi giá trị input, `factorialOf(n)` và `factorialOf(n)` được gọi.
Ben cạnh đó, mỗi lần bạn nhấn re-render, set state `inc` sẽ được update và component `<CalculateFactorial/>` sẽ được re-rendering. Nhưng, trong lần render thứ 2, `factorialOf(n)` được gọi lại lần nữa.
Vậy làm thế nào có thể ghi nhớ `factorial` khi componnent re-renders? 
Bằng cách sử dụng `useMemo(()=>factorialOf(number),[number])` thay vì đơn giản `factorialOf(number)`, React sẽ ghi nhớ `factorial`
Ví dụ

```
import { useState, useMemo } from 'react';
export function CalculateFactorial() {
  const [number, setNumber] = useState(1);
  const [inc, setInc] = useState(0);
  const factorial = useMemo(() => factorialOf(number), [number]);
  const onChange = event => {
    setNumber(Number(event.target.value));
  };
  const onClick = () => setInc(i => i + 1);
  
  return (
    <div>
      Factorial of 
      <input type="number" value={number} onChange={onChange} />
      is {factorial}
      <button onClick={onClick}>Re-render</button>
    </div>
  );
}
function factorialOf(n) {
  console.log('factorialOf(n) called!');
  return n <= 0 ? 1 : n * factorialOf(n - 1);
}
```
Mỗi lần ấn button `Re-render`,  `factorial(n)` không được in ra màn hình console bởi vì `useMemo` returns memorized của `factorial`
**Kết luận**
`useMemo(()=>computation(a,b),[a,b])` cho phép bạn ghi nhớ các phép tính lưu vào vùng nhớ memorize. Với các dependencies [a,b] giống nhau, hook sẽ trả về memorized value mà không cần gọi computation(a,b)
Day 1 of Elm
Tags: functional, elm, webdev
Published: 2022-08-03 13:14:42

Started learning functional programming in Elm yesterday and it has been fun. Tried learning with Lisp and Haskell but didn't make much progress. Decided to go with Elm and it has been easier and better for me. 

The most difficult bit about transitioning into Functional Programming is wrapping your head around everything being an expression that evaluates to a result. 

## Conditionals

Take the concept of conditionals for example. In Javascript land, conditionals are statements but in Elm they are expressions. This means that conditionals in Elm must resolve (evaluate?) to a value and therefore must also have an `else` block. In a sense, as Richard Feldman explains, conditionals in elm are better thought about as ternary operators in Javascript. Since the conditional is an expression and must evaluate to a value, it makes sense that the `else` block must be defined.

so this block of code in Elm:

```elm
pluralise singular plural quantity = 
  if quantity == 1 then
    singular
  else 
    plural
```
and this in JS are equivalent:

```javascript
const pluralize = (singular, plural, quantity) => quantity === 1 ? singular : plural;
```

but not exactly equivalent to this even if they achieve the same result:

```javascript
const pluralize = (singular, plural, quantity) => {
  if (quantity === 1) return singular;
  return plural;
};
```
because in the above code you can omit the `else` block and the code will still compile and you will run into runtime exceptions later. Elm massively frowns at runtime exceptions. It does not allow its possibility.

## Parentheses

The role of parenthesis in Elm is interesting. Here, I will just quote Richard Feldman: 

> Parenthesis disambiguate between nested expressions.

This is interesting because in Javascript, parenthesis can be used to disambiguate but they are also used for different other purposes including calling functions, creating functions, conditionals for loops and if statements, etc.

In Elm, it does what it does in Math; disambiguate between nested expressions.

That's all for yesterday. Will write about what I learned in Elm today later.
How to implement UI theme switching with Recoil?
Published: 2022-08-03 13:07:00

> NOTE: This tutorial is relevant to developers using a CSS-in-JS styling approach, e.g. Emotion.js, Material UI, etc.

#### Step 1: Use Recoil atom for the currently selected theme's name

```ts
import { PaletteMode } from "@mui/material";
import { atom } from "recoil";

export const ThemeName = atom<PaletteMode>({
  key: "ThemeName",
  effects: [/* ... */]
});
```

#### Step 2: Use Recoil selector for the currently selected theme object

```ts
import { createTheme } from "@mui/material";
import { selector } from "recoil";

export const Theme = selector({
  key: "Theme",
  dangerouslyAllowMutability: true,
  get(ctx) {
    const name = ctx.get(ThemeName);
    return createTheme(/* ... */);
  },
});
```

#### Step 3: Add `useTheme()`, `useToggleTheme()` React hooks

```ts
import { useRecoilValue, useRecoilCallback } from "recoil";

export function useTheme() {
  return useRecoilValue(Theme);
}

export function useToggleTheme() {
  return useRecoilCallback(
    (ctx) => () => {
      ctx.set(ThemeName, (prev) => (prev === "dark" ? "light" : "dark"));
    },
    []
  );
}
```

#### Step 4: Save/restore the currently selected theme name to/from `localStorage`

```ts
export const ThemeName = atom<PaletteMode>({
  key: "ThemeName",
  effects: [
    (ctx) => {
      const storageKey = "theme";

      if (ctx.trigger === "get") {
        const name: PaletteMode =
          localStorage?.getItem(storageKey) === "dark"
            ? "dark"
            : localStorage?.getItem(storageKey) === "light"
            ? "light"
            : matchMedia?.("(prefers-color-scheme: dark)").matches
            ? "dark"
            : "light";
        ctx.setSelf(name);
      }

      ctx.onSet((value) => {
        localStorage?.setItem(storageKey, value);
      });
    },
  ],
});
```

#### Step 5: Add `ThemeProvider` to the top-level React component

```tsx
import { ThemeProvider } from "@mui/material";
import { useTheme } from "../theme/index.js";

function App(): JSX.Element {
  const theme = useTheme();

  return (
    <ThemeProvider theme={theme}>
      {/* ... */}
    </Theme>
  );
}
```

**See** [`app/theme/index.ts`](https://github.com/kriasoft/react-starter-kit/blob/main/app/theme/index.ts) in [React Starter Kit](https://github.com/kriasoft/react-starter-kit)

#### Resources

- https://recoiljs.org/
- https://learnrecoil.com/course
- https://www.youtube.com/watch?v=2cD8y3CCsIA
Documentation for Rest Web Service. Any suggestion??
Published: 2022-08-03 13:02:45

---
title: Documentation for Rest Web Service. Any suggestion??
published: true
description: 
tags: 
# cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/84layh0nfp2wi1l5nq6o.jpg
# Use a ratio of 100:42 for best results.
---
My company use an "Excel" documentation and a poor diagram for information about Rest Web Service (a lot of WS). The IT client is like "monkeys jumping for bananas".
 Has any standard page, format page or web page to do that job more easy and clean??
 Thanks for the patience.
417. Pacific Atlantic Water Flow
Tags: algorithms, cpp
Published: 2022-08-03 13:01:31

# **417. Pacific Atlantic Water Flow**

# Description

There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges.

The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`.

The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean.

Return *a **2D list** of grid coordinates* `result` *where* `result[i] = [ri, ci]` *denotes that rain water can flow from cell* `(ri, ci)` *to **both** the Pacific and Atlantic oceans*.

## Example 1:



```
Input: heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]]
Output: [[0,4],[1,3],[1,4],[2,2],[3,0],[3,1],[4,0]]
```

## Example 2:

```
Input: heights = [[2,1],[1,2]]
Output: [[0,0],[0,1],[1,0],[1,1]]
```

## Constraints:

- `m == heights.length`
- `n == heights[r].length`
- `1 <= m, n <= 200`
- `0 <= heights[r][c] <= $10^5$`

---

# Solutions

## Solution 1

### Intuition

from **Ocean to land** `heights[x][y] <= heights[dx][dy]`

two types flag, 1 and 2, if two ocean can reach land simultaneous, the flag will be 3

### Code

```cpp
class Solution {
private:
    int m, n;
    int dirs[5] = { 0, 1, 0, -1, 0 };
    vector<vector<int>> state;
    void dfs(int x, int y, int val, vector<vector<int>>& heights) {
        if (state[x][y] & val) return;
        state[x][y] |= val;
        for (int i = 0; i < 4; i++) {
            int dx = x + dirs[i], dy = y + dirs[i + 1];

            if (dx >= 0 && dx < m && dy >= 0 && dy < n && heights[x][y] <= heights[dx][dy]) {
                dfs(dx, dy, val, heights);
            }
        }
    }

public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        m = heights.size(), n = heights[0].size();
        state.resize(m, vector<int>(n, 0));
        // top
        for (int i = 0; i < n; i++) dfs(0, i, 1, heights);
        // left
        for (int i = 0; i < m; i++) dfs(i, 0, 1, heights);
        // bottom
        for (int i = 0; i < n; i++) dfs(m - 1, i, 2, heights);
        // right
        for (int i = 0; i < m; i++) dfs(i, n - 1, 2, heights);

        vector<vector<int>> res;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (state[i][j] == 3) res.push_back({ i,j });
            }
        }
        return res;
    }
};
```

### Complexity

- Time: O(n)
- Space: O(n)

---
How to Take PostgreSQL Schema Backup
Tags: postgres, schema, tutorial, devops
Published: 2022-08-03 12:57:44

In some cases, we have to take PostgreSQL schema level backup. it’s like a logical backup where it just backup the schema objects like tables, indexes, and procedures. These backups are used in the condition where you need to restore just one schema backup, not the whole database. For daily backup, you can create a shell or bash script and schedule it using crontab or windows scheduler.

Read more:
https://thedbadmin.com/how-to-take-postgresql-schema-backup/
Few Suggestions to become a laravel developer
Tags: laraveldevelopmentservices, laravelwebdevelopmentcompany
Published: 2022-08-03 12:57:16

Laravel is an open-source PHP-based framework intended for the development of web applications. Following suggestions can be helpful to you.
website: [https://articles.abilogic.com/579568/what-you-need-know-become.html](https://articles.abilogic.com/579568/what-you-need-know-become.html)
SOLID
Tags: csharp, dotnet, solid
Published: 2022-08-03 12:56:00



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p34lomar40f92nmh324x.jpg)
SOLID besh qisimdan iborat:
S - Yagona javobgarlik printsipi
O - Ochish-yopish printsipi
L - Liskov almashtirish printsipi
I - Interfeysni ajratish printsipi
D - Bog'liqlik inversiyasi printsipi

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

## S
"Class faqat bitta ma'suliyatga ega bo'lishi kerak."

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8l5yyrk9d8k7d130heas.jpg)

## O
"Dastur ob'ektlari kengaytirish uchun ochiq, lekin o'zgartirish uchun yopiq bo'lishi kerak"

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06cq61524ntw0h5ei99x.jpg)

## L
"Liskov almashtirish printsipi ota class ob'ektlari dasturni buzmasdan uning bola class ob'ektlari bilan almashtirilishi kerakligini aytadi."

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hiic6zcb1eiz7vxc3fts.jpg)

## I
"Ko'pgina mijozga xos interfeyslar bitta umumiy maqsadli interfeysdan yaxshiroqdir."

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vfy4cx7a3y5t4abvnfon.jpg)

## D

"Classlar classdan emas abstrakt class yoki interface bilan ulash kerak"

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qwig551npcmgshd4pv7i.jpg)
Replacing Trix with Tinymce in Rails 6.1 ActionText
Published: 2022-08-03 12:51:00

Summary:
If you want to replace Trix you should not use ActionText. It works kind of but adds a lot of Trix-specific content (like the "trix-content" blocks around your edit text which you don't need.

The easiest way is to just add a `text`-field to your model and use `<%= sanitize content %>` in your view.

Tinymce was very easy to install. See my summary here.

As Trix is very limited in scope and doesn't allow you to add attributes to elements (for example you can't add target="_blank" to a link to open it in a new tab) and it doesn't allow you to add classes and in general has a lot of problems as it's seems not to be actively maintained it makes sense to look for other options.

After looking around I started to experiment to replace Trix with Tinymce, but was wondering if it makes sense to keep ActionText.

It was surprisingly easy to replace Trix with TinyMCE which was recommended to me in a Reddit Thread.

My Stack:

- Rails 6.1.4
- Ruby 3.0
- jsbundling-rails with esbuild
- Turbo and Stimulus

You just add tinymce to your package.json and run `yarn install`

You want to wrap Tinymce in a Stimulus controller to easily be able to add it to any textfield.

`rails generate stimulus tinymce`

This will make every textfield a Tinymce editor.

```
import tinymce from 'tinymce/tinymce'
import 'tinymce/icons/default/icons'
import 'tinymce/themes/silver/theme';
import 'tinymce/skins/ui/oxide/skin.min.css';
import 'tinymce/models/dom';

import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="tinymce"
export default class extends Controller {
  connect() {
    tinymce.init({
      selector: 'textarea',  // change this value according to your HTML
    });
  }

  disconnect () {
    tinymce.remove()
  }
}
```

After that you just add the stimulus controller to the encapsulating block and change the rich_text_area to a text_area (here my views using HAML and Tailwind)
```
    .flex.flex-col.gap-3.mb-3
      = f.label :add_text_block, class: "font-bold text-xl"
      = f.rich_text_area :text, class: "", id: "editor_#{block.id}"
```

```
    .flex.flex-col.gap-3.mb-3{ data: { controller: "tinymce" } }
      = f.label :add_text_block, class: "font-bold text-xl"
      = f.text_area :text, class: "", id: "editor_#{block.id}"
```

Now your view will show Tinymce Editor instead of Trix editor. And the best part is that all changes get automatically saved. So `has_rich_text :text` in the model works also with other editors.

Now I just need to figure out how to add links and images to Tinymce and how to customize the elements with attributes and classes. The main reason Trix didn't work for me.

So, the next step is to figure out how plugins work with Tinymce. 

Plugins are also quite easy to add. Just import:

```
import 'tinymce/plugins/link';
import 'tinymce/plugins/code';
import 'tinymce/plugins/image';
```

And customize it in the intializer:

```
      plugins: 'link image',  // note the comma at the end of the line!
      toolbar: 'h2 link image',
```
Largest no. in Array using Recursion
Tags: beginners, tutorial, javascript, webdev
Published: 2022-08-03 12:50:00

Hello guys today i want to show you how to find largest number in array using recursion.
Well i found this question today and then searched the stackoverflow😂 and found this solution and then tried to understand this solution.
Lets get started...

## Code - 
```js
const findMax = arr => {
  if (!Array.isArray(arr)) throw 'Not an array'
  if (arr.length === 0) return undefined
  const [head, ...tail] = arr
  if (arr.length === 1) return head
  return head > findMax(tail) 
    ? head
    : findMax(tail)
}

console.log(findMax([1,9,10,28,78,10]))
```

## Working - 
* First we will check that the argument passed is an arrow or not , if it is not an array then throw an error
* Then we will check if the length of array is 0 , if it is , return undefined.
* In the next line , we destructured the array in two parts - head and tail, head containes the first element of the array and ...tail contains the rest of the array
* After that we check that if the array length is 1 , if it is then we will return the head (the first and only element of that array)
* Then we used the ternary operator to provide the condition, if the head is greater than findMax(tail) meaning the head element is the first element and findMax(tail) will give the first element from the tail array which is the next element jsut after that , so we will compare those two , if the condition is true , we will return the head element as the largest and if the condition is false then we will recursively check the tail and use the first element of that array as head and the rest as other tail element
* So, Recursively it will check and compare all the elements in the array and gives us the largest one.

It looks quite confusing and i tried my best to explain and if you find any point wrong please correct it in the comment section.


Easy and Fast approach 
```js
const findMax = array => Math.max(...array);
```

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl
Day 06 of 100 Days of Code Python Bootcamp by Dr. Angela
Tags: python, programming, beginners, 100daysofcode
Published: 2022-08-03 12:41:26

Day 06 - Code Blocks, Indentations and Functions

For this day, I solved a maze puzzle on Reeborg's World and learned about functions, indentations and code blocks. I also learned about different functions to solve different problem sets.
The goal is to move the robot at the destination/goal.

Code: 

```python

def turn_right():
    turn_left()
    turn_left()
    turn_left()
    
while front_is_clear():
    move()
turn_left()

while not at_goal():
    if right_is_clear():
        turn_right()
        move()
    elif front_is_clear():
        move()
    else: 
        turn_left()

```

Output: 

![Day 06 Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2xeerbl6b1yt08kysfs.gif)

[Maze Puzzle: ](https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Maze&url=worlds%2Ftutorial_en%2Fmaze1.json
)