teleren/devto huggingface dataset:
How to set value of input field in angular template
Tags: angular, forms, codever, snippets
Published: 2023-01-11 10:10:13

To set the initial value of the `input` control, just use the `value` attribute:

```typescript
<input type="text" class="form-control" placeholder="Generate Codever sharable Url"
       aria-describedby="basic-addon2"
value="{{ environment.HOST + '/bookmarks/shared/' + shareableId}}">
```

**Project**: `codever` - **File**:  `social-share-dialog.component.html`

To understand usage of angular environment used in this snippet (`environment.HOST`)
see the [Configure and use environment specific values in Angular and html template](https://www.codever.dev/snippets/6389997bb160cb1fab2430fe/details) snippet

<span style="font-size: 0.9rem">
  <strong>Reference - </strong>
  <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input" target="_blank" style="font-weight: lighter">
     https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
  </a>
</span>

<hr/>

> Shared with :heart: from [**Codever**](https://www.codever.dev/snippets/638ceaf03b43b9521ecfab28/details). Use :point_right: [**copy to mine**](https://www.codever.dev/snippets/638ceaf03b43b9521ecfab28/details) functionality to add it to your personal snippets collection. 
> 
> **Codever** is open source on [Github](https://github.com/CodeverDotDev)⭐🙏
How to compare date (no time) with current day in javascript
Tags: javascript, date, codever, snippets
Published: 2023-01-11 10:07:04

Get current date with `new Date()` and `setHours` to `0, 0, 0` and then you are ready to compare with the input date, which is a string in the `yyyy-MM-dd` format

```javascript
export const isLessThanToday = (input: string): boolean => { //format of input date is YYYY-MM-DD
    const today = new Date();
    today.setHours(0, 0, 0);

    return notEmpty(input) && new Date(input) < today;
};
```

To test that we can use the following jest test:

```javascript
    describe('isLessThanToday > ', () => {
        test.each([
            [null, false],
            [undefined, false],
            ['AXON', false],
            ['1900-01-01', true],
            ['2099-12-12', false], // TODO change this date when in 2099 :)
            [new Date().toISOString().slice(0, 10), false], //today
            [new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().slice(0, 10), true], //yesterday
            [new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().slice(0, 10), true], //one week ago
        ])('given input date %p, it should return %p', (input, expected) => {
            expect(isLessThanToday(input)).toEqual(expected);
        });
    });
```

See this [How to use jest test.each function ](https://www.codever.dev/snippets/639852fc3b43b9521ecfe046/details) to understand the usage of `test.each` function

<hr>

> Shared with :heart: from [**Codever**](https://www.codever.dev/snippets/6398a6a53b43b9521ecfe361/details). Use :point_right: [**copy to mine**](https://www.codever.dev/snippets/6398a6a53b43b9521ecfe361/details) functionality to add it to your personal snippets collection. 
> 
> **Codever** is open source on [Github](https://github.com/CodeverDotDev)⭐🙏
1443. Minimum Time to Collect All Apples in a Tree
Tags: java, leetcode, 100daysofcode
Published: 2023-01-11 10:02:48

**Problem Statement:**

Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.

The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.

 

**Example 1:**
**Input:** n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]
**Output:** 8 
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  

**Example 2:**

**Input:** n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]
**Output:** 6
**Explanation:** The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.  

**Example 3:**
**Input:** n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]
Output: 0
 

**Constraints:**

- 1 <= n <= 105
- edges.length == n - 1
- edges[i].length == 2
- 0 <= ai < bi <= n - 1
- fromi < toi
- hasApple.length == n

**Solution:**
**Algorithm:**
1. Create an array parent of size n and initialize it with -1.
2. Traverse the edges array and update the parent array.
3. Create a variable res and initialize it with 0.
4. Traverse the array from n-1 to 1.
5. If the ith index of hasApple is true, then update the res by 2 and update the parent[i]th index of hasApple to true.

**Code:**
```
public class Solution {
    public int minTime(int n, int[][] edges, List<Boolean> hasApple) {
        int[] parent = new int[n];
        Arrays.fill(parent, -1);
        for (int[] edge : edges) {
            parent[edge[1]] = edge[0];
        }
        int res = 0;
        for (int i = n - 1; i > 0; i--) {
            if (hasApple.get(i)) {
                res += 2;
                hasApple.set(parent[i], true);
            }
        }
        return res;
    }
}
```

**Time Complexity:**
O(n)

**Space Complexity:**
O(n)
Hack CSS GROUPING SELECTORS
Tags: css, webdev, frontend
Published: 2023-01-11 10:02:33

This article is for intermediate or entry level frontend developers interested  in  CSS Grouping selectors. The writer assumes that the reader has basic knowledge of CSS selectors, HTML elements. This  article will not cover other type of selectors . At the end of the article, the reader can style nested HTML elements with CSS grouping selectors. The article will utilize a basic HTML layout to demonstrate CSS grouping selectors at work.

HTML Layout.


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

Types of grouping Selectors
1)Selector list (“,”): Two or more CSS selectors separated by comma(s). From the above HTML, below is an example of selector list. 

.header-content, .content-input, .header-people{
background-color: red;
}
The above styles will give the three classes a background color of red.

2) Descendant selectors ("  " ): It is an empty space  two CSS selectors.

.container  p{
color:#FF4820

}
The style above gives all the p element and any element within p such as the span element an orange colour.

3) Child selectors “>”: Greater than sign between two CSS selectors D>E. The style affects all E that are directly within D and not those inside E.
.container >p{
color:#FF4820

}
The style will only affect the p element and not the span element.

