teleren/devto huggingface dataset:
Differences between lastChild and lastElementChild DOM element property in JavaScript
Tags: javascript
Published: 2020-10-15 00:00:00

---
  title: Differences between lastChild and lastElementChild DOM element property in JavaScript
  published: true
  tags: JavaScript
  date: Thu Oct 15 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/difference-between-lastchild-and-lastelementchild-element-property-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-c6ccbe5e6a8b9dec458555f1220844bf.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/difference-between-lastchild-and-lastelementchild-element-property-javascript)
  
The core difference between the `lastChild` and `lastElementChild` DOM element properties is that,

- The `lastChild` DOM element property returns a `text`, `comment`, or an `Element` that comes as the last in a parent element. Put simply, it returns the last thing whether it may be of `text`, `comment`, or an `Element` type.

- The `lastElementChild` element property, on the other hand, returns the last `Element` type as the value. Even If there are `text` or `comment` which comes after it, it doesn't return the `text` or the `comment` as the values.

Let's look at an example.

Consider this `div` tag with:

- `span` tag
- `text` of `Hello World!`
- a `paragraph` tag
- another text of `Hai, I'm another simple text`

inside it as its children.

```html
<div>
  <span>I'm inside a SPAN tag</span>
  Hello World!
  <p>I'm a paragraph</p>
  Hai, I'm another simple text.
</div>
```

Now let's use the `lastChild` and the `lastElementChild` DOM element properties on the `div` element to check what it returns.

```js
// get reference to the div tag
const div = document.querySelector("div");

// lastChild DOM element property
const lastChild = div.lastChild;

// lastElementChild DOM element property
const lastElementChild = div.lastElementChild;

console.log(lastChild); // Hai, I'm another simple text.

console.log(lastElementChild); // <p>I'm a paragraph</p>
```

As you can see the `lastChild` returns the last text content `Hai, I'm another simple text` and the `lastElementChild` returns the last element i.e `para` tag (`<p>I'm a paragraph</p>`).

