teleren/devto huggingface dataset:
Custom Hooks - useToggle()
Tags: webdev, react, typescript, javascript
Published: 2023-02-26 23:12:19

Hello everyone,

Today I am here to explain you to another custom hook, **useToggle**. We will continue with this hook as the second step in our Custom Hook adventure. It is a pretty simple hook. 🙂

**So what's the point of this hook?** 

As you know, sometimes there are only values that we toggle. For example, the best example of this is sidebar status, whether the sidebar is opened or closed. 

We want to know the instant status of the sidebar, but instead of assigning a boolean value directly to it, we want to toggle it. 

In these cases, the useToggle custom hook comes to our aid. If we implement this hook, we can use it in such situations very easily. Below you can see the file structure I prepared for this hook and the implementation.

![File Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fczm75zarexgrkyvlobn.png)

```typescript
import React, { useCallback, useEffect, useState } from "react";

// Part 1
const useToggle = (initialState: boolean = false) => {
  // Part 2
  const [state, setState] = useState(initialState);

  // Part 3
  const toggle = useCallback(() => setState((state) => !state), []);

  // Part 4
  return [state, toggle] as const;
};

// Part 5
export default useToggle;
```

## Explanations

**Part 1**
We name our function using the use....() pattern and take the necessary arguments. The argument we receive here specifies the initial state of toggle status.

**Part 2**
We need to manage state internally in our hook. To do so, we used useState() hook.

**Part 3**
Here we create the function that will provide the toggle operation. In this way, the person who will use the function will be able to switch between values with this function.

In case of passing components down, we should prevent unnecessary function redefinition with pre-defined useCallback hook.

**Part 4**
Just like the return value of the useState function, we return our state and toggle function as an array.

If you're using typescript just like me, you're probably wondering about the `as const` expression. 

Since Typescript uses the union structure in values that we return as an array, it is quite natural to get an error. That's why we avoid type inference by spelling `as const`. You can get detailed information about this subject by clicking this [link](https://stackoverflow.com/questions/68702115/type-error-type-boolean-void-is-not-assignable-to-type-mouseeventh).

**Part 5**
Exporting that hook as a default export.

## Usage

We explained everything clearly. Now the rest is using this hook in our source code. Below is the example **App.tsx** file.

```typescript
import React from "react";
import { useToggle } from "./hooks";

function App() {
  const [isSidebarOpen, toggleSidebar] = useToggle();

  return (
    <div>
      <button onClick={toggleSidebar}>
        {isSidebarOpen ? "Toggled" : "Click to Toggle"}
      </button>
    </div>
  );
}

export default App;
```
Android SearchView.OnCloseListener Not Working? Here is how to fix it.
Tags: android, java, searchview, onclicklistener
Published: 2023-02-27 05:25:17

I was working on an android app project which required a **SearchView**. While working on the **SearchView**, I discovered that the method **setOncloseListener** is not working for the **SearchView**. I did some research and found that a lot of people like are having the same issues. After some testing I found a solution to make the close icon click listener or the **OnCloseListener** for **SearchView** work. It is not ideal, but here we go.

![SearchView](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4rrcsvvlhp75wys1j57x.png)

![SearchView with Close Icon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6cnvjc52mkvx909boj9.png)


**SearchViewSearchView** with Close **IconBefore** going further here are some primary details,

- I'm using androidx.appcompat.widget.SearchView in a layout.
- I needed the method to clear queries from searchView, remove focus and finally hide the soft keyboard.

### Solution

In your java code add these lines to make the magic work:
``` java
        SearchView searchView = findViewById(R.id.search_view);

        int searchCloseButtonId = searchView.findViewById(androidx.appcompat.R.id.search_close_btn).getId();
        ImageView closeButton = searchView.findViewById(searchCloseButtonId);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchView.setQuery("", false);
                searchView.clearFocus();
                binding.searchResultLayout.setVisibility(GONE);
                hideKeyboard();
            }
        });
```
for **hideKeyboard**:
``` java
        private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(binding.searchView.getWindowToken(), 0);
        }
```
And that's it. Now you can make your `searchView` close icon work as you like.

### How it's working?

**SearchView** has IDs for its own components, in this case, the close icon. In the code have `searchView.findViewById(androidx.appcompat.R.id.search_close_btn).getId()` which calls the id of the close image from **searchView** itself. 
Later we added this id to an **ImageView** by using `searchView.findViewById(searchCloseButtonId)` this. And then just setting on click listener for the ImageView and creating a method for **hideKeyboard** from **searchView windowToken**.