4)Sibling selector (~): Given two CSS selectors A~B, the sibling selector select all B that follows A.
H1~p{
      font-family:verdana;
      font-size:24px;

}
The above will style all p elements that follows h1
5) Adjacent Sibling Selector (+): Given two CSS selectors D+E. The style will affect the first E that follows D.
h1+p{
       font-family:verdana;
      font-size:24px;

}
The style will affect the first p that follows h1.

 Take note that grouping selectors can be nested. For example

.container .header-content >p {

}
It means style a element p that is a child of class header-content, a descendant of class container.




The article listed different CSS grouping selectors with examples. 

- Selector List
- Descendant Selector
- Child Selector
- Sibling Selector
- Adjacent selector
Also, the articles demonstrated nesting of grouping selectors.
Book Review: Exam Ref AZ-104 Microsoft Azure Administrator Certification and Beyond - Second Edition
Tags: books, azure
Published: 2023-01-11 10:00:00


![The book cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvg4ejbzh6rp0fx6mpe1.jpg)

In my opinion, the AZ-104 exam is one of the most important exams you can take in the Azure landscape. It contains a lot of topics, and all of these topics have a theoretical part and a practical part, and both are important. You need to know the services in Azure, and you must know how to manage them.

I suggest this book because the authors mix the theoretical part with the practical part in each paragraph giving you the possibility to understand the theory and make practical exercise on the portal. The book is clear even when the authors go into the details, deep into the topic. Furthermore, at the end of each chapter, there is a practice lab that allows the student to make a recap using a practical approach.

At the end of the book, in the final chapter, you can, furthermore, find a set of questions similar to those found in the exam, which allows you to verify your preparation. The questions are, of course, not the ones you will find on the exam, but they are very similar and are not trivial at all.

In conclusion, this is a rich and full-bodied book (more than 750 pages) that, due to its practical approach (but without disdaining the theory), can be handy not only for those preparing for the exam but also as a vademecum for the daily job. A book, generally, becomes old after a bref amount of time, but I think that this one can be still valid for long time and you can use it as a reference guide during your daily job.