See this example live in [JSBin](https://jsbin.com/pavotazafi/1/edit?html,js,output).

### Feel free to share if you found this useful 😃.

---
Build an Election Texting bot with Twilio, Node, and Cron
Tags: node, cron, twilio, javascript
Published: 2020-10-15 00:00:00

---
date: "2020-10-15"
title: "Build an Election Texting bot with Twilio, Node, and Cron"
tags: ['node', 'cron', 'twilio', 'javascript']
published: true
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/boq8zsq5niplaikq9o6o.jpg
---

## Intro
To celebrate the upcoming election, we decided to learn Twilio and make a passive aggressive texting bot to remind ourselves and our friends to go vote. In this video, we walk you through how to create some text messages and automatically text them via the Twilio api. Help spread the word about voting by using the power of code. See http://vote.org to check your voter registration.

## Video
{% youtube OekQnPcXTRg %}


## Resources
- https://www.twilio.com/docs/sms/quickstart/node#install-nodejs-and-the-twilio-module
- https://github.com/node-cron/node-cron
- https://www.geeksforgeeks.org/how-to-generate-random-number-in-given-range-using-javascript/
Useful Free APIs — Anti-Malware
Tags: productivity, codenewbie, beginners, webdev
Published: 2020-10-14 23:39:37

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

In the software development world, practice makes perfect. Therefore, we should find as many ways to practice programming as possible. With free public APIs, we can practice programming by creating apps that use those APIs.

In this article, we’ll look at some practice project ideas that can use some of those APIs.

### Anti-Malware

There are APIs that let us prevent hacker attackers on the Internet that we can use for free.

### AbuseIPDB

The AbuseIPDB API lets us get the reputation of the IP, domain, or URL.

An API key is required for authentication.

We can use it to check an IP, domain, or URL in various blacklists and reports.

Also, we can get IP addresses that have good reputations.

There’s in usage limit to this API.

### Google Safe Browsing

The Google Safe Browsing API lets us check a URL with it to let us know whether a URL is reputable or not.

We can use it to find out whether the URL is safe to make a request to or not.

An API key is used to access this API.

### urlscan

The urlscan API lets us check whether a URL is a phishing URL.

Like the Google Safe Browsing API, it lets us check against a database to see whether a link is safe and which website we can trust.

An API key is used to access this API.

There’s a rate limit imposed on this API.

Submissions of URLs can be done automatically with this API.

### VirusTotal

The VirusTotal API lets us upload a file to check if there’re any viruses in it.

We can retry the scan.

We need permission to upload files bigger than 32MB in the size.

Permission can also be obtained from this API.

Also, we can use it to check whether a URL is safe to go to.

And we can also check domains and IPs to see if they’re safe.

An API key is required to access this API.

### Web Of Trust (WOT)

The Web Of Trust (WOT) API is another API that lets us check the reputation of a website.

We can submit a URL and this API will return whether this URL is safe to go to or not.

An API key is required to access this API.

### Conclusion

We can use various APIs to get us check whether a URL, domain, IP, or file is safe with some free APIs.
How to pick properties from an interface
Tags: typescript, beginners, webdev
Published: 2020-10-14 22:55:42

---
title: How to pick properties from an interface
published: true
date: 10/15/2020
tags: typescript, beginners, webdev
canonical_url: https://adamlacombe.com/blog/typescript-how-to-pick-properties-from-an-interface
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/1k75ys45s0ieprhs4p5b.png
---

You can use the built-in type [Pick](https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys). `Pick<MyInterface, "prop1" | "prop2">` is a built-in type which allows you to pick specific properties from an interface.

A great use-case would be verifying user credentials. You might have a `User` interface such as the following:


```typescript
interface User {
  id: number;
  firstName: string;
  lastName: string;
  email: string;
  password: string;
}
```

Instead of creating a new interface with the `email` and `password` properties from the `User` interface, lets `Pick` them! 

```typescript
// without Pick
async function verifyLoginCredentials(credentials: { email: string, password: string }) {
  // ... ...
}

// with Pick
async function verifyLoginCredentials(credentials: Pick<User, "email" | "password">) {
  const user = await getUserByEmail(credentials.email);

  if (!passwordMatches(credentials.password, user.password)) {
    throw new BadRequestError('incorrect password');
  }

  return user;
}

verifyLoginCredentials({ email: "example@example.com", password: "123" });
```
My First npm Package - A Custom React Theme
Tags: react, npm, beginners, webdev
Published: 2020-10-14 22:50:52

After being sick and tired of constantly having to delete and rearrange the `create-react-app` boilerplate, I finally made a custom [stripped-down React template](https://github.com/timmybytes/timmybytes-template#readme) for starting new projects. So far it doesn’t include anything extraordinary (though I did incorporate my SCSS boilerplate called [SPLATE](https://github.com/timmybytes/splate)), but it removes all of the extraneous defaults for new React apps. I also managed to setup GitHub Actions to automatically release new versions to the npm registry when I update the `main` branch. 

If you’d like to try it out, you can use it via `npx create-react-app [name-of-your-app] --template timmybytes-template`. I’ll be adding more helpful starting features, and more automation for deployment.
Sticky navigation bar without JavaScript
Tags: javascript, css, frontend, webdev
Published: 2020-10-14 22:48:25

Have you ever wanted to create a sticky menu, but without the hassle of writing extra JavaScript for it? CSS got you covered now!

![Example animation of a sticky menu bar](https://dev-to-uploads.s3.amazonaws.com/i/tciln4pch883qdzbsjw1.gif)

The key for success is the property `position: sticky`. And despite it being marked as "partial support" for the majority browsers, it is working pretty well. The "partial" is due to the fact that some browser don't deal with that property correctly in some table setups. If you do not use tables and don't want some stickiness there, you're good to go.

The following is my code change on my [personal site][mtt]:

## Before

### JavaScript

```javascript
const navbar = document.querySelector('.navbar');
let sticky = navbar.offsetTop;
const navbarScroll = () => {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add('sticky')
  } else {
    navbar.classList.remove('sticky');
  }
};

window.onscroll = navbarScroll;
```

### Stylesheet

```css
.navbar {
  position: relative;
}
.sticky {
  position: fixed;
  top: 0;
  left: 0;
}
```

## After

### JavaScript

```javascript
// nope
```

### Stylesheet

```css
.navbar {
  position: sticky;
  top: 0; /* it does not reposition right away,
             but determines at which point it sticks */
}
```

As the comment states, you will need `top` to tell where to stick once the element scrolled to it. Meaning: as long as you have not scrolled the bar up to top zero of your current view, it will keep scrolling up. Afterwards it stays there.

Not tested, but this could also work in all other directions. Someone up for a bottom bar? ;-)

## Conclusion

I think 2 lines of CSS are better than several in CSS and JS.

What's not present yet is a way to apply different style when stuck or not, since there is no CSS selector for that. Dunno if that will ever come, but one can hope.

I recently blogged about this and JS usage in general in my article [»How I wrote JavaScript to avoid JavaScript«][mtt-nojs] - don't worry, you do not have to throw away everything like I did. But I want to give you some food for thought. Maybe you realize you solved your problems with way too much JS.

Also check out the specs and development of HTML and CSS standards, there are always interesting things to discover. One of the biggest changes in recent years were flexboxes and grids, I guess many web designers welcomed these additions.

[mtt]: https://markentier.tech/ "markentier.tech - a blog about code, tech, and people"
[mtt-nojs]: https://markentier.tech/posts/2020/10/wrote-javascript-to-avoid-javascript/
Hacktoberfest-Accepted
Tags: hacktoberfest
Published: 2020-10-14 22:48:01

## What I Learned From Hacktoberfest

I contributed to repositories of DSA to give unique adhoc problems which have a specific way of solving and helps coders in intensive understanding of the specific problem. But moreover it strengthened my concepts based on git ,contributed open source and taught me how to improve code quality
These days I see on dev: Hacktober completed + Spam messages 😁. Anyone with article?
Published: 2020-10-14 22:17:50

Hello friends, 
I spend more time on dev.to than any other community or social media platform.

I am happy to see Hacktober is doing fine here but our lovely spammers are visiting dev.to and dropping by customer care number.😁👏👏👏
Cloud Native Developer Summit video replay
Tags: conference, events, ibmcloud, ibmdeveloper
Published: 2020-10-19 18:05:52

---
title: Cloud Native Developer Summit video replay
published: true
date: 2020-10-14 22:13:28 UTC
tags: Conference,Events,IBMCloud,IBMDeveloper
canonical_url: https://maxkatz.org/2020/10/14/cloud-native-developer-summit-video-replay/
---

[Julia Nash](http://GrrrlTech) and [Upkar Lidder](https://twitter.com/lidderupk) from [IBM Developer](http://developer.ibm.com) hosted a half-day a Cloud Native Developer Summit on Tuesday, October 13, 2020. In case you missed the live event you can watch a replay of the entire [event](https://www.crowdcast.io/e/cloud-native-dev-summit) (event agenda is right after the image).

[![](https://katzmax.files.wordpress.com/2020/10/cloudnative-dev-summit.png?w=1024)](https://www.crowdcast.io/e/cloud-native-dev-summit)<figcaption>Watch replay: <a rel="noreferrer noopener" href="https://www.crowdcast.io/e/cloud-native-dev-summit" target="_blank">https://www.crowdcast.io/e/cloud-native-dev-summit</a></figcaption>

8:45 AM
**_Welcome_**!
Julia Nash, Upkar Lidder

9 AM
_**Why Cloud Native Requires Chaos Engineering**_
Ana Margarita, Gremlin

9:30 AM
**_Building Cloud Native Apps with Knative and TektonCD_**
Carlos Santana, IBM

10:00 AM
_**Cloud Native Hands-on Workshop**_
Alex Parker, IBM

10:30 AM
_**10 useful techniques to make sense of Istio**_
Lin Sun, IBM

11 AM
_**Service Mesh and Enterprise Level Design**_
Shweta Vohra, IBM

11:30 AM
_**Serverless Deployment of a Reactive Microservice to the Modern Cloud Infrastructure**_
Mary Grygleski, IBM
My #100DOC - Day 49
Tags: 100daysofcode, challenge
Published: 2020-10-14 21:22:51

1. **[Redesign of my portfolio](https://github.com/pablohs1986/pablohs1986.github.io)** (1h):<br>I continued working on expandProjectOnClick function.
    
#### **What I learned**: 
* Review of JavaScript events.

#### **Total time**:
1h.
Refactoring: Dependency Injection for Reusable Functions
Tags: typescript, javascript, refactoring
Published: 2020-10-14 21:21:48

```typescript
// In this reusable View component,
// the context of its table
// is injectable with 
// context from elsewhere. 
// This means as a child
// View, others can inject
// the context.

 setTableData(context: any) {
  this.showTable = true;
  this.cdf.detectChanges();
  // Use the reusable function here
  funcSetTableData(
   context, // outside data
   this.paginator, // view 
   this.pageSize,  // number
   this filter,    // string
   this.sort,      // view
  );
  // Back to the view component here
}
 
```
Notice that the reusable function is taking in four "this." values. Two of them are Views contained in this View and the other two are string and numeric values respectively. We are "injecting" the reusable function with local values. 

From the perspective of this View Component, this is close-coupling; however, the function itself doesn't care where the parameters come from. 

Functions just require the proper parameters to work. This means that functions themselves are not close-coupled.

If we create another material table View which re-uses this function it will inject its own required proper dependencies. 

We created the function, funcSetTableData when we spotted a possible refactor while thinking about reusability. The number of 'this.' parameters was a clue too. 

Had we not moved it into a function library it would have only been known to this View. This is the mal effect of "close-coupling" and not thinking of reusability.
Mocking http clients in Go
Tags: go, testing, tdd
Published: 2020-10-14 20:54:19

If you ever find yourself needing intercept a http client in go, [httptest](https://golang.org/pkg/net/http/httptest/#NewServer) provides a facility to do just that. `httptest.NewServer` lets you stand up a temporary server that you can control in your test case.

We will use this function as an example of writing unit tests that use httptest.NewServer.

```golang
func topPostOnSubreddit(r string) (string, error) {
	resp, err := http.Get(fmt.Sprintf("https://reddit.com/r/%s", r))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	dec := json.NewDecoder(resp.Body)
	var data redditData
	err = dec.Decode(&data)
	if err != nil {
		return "", err
	}

	top := findTopPost(data)
	return top["title"].(string), nil
}
```

# Refactor

Let refactor this so we can use httptest.NewServer in our unit tests. The required changes are ...

## An instance of http client has to be passed in

```golang
func topPostOnSubreddit(client *http.Client, r string) (string, error) {
    req, err := http.NewRequest("GET", fmt.Sprintf("https://reddit.com/r/%s", r), nil)
	if err != nil {
		return "", err
	}
	resp, err := client.Do(req)
    // ...
}
```

## The base of the url has to be configurable by the caller

```golang
func topPostOnSubreddit(client *http.Client, fullUrl string) (string, error) {
    req, err := http.NewRequest("GET", fullUrl, nil)
	if err != nil {
		return "", err
	}
	resp, err := client.Do(req)
    // ...
}
```

# Writing the Test Case

The returned test server has both the client and url available for you to pass to the function. When the function uses the client makes the http call the handlerFunc you defined in your test case is called. This allows you to inject fixture data into the runtime to control unit test behavior.

```golang
func TestTopPostOnSubreddit(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        enc := json.NewEncoder(w)
        // this is where your test fixture goes
		testData := redditData{}
		err := enc.Encode(&testData)
		require.NoError(t, err)
	}))
	t.Cleanup(server.Close)

	url := fmt.Sprintf("%s/r/android.json", server.URL)
	top, err := topPostOnSubreddit(server.Client(), url)
	require.NoError(t, err)
	require.Equal(t, "foobar", top)
}
```

## Happy Testing!
Starter Kit for Static Websites 🚀
Tags: webdev, npm, showdev, javascript
Published: 2020-10-14 20:51:58


##parcel-static-site-starterkit

A minimalistic(simple) starter kit for Static Websites with out of the box ES6+ and SCSS support. No Config needed. [Project On Github](https://github.com/InsaneNaman/parcel-static-site-starterkit)

---

### Features 🚀

1- Compatible with All Static Site like Bootstrap Template

2- Out of the box Uglifying/ Minifying of CSS, HTML, JS

3- SCSS Support

4- ES6+ Support

5- Hot Reloading

6- Runs on a local server

7- Auto prefixing - Support IE10 and last 4 versions of all browsers

---

### When and Why should you use this project? 😯

1- No setup required. Just one command to start developing.

2- Provides out of the box ES6+ and SCSS support. No config needed.

3- If you are a beginner and following some tutorial then you can code on your machine hassle-free.

4- If you want to test something locally and you need a preconfigured environment for a static site.

5- You have a website and want to deploy it on production.

---

### How to use 🧐

`Make sure you have node installed. If not, I recommend installing via` [nvm(Node Version Manager)](https://github.com/nvm-sh/nvm)

1- Clone project - 
👉 `git clone https://github.com/InsaneNaman/parcel-static-site-starterkit.git`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gscnt5n3qpkaxu1c8y33.gif)

2- Navigate to that directory
👉 `cd parcel-static-site-starterkit/`

3- Install dependencies 
👉 `npm i` or `yarn`

> This would install dependencies (required libraries) under `node_modules` folder.

4- Run Project
👉 `npm run start`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/1ny0oogh7culvbx8vpk6.gif)

🎉🎉🎉🎉 That's it. Your website is live on `localhost:1234`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/guux97xwco2tya5eedok.png)


5- Put/Write your code in `src` folder

> There are sample files already present (feel free to delete them and add yours) to give you an idea about the architecture. You only need to care about just one file i.e, `index.html` and that you must put/create at the `src` (`src/index.html`) folder level.

### Ready to build?

👉 `npm run build` or `yarn run build`

This will generate `dist` folder that you can deploy to anywhere like [Netlify](https://netlify.com), [Firebase](https://firebase.com) or wherever you like. 

> Here is a list of [Free hosting Services](https://dev.to/insanenaman/15-easy-peasy-services-to-deploy-your-static-webapp-for-free-4m2b) 🔥

[Starter Kit On Github](https://github.com/InsaneNaman/parcel-static-site-starterkit)

That's it for today. Feel free to provide any type of feedback/report error. I do appreciate that. Meanwhile, you can find me on Twitter [@InsaneNaman](https://twitter.com/InsaneNaman).

Signing off. See you soon.

---
> For every minute you are angry you lose sixty seconds of happiness. So, keep smiling. 😉 
---
Hacktoberfest 2020
Tags: hacktoberfest
Published: 2020-10-14 20:49:57

#opensource #git #gitcommands
I was a beginner who didn't know much about opensource and how to use github so all thanks to hacktoberfest which made me interested in learning open source through which we can contribute and make someone else's project a better version of former or others can help you too. I also learnt about git commands.
My github profile-https://github.com/illuminati490
Micronaut integration testing using testcontainers
Tags: java, micronaut, testcontainers, junit
Published: 2020-10-14 20:35:55

Micronaut is a modern, JVM-based, full-stack framework for building modular, easily testable microservice and serverless applications. Concepts, API, annotations, and conventions are similar to Spring Framework, but some features should be done differently or missing.

One of these missing is ApplicationContextInitializer which is really handy for application context configuration in runtime, before component initialization. This feature is used to get Testcontainers instance host and port, as Testcontainers uses randomized ports for each container it starts, but makes it easy to obtain the actual port at runtime. 

Spring Boot configuration and ApplicationContextInitializer described with great details in the [article]( https://dev.to/sivalabs/springboot-integration-testing-using-testcontainers-starter-13h2), and here I will try to fill the gap for Micronaut.

#### Option1. Lazy and deprecated.
`withCreateContainerCmdModifier` could be used to set known port instead of random.
```java
public abstract class ResourceProvider {

    private static final int REDIS_PORT = 6379;

    @Container
    static GenericContainer redis = new GenericContainer<>("redis:5.0.8-alpine")
            .withCreateContainerCmdModifier(it -> it.withName("redis-unit")
                    .withPortBindings(new PortBinding(Ports.Binding.bindPort(REDIS_PORT), new ExposedPort(REDIS_PORT))))
            .withExposedPorts(REDIS_PORT);

}
```
but, `withPortBindings` deprecated, and will be removed in future releases. Main idea behind this, is virtualization and scoping. Your application tests should be independent, so they could be executed in parallel, using same docker. From the other hand same Docker/Jenkins environment frequently used for multiple projects, and in this case you will receive "Bind for 0.0.0.0:6379 failed: port is already allocated" when both tests will require same container.
#### Option2. Micronaut way solution.
Micronaut offers `PropertySource` concept to initiate application configuration with host/port values obtained from testcontainer.
Example for `EmbeddedServer`
```java
@BeforeAll
public static void initUnitTest() {

    embeddedServer = ApplicationContext.run(EmbeddedServer.class, PropertySource.of(
            "test", Map.of("redis.host", redis.getContainerIpAddress(), "redis.port", redis.getMappedPort(REDIS_PORT))
    ));

    context = embeddedServer.getApplicationContext();

}
```
Example for `ApplicationContext`
```java
@BeforeAll
public static void initUnitTest() {
    context = ApplicationContext.run(PropertySource.of(
            "test", Map.of("redis.host", redis.getContainerIpAddress(), "redis.port", redis.getMappedPort(REDIS_PORT))
    ));
}
```
End to end demo could be found [here](https://github.com/major13ua/micronaut-tc).
Happy codding and testing!