So, now you have a solution to fix problems with `searchView.setOnCloseListener`.

Find me on - [Github](https://github.com/ahmmedrejowan), [Facebook](https://www.facebook.com/ahmmedrejowan)
Using .filter and .find in arrays
Published: 2023-02-27 04:34:14

```
const restaurants = [
  { name: 'Cap City Diner', milesAway: 2.2 },
  { name: 'Chop Shop', milesAway: 4.1 },
  { name: 'Northstar Cafe', milesAway: 0.9 },
  { name: 'City Tavern', milesAway: 0.5 },
  { name: 'Shake Shack', milesAway: 5.3 }
]

const results = restaurants.filter(restaurant => 
  restaurant.name.startsWith('C') && restaurant.milesAway < 3
)
console.log(results);
```
Gives multiple results.


```
const restaurants = [
  { name: 'Cap City Diner', milesAway: 2.2 },
  { name: 'Chop Shop', milesAway: 4.1 },
  { name: 'Northstar Cafe', milesAway: 0.9 },
  { name: 'City Tavern', milesAway: 0.5 },
  { name: 'Shake Shack', milesAway: 5.3 }
]

const result = restaurants.find(restaurant => 
  restaurant.name.toLowerCase().includes('north') && restaurant.milesAway < 2
)
console.log(result);
```
Returns the first result that meets the description.
sm66mobi
Published: 2023-02-27 05:00:35

SM66 la mot trong nhung san choi co ten tuoi lau nam tren thi truong hien nay. Voi su phat trien cong nghe ngay cang hien dai va tien tien, cong game nay ngay cang cap nhat nhieu ung dung de thu hut nhieu nguoi tham gia hon. 
Dia Chi: 332 D. 79, Kp 6, Thanh Pho Thu Duc, Thanh pho Ho Chi Minh, Viet Nam
Email: sm66mobi@gmail.com
Website: https://sm66mobi.com/
Dien Thoai: +(84) 921577975
#sm66 #sm66mobi #sm66casino #nhacaism66

https://www.facebook.com/sm66mobi/
https://twitter.com/sm66mobi
https://www.youtube.com/channel/UCXDNOikpKUs9zw5IHzbWu4A
https://www.pinterest.com/sm66mobi/
https://bbs.now.qq.com/home.php?mod=space&uid=3823287
https://www.blogger.com/profile/03556191392538701322
https://www.reddit.com/user/sm66mobi
https://www.flickr.com/people/sm66mobi/
https://www.tumblr.com/sm66mobi
https://medium.com/@sm66mobi
https://sm66mobi.wixsite.com/sm66mobi
https://sm66mobi.weebly.com/
https://sm66mobi.livejournal.com/profile
https://sm66mobi.wordpress.com/
https://sites.google.com/view/sm66mobi/trang-ch%E1%BB%A7
https://linktr.ee/sm66mobi
https://www.twitch.tv/sm66mobi
https://tinyurl.com/sm66mobi
https://ok.ru/sm66mobi
https://profile.hatena.ne.jp/sm66mobi/
https://issuu.com/sm66mobi
https://www.liveinternet.ru/
https://dribbble.com/sm66mobi
https://sm66mobi.webflow.io/
https://sm66mobi.thinkific.com/
https://500px.com/p/sm66mobi
https://about.me/sm66mobi
https://tawk.to/sm66mobi
https://www.deviantart.com/sm66mobi
https://ko-fi.com/sm66mobi
https://www.provenexpert.com/sm66-mobi/
https://hub.docker.com/u/sm66mobi
https://independent.academia.edu/sm66mobi
Why do you need to monitor your network?
Published: 2023-02-27 04:25:22

              

Monitoring your network is essential for several               reasons, including:
**Security:** Monitoring your network can help you identify potential security breaches or threats, such as unauthorized access or suspicious activity. It allows you to take action quickly to prevent or minimize any damage caused by a security incident.

**Performance:** Monitoring your network can help you identify performance issues such as slow network speed or bandwidth constraints. You can then take action to optimize your network to improve its performance.

**Availability:** Network downtime can result in lost productivity and revenue. Monitoring your network can help you identify and resolve issues quickly, reducing the amount of downtime your network experiences.                                                                                    

**Compliance:** Depending on your industry or organization, you may be required to meet specific compliance requirements. Network monitoring can help you identify any non-compliant activity or vulnerabilities, allowing you to take corrective action.

Overall, network monitoring is an essential practice to ensure the security, performance, and availability of your network, which is critical to the success of your organization.
Performing action on elements in an array
Published: 2023-02-27 04:12:31

```
const temperatures = [
  { degrees: 69, isRecordTemp: false },
  { degrees: 82, isRecordTemp: true },
  { degrees: 73, isRecordTemp: false },
  { degrees: 64, isRecordTemp: false }
];

const newTemps = temperatures.map(temperature => 
temperature.degrees > 70 ? { ...temperature, isHigh: true } : temperature 
);

newTemps.forEach(temperature => {
   if (temperature.isHigh) {
     console.log(`Temperature ${temperature.degrees} was a record high last week!`);  
   }
})
// console.log(newTemps);
```
Thus adds isHigh to elements given a conditional is granted.


```
const temperatures = [
  { degrees: 69, isRecordTemp: false },
  { degrees: 82, isRecordTemp: true },
  { degrees: 73, isRecordTemp: false },
  { degrees: 64, isRecordTemp: false }
];

const newTemps = temperatures.map(temperature => {
   temperature.isHigh = true; 
   return temperature;
});
console.log(newTemps);
```
Thus adds isHigh to all elements in the array.
Do you have any questions?
Tags: interview, beginners, programming, career
Published: 2023-02-27 04:03:22

Here's a short post on good questions to ask in an interview, when they ask you "Do you have any questions?"

- What skills are the most important for this position?
- What is the most important thing you're looking to solve by filling this position?
- What is your vision for "the project/product"?
- What is the overall vision of the company?
- Can you tell me what you think i'm lacking to fulfil this role?
- Are there any suggestions for areas I would need to improve, to better fill this role?

Just something I wrote up before starting an interview. It's good to sit down for at least five minutes and figure out more specific questions, that you actually would like answered. 

There's no harm in asking and it can make a world of difference for you to figure out if you'd like to join the company/team.

Of course it completely depends on your situation at the time. Take all of this with a grain of salt!
Confused - Guide to Getting Started with AI/ML
Tags: discuss, ai, machinelearning, python
Published: 2023-02-27 04:01:36

Hey guys,

Currently I'm a full stack developer with a good grasp on Node.js, PHP, Typescript, Flutter etc and I want to learn AI/ML.

I'm a python beginner and need community help to know the path for learning AI/ML.

Help & suggestions appreciated! Thank you!

_Happy Coding_
Absolute imports in React Native
Tags: javascript, tutorial, reactnative, typescript
Published: 2023-02-27 04:00:06

This is a short guide on how to use absolute imports in React Native.

## Absolute imports

The absolute imports are a feature that was introduced in ES2020. It allows you to import modules using an absolute path instead of a relative path.

For example, if you have a file called `App.js` in the `src` folder, you can import a module called `utils.js` using the following code:

```javascript
import { sum } from 'src/utils';
```

This is a simple example, but it can be very useful when you have a complex project with many files and folders.

## How to use absolute imports in React Native

To use absolute imports in React Native, you need to install the `babel-plugin-module-resolver` package.

```bash
yarn add -D babel-plugin-module-resolver
```

After installing the package, you need to configure it in the `babel.config.js` file.

```javascript
module.exports = {
  presets: ['babel-preset-expo'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        alias: {
          '~/assets': './src/assets',
          '~/contexts': './src/contexts',
          '~/screens': './src/screens',
          '~/styles': './src/styles',
          '~/routes': './src/routes',
          '~/services': './src/services',
          '~/hooks': './src/hooks',
          '~/shared': './src/shared',
        },
      },
    ],
  ],
};
```

The `root` property is used to define the root folder of the project. In this case, it is the `src` folder.

The `alias` property is used to define the aliases that will be used in the imports. In this case, I defined the following aliases:

- `~/assets`: `./src/assets`
- `~/contexts`: `./src/contexts`
- `~/screens`: `./src/screens`
  …

The aliases are used to import modules using the `~` character. For example, if you want to import the `App.js` file in the `screens` folder, you can use the following code:

```javascript
import App from '~/screens/App';
```

If you are using Typescript, you will need to add the following code to the `tsconfig.json` file:

```json
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "~/*": ["*"]
    }
  }
}
```

It is important to note that the `baseUrl` property must be the same as the `root` property in the `babel.config.js` file.

Now you will be able to use absolute imports in your React Native project.

Thank you for reading this article.
If you enjoy this article, please upvote and comment.

Follow me on:

- [Twitter](https://twitter.com/_ianfelix)
- [GitHub](https://github.com/ianfelix)
- [LinkedIn](https://www.linkedin.com/in/ian-felix)
Week 7: Doing some small and big things
Tags: opensource
Published: 2023-02-27 03:54:43

## Overview 
These week I merged two PRs and each of them were both front-end and back-end related. Additionally, I was doing code reviews for my colleagues. 

## PR 1
In this PR I implemented fetching of records from server and rendering them in domains table that I implemented the last week. 

I faced an issue that Remix serialize and deserializes data sent from the server, but it doesn't deserialize dates, so return them like strings.

I found the solution of using remix-typedjson the most simple and beautiful. Using that lib you need just:

json -> typedjson
useLoaderData -> useTypedLoaderData

Another thing that was included in this PR was making the caution dialog for users who try to delete the record.

https://github.com/DevelopingSpace/starchart/pull/242

## PR 2 
This PR was resolving the issue of making a real request to the server when user tries to delete record or prolong it's expiration date + it resolves some minor UI issues and adds loading effect for specific record in a table. 

https://github.com/DevelopingSpace/starchart/pull/276
To Learn it all is a must and Mastery is the key
Tags: beginners, tutorial, programming
Published: 2023-02-27 03:42:02

What is the Trend? What programming language is the way to start? What Job and How Much money would i earn if i do this and that..

Lot's of starter's in the field of programming have different goals and Why's.. Were all different in some ways.. but what i have learned and now using is Mastery..

> What i can share to you is **"Start"** and **"Master one"**.. before starting a new language

The Trend is changing, lot's of knowledge will be discovered,  and getting good is much important.. earning follows.. 

Thank you for reading..
Mr Bắn Cá Đổi Thưởng - Top 10 + Game Bắn Cá Uy Tín Nhất Hiện Nay
Tags: programming
Published: 2023-02-27 03:37:03

**Bắn cá đổi thẻ là gì**
<a href="https://mrbanca.net/" rel="noreferrer dofollow">bắn cá đổi thưởng</a> sẽ có 1 một phiên bản mới lạ đó là trò chơi bắn cá đổi thẻ. Thay vì sử dụng tiền mặt, người chơi sẽ sử dụng thẻ cào để nạp tiền vào tài khoản chơi game. Điều này giúp cho việc nạp tiền trở nên đơn giản và tiện lợi hơn cho người chơi.


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

**Phong cách mới lạ của bắn cá đổi thẻ**

Với phong cách mới lạ này, game bắn cá đổi thẻ sẽ đem đến cho người chơi cảm giác thú vị hơn khi sử dụng thẻ cào để nạp tiền và trải nghiệm trò chơi. Ngoài ra, bắn cá đổi thẻ còn có nhiều tính năng hấp dẫn như bảng xếp hạng, thử thách người chơi với các màn chơi khác nhau, các loại vũ khí đa dạng, và nhiều loại cá đặc biệt khác nhau với kỹ năng và tính năng riêng biệt.

Để tăng tính thú vị cho trò chơi, các nhà phát triển game bắn cá đổi thẻ cũng thường xuyên cập nhật và phát hành các sự kiện đặc biệt, các bản cập nhật mới với nhiều tính năng mới, và các ưu đãi hấp dẫn cho người chơi.

Với phong cách mới lạ này, bắn cá đổi thẻ đang trở thành xu hướng mới trong thế giới game đổi thưởng, và sẽ còn là một trò chơi hấp dẫn và được yêu thích trong thời gian tới.
**Kết luận**
Trên đây là phong cách mới lạ mà Mrbanca đem lại cho bạn giúp bạn tránh sự nhàm chán trong cách chơi , chúc bạn chơi game vui vẻ.

Liên hệ với chúng tôi
Email: mrbancanet@gmail.com
Địa chỉ: 187 Nguyễn Lương Bằng, Quang Trung, Đống Đa, Hà Nội, Việt Nam 
Hotline: 0915704149
openGauss TRUNCATE TABLE Statement
Tags: opengauss
Published: 2023-02-27 03:17:22

The TRUNCATE TABLE statement deletes table data but does not delete the table structure. You can also execute the DROP TABLE statement to delete a table. However, this statement deletes the table structure together with the table. To insert data into the table, you need to recreate the table.

It has the same effect as an unqualified DELETE statement on each table, but it is faster since it does not actually scan the tables. This is most useful on large tables. In addition, the TRUNCATE TABLE statement immediately releases tablespaces without requiring subsequent VACUUM operations.

## Syntax
`TRUNCATE TABLE  table_name ;`

## Parameter Description
table_name

Specifies the name (optionally schema-qualified) of the target table.

Value range: an existing table name

## Examples
Execute the TRUNCATE TABLE statement to delete data from the customer_t1 table.


`openGauss=# TRUNCATE TABLE customer_t1;
TRUNCATE TABLE`
Query the customer_t1 table. The query result is as follows:

`openGauss=# SELECT * FROM customer_t1;
 c_customer_sk | c_customer_id | c_first_name | c_last_name | amount
---------------+---------------+--------------+-------------+--------
(0 rows)`
openGauss ALTER TABLE Statement
Published: 2023-02-27 03:15:25

The ALTER TABLE statement modifies tables, including modifying table definitions, renaming tables, renaming specified columns in tables, renaming table constraints, setting table schemas, enabling or disabling row-level security policies, and adding or updating multiple columns.

## Syntax
Add a column to an existing table.

`ALTER TABLE  table_name
    ADD column_name data_type;`
Delete a column from an existing table.

`ALTER TABLE table_name DROP COLUMN column_name;`
Change the column type of a table.

ALTER TABLE  table_name
` MODIFY column_name data_type;`

Add or delete a NOT NULL constraint to or from a column of an existing table.


`ALTER TABLE  table_name
   ALTER column_name { SET | DROP } NOT NULL;`
Rename a specified column in a table.

`ALTER TABLE table_name RENAME  column_name TO new_column_name;`
Update columns.

`ALTER TABLE  table_name 
    MODIFY ( { column_name data_type | column_name [ CONSTRAINT constraint_name ] NOT NULL [ ENABLE ] | column_name [ CONSTRAINT constraint_name ] NULL } [, ...] );`
Rename a table,which does not affect stored data.


`ALTER TABLE table_name 
    RENAME TO new_table_name;`

## Parameter Description
table_name

Specifies the name of the table to be modified.

If ONLY is specified, only the table is modified. If ONLY is not specified, the table and all subtables are modified. You can add the asterisk (*) option following the table name to specify that all subtables are scanned, which is the default operation.

column_name

Specifies the name of a new or an existing column.

data_type

Specifies the type of a new column or a new type of an existing column.

new_table_name

Specifies the new table name.

new_column_name

Specifies the new name of a specific column in a table.

constraint_name

Specifies the name of a constraint.
w7 hw
Published: 2023-02-27 03:08:45

React:

JSX syntax: React uses JSX, which is a mix of JavaScript and HTML syntax. This can be confusing for new developers who are not familiar with this syntax, as it can look like regular HTML but behaves like JavaScript.
Virtual DOM: React uses a virtual DOM to optimize rendering performance. This concept can be difficult to understand for new developers, especially those who are not familiar with how the DOM works.
Prop drilling: React uses a uni-directional data flow model, where data is passed down from parent components to child components through props. This can become confusing and cumbersome as the component tree grows deeper.

Web Components/Platform:

Standards and specifications: Web Components/Platform is a collection of web standards and specifications that define how to create reusable and encapsulated components. Learning all these standards and specifications can be overwhelming for new developers.

Browser compatibility: Some web components may not work as expected on older browsers, or may require additional polyfills to work properly. This can be confusing and frustrating for new developers who are not familiar with browser compatibility issues.

Complexity: Web Components/Platform can be more complex than React, especially when it comes to setting up a development environment or building a complete application from scratch.

To teach Web Components and VanillaJS in a more approachable way, it may be helpful to start with simpler examples and gradually introduce more complex concepts. Providing clear and concise documentation, tutorials, and code examples can also help new developers better understand the concepts.


Some parts of tooling that may be confusing for new developers include managing dependencies, setting up a development environment, and configuring build and deployment processes. What clicked with me immediately when working with Web Components and VanillaJS was the simplicity of the approach. By focusing on the core building blocks of the web (HTML, CSS, and JavaScript), it felt more intuitive and less abstract compared to working with larger frameworks such as React or Vue. Additionally, the ability to create truly reusable and encapsulated components felt empowering and encouraged modular and maintainable code. That being said, there were still parts of the tooling that were confusing, particularly around configuring build and deployment processes. However, I found that reading documentation and asking for help from more experienced developers were helpful in overcoming these challenges.