You can buy the book from the [Packt Publishing web site](https://www.packtpub.com/product/exam-ref-az-104-microsoft-azure-administrator-certification-and-beyond-second-edition/9781801819541), and, now, you can find it at **5€ only**!!!
Creating a basic GET API with Firebase Cloud Functions and Firestore
Tags: firebase, googlecloud, beginners, tutorial
Published: 2023-01-11 09:57:16

Creating a GET API that fetches 100 records using Firebase Cloud Functions and Firestore is relatively simple. Here's an example of how to do it:

1. Start by creating a new Firebase Cloud Function and selecting an HTTP trigger.

2. In the function's index.js file, import the Firebase and Firestore modules by adding the following lines at the top:

`const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();
`

3. Then in the function's body you can use the get() method from the firestore collection object with the limit() method that sets the maximum number of documents to retrieve, in this case, you want to get 100 documents.


`exports.get100Records = functions.https.onRequest((req, res) => {
    db.collection("collection_name")
    .limit(100)
    .get()
    .then(snapshot => {
        const data = [];
        snapshot.forEach(doc => {
            data.push(doc.data());
        });
        res.json(data);
    })
    .catch(error => {
        res.status(500).send(error);
    });
});
`

4. Once your function is ready, you will want to deploy it to Firebase. This can be done by running the following command in your command line: firebase deploy --only functions

5. Now you can test the API endpoint by sending a GET request to the endpoint and checking the results.

Note that this is a simplified example.


Another slightly complex example is shared below : 

`const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const db = admin.firestore();

exports.get100Records = functions.https.onRequest((req, res) => {
    // Get request parameters
    const { orderBy, orderDirection, filterBy } = req.query;

    // Create a reference to the Firestore collection
    let collectionRef = db.collection('collection_name');

    // Apply sorting if specified
    if (orderBy && orderDirection) {
        collectionRef = collectionRef.orderBy(orderBy, orderDirection);
    }

    // Apply filtering if specified
    if (filterBy) {
        collectionRef = collectionRef.where(filterBy.field, filterBy.op, filterBy.value);
    }

    // Get the first 100 documents
    collectionRef.limit(100).get()
    .then(snapshot => {
        const data = [];
        snapshot.forEach(doc => {
            data.push(doc.data());
        });
        res.json(data);
    })
    .catch(error => {
        console.log(error);
        res.status(500).send(error);
    });
});
`

In this example, the API endpoint accepts query parameters for sorting (orderBy and orderDirection) and filtering (filterBy) the data before fetching the first 100 records.

You can test this endpoint by sending a GET request to the endpoint with the appropriate query parameters.
Create APIs with Firebase
Tags: firebase, googlecloud, webdev, java
Published: 2023-01-11 09:50:20

1. Go to the Firebase console (https://console.firebase.google.com/) and create a new project.
2. Once you have created your project, navigate to the "Database" section in the left sidebar and click on the "Realtime Database" tab.
3. Click on the "Create database" button and choose "Start in test mode" to allow anyone to read and write to your database.
4. To connect to the Firebase Realtime Database from your Java application, you will need to install the Firebase SDK using Maven or Gradle, and include it in your code. Here's an example of how to do this in Java:


```
// Import the Firebase SDK
import com.google.firebase.*;
import com.google.firebase.database.*;

// Initialize Firebase
FirebaseOptions options = new FirebaseOptions.Builder()
  .setApiKey("your_api_key")
  .setAuthDomain("your_auth_domain")
  .setDatabaseUrl("your_database_url")
  .setProjectId("your_project_id")
  .setStorageBucket("your_storage_bucket")
  .setMessagingSenderId("your_messaging_sender_id")
  .build();
FirebaseApp.initializeApp(options);
```


5.  Create the API endpoint(s) for your application. For example, here's a simple endpoint for creating a new record in the database:

```
app.post("/create", new Route() {
    @Override
    public Object handle(Request request, Response response) {
        // Get the new record from the request body
        Map<String, String> newRecord = new Gson().fromJson(request.body(), Map.class);
        
        // Get a reference to the database
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        
        // Push the new record to the database
        ref.push().setValue(newRecord);
        
        // Send a response
        response.status(200);
        return "Record created successfully.";
    }
});
```

6.  To deploy your API, you can use a hosting service such as Firebase Hosting or any other service that supports Java.

7.  Finally, you can test your API using a tool such as Postman or curl.

Please note that this is a basic example, it is recommended to also secure your API with Firebase Authentication and Firebase Cloud Firestore Security Rules.
You can find more detailed information and sample code in the Firebase Realtime Database documentation for Java: https://firebase.google.com/docs/database/admin/start

Also, you can use Firebase Admin SDK for Java to interact with Firebase Realtime Database, it has more functionalities like authentication, and security rules checking. https://firebase.google.com/docs/admin/setup.
Inventory Management Software System for Small Business
Published: 2023-01-11 09:48:48


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/srektnmeqz6s6ov53mjd.png)
Do you want to save time and money managing your inventory? Genic Solutions provide the best [inventory management system software](https://www.genicsolutions.com/inventory-management-system/) for you! With our easy-to-use platform, streamlining your inventory control and stock management has never been easier. Get started today and see the difference our software can make for your business.
Introduce IdentityCore.Adapter.AspNetMembership
Tags: csharp, dotnet, productivity, webdev
Published: 2023-01-11 09:47:53

### [IdentityCore.Adapter.AspNetMembership](https://github.com/realkarimfahmy/IdentityCore.Adapter.AspNetMembership)

Is a Adapter library that enables you to use [Microsoft Identity](https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-6.0&tabs=visual-studio) with existing code base using AspNetMembership user management
to have several new features like Two-Factor Authentication, Account Lockout, Account Confirmation, Password Reset, Security Stamp (Sign-Out Everywhere) and external login with existing Facebook, Google, Twitter or Live login.

Before, these features had to be coded,

so now developers can focus more on main business while using tested and standardized method to manage users.

### Required

.Net 6 Framework


### Installation

Install by [Nuget](https://www.nuget.org/packages/IdentityCore.Adapter.AspNetMembership)

```bash
  dotnet add package IdentityCore.Adapter.AspNetMembership
```
    
### Usage

if you are using the default schema of AspNetMemberShip without any customization

as well you can include identity options.
```csharp
services.AddIdentityAdapter(SqlConnectionString);

//or

services.AddIdentityAdapter(SqlConnection, opts =>
            {
                opts.Password.RequiredLength = 8;
                opts.Password.RequireNonAlphanumeric = true;
                opts.Password.RequireLowercase = false;
                opts.Password.RequireUppercase = true;
                opts.Password.RequireDigit = true;
            }); 
```
if you are using the customize schema of AspNetMemberShip create your own `CustomUserStore.cs` and `CustomRoleStore.cs` to adapted your customization  
```csharp
services.AddIdentityAdapter(SqlConnection, opts =>
            {
                opts.Password.RequiredLength = 8;
                opts.Password.RequireNonAlphanumeric = true;
                opts.Password.RequireLowercase = false;
                opts.Password.RequireUppercase = true;
                opts.Password.RequireDigit = true;
            }).AddUserStore<CustomUserStore>()
              .AddRoleStore<CustomRoleStore>(); 
```


#### 🔗 Links
[![linkedin](https://img.shields.io/badge/linkedin-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/realkarimfahmy/)
[![twitter](https://img.shields.io/badge/twitter-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/realkarimfahmy)
Install Java 11 on Amazon Linux 2
Tags: aws, amazonlinux, installjava11
Published: 2023-01-11 09:35:31

---
title: Install Java 11 on Amazon Linux 2
published: true
description:
tags: aws,amazonlinux, installjava11
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-01-11 09:19 +0000
---

#### First SSH Your Linux Machine

![SSH EC2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lp64c1goif6u0wqu1eia.png)

### Run the yum update command. Optionally, you can add the --security flag to apply only security updates

Command: sudo yum update


## ![yum update](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pizdi1mpnm6rkie0u5iy.png)



## In order to install java 11:

sudo amazon-linux-extras install java-openjdk11

![Java Install](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lq1mktxdkm03h95mlooo.png)

Type "Y" for install packages

![Y](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rfcwadmlxev2k1c8hrrl.png)


![Package installation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/11ol2ic9fb6dvq0hptf8.png)


Wait until all packages finished install

![Finished Install](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49awli7gtx9eqbstra46.png)

## Check Java Instillation
Command: java -version

![Java Check](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/irvv3vohhj3wb8ra3hst.png)
HOW TO Earn Money on dev.to
Published: 2023-01-11 09:30:51




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4kefemk0nwaa1yx055d.png)
Writing articles: Share your knowledge and experiences with the community by writing articles on various topics related to programming, software development, and technology. The more views and engagement your article receives, the more money you can earn through the Dev.to Partner Program.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llsy1cpitrkk57cfak6l.png)
Creating tutorials: Share your expertise by creating detailed tutorials on a specific programming language, framework, or tool. This can help others learn new skills and you can earn money through the Partner Program.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vxs6shkbfpff39shb3m.png)
Participating in discussions: Engage in conversations and discussions within the community by commenting and answering questions on articles and posts. This can help you gain visibility and establish yourself as an expert in a certain area.

Building a following: Build a following by consistently sharing valuable content and engaging with the community. As your following grows, you may be able to monetize it through sponsorships, affiliate marketing, or consulting work.

Sponsored posts: Companies and individuals may pay you to write sponsored posts or reviews on Dev.to. You can reach out to them to see if they are interested in working with you.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mn0pm3j2g2sdjhq3uq8z.png)
Freelancing: You can use Dev.to as a platform to showcase your portfolio, skills, and experience to potential clients. You can also apply for freelance projects posted on the platform.
An error occurred while installing rjb (1.6.4), and Bundler cannot continue.
Tags: rjb, rails, errors
Published: 2023-01-11 09:26:54

I face this error around installing rjb gem. 
I have found a solution after searching on [here](https://www.cnblogs.com/qinyan20/p/14392974.html).
but in other language, I decide to make it easy solution for all. so let's move to point.
here is the error 
Could not create Makefile due to some reason, probably lack of necessary

libraries and/or headers.  Check the mkmf.log file for more details.  You may

need configuration options.

 

Provided configuration options:

--with-opt-dir

--without-opt-dir

--with-opt-include

--without-opt-include=${opt-dir}/include

--with-opt-lib

--without-opt-lib=${opt-dir}/lib

--with-make-prog

--without-make-prog

--srcdir=.

--curdir

--ruby=/home/admin/.rvm/rubies/ruby-2.7.2/bin/$(RUBY_BASE_NAME)

extconf.rb:54:in `<main>': JAVA_HOME is not set. (RuntimeError)

 

extconf failed, exit code 1
1: install java related things 
`sudo apt install default-jre`              # version 2:1.11-72, or

`sudo apt install openjdk-11-jre-headless`  # version 11.0.9.1+1-0ubuntu1~20.04

`sudo apt install openjdk-8-jre-headless`   # version 8u275-b01-0ubuntu1~20.04

`sudo apt install openjdk-13-jre-headless ` # version 13.0.4+8-1~20.04

`sudo apt install openjdk-14-jre-headless`  # version 14.0.2+12-1~20.04`

2: `sudo apt install openjdk-8-jre-headless`

3: cd 
`export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64`

Could not create Makefile due to some reason, probably lack of necessary

libraries and/or headers.  Check the mkmf.log file for more details.  You may

need configuration options.

 

Provided configuration options:

--with-opt-dir

--without-opt-dir

--with-opt-include

--without-opt-include=${opt-dir}/include

--with-opt-lib

--without-opt-lib=${opt-dir}/lib

--with-make-prog

--without-make-prog

--srcdir=.

--curdir

--ruby=/home/admin/.rvm/rubies/ruby-2.7.2/bin/$(RUBY_BASE_NAME)

extconf.rb:46:in `open': No such file or directory @ dir_initialize - /usr/lib/jvm/java-8-openjdk-amd64/include (Errno::ENOENT)

from extconf.rb:46:in `<main>'

4: `sudo apt-get install openjdk-8-jdk`
and now is the final step 
5: `gem install rjb -v '1.6.4'`
success!!