teleren/devto huggingface dataset:
Interpreter Pattern
Tags: designpatterns, java, pattern, behavioral
Published: 2020-10-09 00:24:16

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

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

#Participants
* AbstractExpression: declares an interface for executing an operation
* TerminalExpression: implements an Interpret operation associated with terminal symbols in the grammar.
An instance is required for every terminal symbol in the sentence.
* NonterminalExpression: one such class is required for every rule R ::= R1R2...Rn in the grammar.
Maintains instance variables of type AbstractExpression for each of the symbols R1 through Rn.
Implements an Interpret operation for nonterminal symbols in the grammar. Interpret typically calls itself recursively on the variables representing R1 through Rn.
* Context: contains information that is global to the interpreter
* Client: builds (or is given) an abstract syntax tree representing a particular sentence in the language that the grammar defines. The abstract syntax tree is assembled from instances of the NonterminalExpression and TerminalExpression classes. Invokes the Interpret operation

#Code#
```java
public class Main {

	public static void main(String[] args) {
		Context context = new Context();
		List<AbstractExpression> list = new ArrayList<>();
		list.add(new TerminalExpression());
		list.add(new NonterminalExpression());
		list.add(new TerminalExpression());
		list.add(new TerminalExpression());

		for (AbstractExpression exp : list) {
			exp.interpret(context);
		}

	}
}

public class Context {
}

public interface AbstractExpression {
	void interpret(Context context);
}

public class TerminalExpression implements AbstractExpression {

	@Override
	public void interpret(Context context) {
		System.out.println("Called Terminal.interpret()");
	}
}

public class NonterminalExpression implements AbstractExpression {

	@Override
	public void interpret(Context context) {
		System.out.println("Called Nonterminal.interpret()");
	}
}
```

#Output#
```
Called Terminal.interpret()
Called Nonterminal.interpret()
Called Terminal.interpret()
Called Terminal.interpret()
```

{% github https://github.com/eidherjulian61/design-patterns no-readme %}
{% link https://dev.to/eidher/principales-patrones-de-diseno-13ao
 %}
Testable go with function types
Tags: go, tdd, testing
Published: 2020-10-09 00:10:16

A helpful pattern I've picked up writing test cases for go code is called [Ports and Adapters](https://www.thinktocode.com/2018/07/19/ports-and-adapters-architecture/). Skipping past long blog post with theory lets get into how this can look in typical go code.

```golang
func TellEveryBobHeSmells() error {
    emailSvc := getEmailService()
    db := getDBConn()
    rows := db.Exec(`select bobs from db`)
    for row.Next() {
        var bobsEmail string
        err := rows.Scan(&bobsEmail)
        if err != nil // ...
        err = emailSvc.SendSpiceyEmail(bobsEmail)
        if err != nil // ...
    }
}
```

This function is going to be very annoying to test. It takes no inputs and reaches out to 2 external services. First to get a list of bobs and another to send emails. Lets refactor this code to be more testable.

```golang
type sendSpicyEmailFn = func(email string) error
type bobFinderFn = func() ([]string, error)

func tellEveryBobHeSmells(findBobs bobFinderFn, sendEmail sendSpicyEmailFn) error {
    bobs, err := findBobs()
    if err != nil // ...
    for _, email := bobs {
        err := sendEmail(email)
        if err != nil // ...
    }

    return nil
}
```

We created two "ports" to abstract away the side effects of the implementation. `sendSpicyEmailFn` and `bobFinderFn`. Now our test cases can control the behavior of these functions. You can imagine writing a unit test for this function without even providing a database in the test suite.

```golang
// now we write a public wrapper function that fills in
// the adaptors so our callers dont have to care about ports/adaptors
func TellEveryBobHeSmells() error {
    // note we still passing in dependencies to the adaptors
    db := getDBConn()
    findBobs := defaultBobFinderFn(db)

    emailSvc := getEmailService()
    sendEmail := defaultSendSpicyEmailFn(emailSvc)
    
    return tellEveryBobHeSmells(findBobs, sendEmail)
}

// adaptor implementations
func defaultBobFinderFn(db *DB) bobFinderFn {
    return func() ([]string, error) {
        var bobs []string
        rows := db.Exec(`select bobs from db`)
        for row.Next() {
            var email string
            err := rows.Scan(&email)
            if err != nil // ...
            bobs = append(bobs, email)
        }

        return bobs, nil
    }
}

func defaultSendSpicyEmailFn(svc *EmailSvc) sendSpicyEmailFn {
    return func(email string) error{
        return emailSvc.SendSpiceyEmail(email)
    }
}
```

Now that we have cut apart the function into its business logic and external dependencies it is much easier to test. In general I would create a unit test for `tellEveryBobHeSmells` and the two adaptors `defaultBobFinderFn` and `defaultSendSpicyEmailFn` but skip the test case for `TellEveryBobHeSmells`.
Type Pattern Matching - CORBA Style
Published: 2021-01-10 11:11:46

---
title: Type Pattern Matching - CORBA Style
published: true
date: 2020-10-09 00:00:00 UTC
tags: 
canonical_url: http://ikysil.github.io/type-pattern-matching-CORBA-style/
---

```
package io.github.ikysil.javaplayground.narrow;

import java.util.List;
import java.util.Optional;

public class TypeNarrowDemo {

    static final class Types {

        private Types() throws IllegalAccessException {
            throw new IllegalAccessException();
        }

        static <T> T narrowToNull(final Object obj, final Class<T> expectedType) {
            if (expectedType.isInstance(obj)) {
                return expectedType.cast(obj);
            }
            return null;
        }

        static <T> Optional<T> narrow(final Object obj, final Class<T> expectedType) {
            return Optional.ofNullable(obj)
                .map(o -> narrowToNull(o, expectedType));
        }

    }

    public static void main(String[] args) {
        System.out.println("TypeNarrowDemo Demo");
        if (Types.narrowToNull("test", Object.class) != null) {
            System.out.println("SUCCESS: String is Object");
        }
        Types.narrow("test", Object.class)
            .ifPresent(o -> System.out.println("SUCCESS: String is Object: " + o));
        if (Types.narrowToNull("test", List.class) == null) {
            System.out.println("SUCCESS: String is NOT List");
        }
        Types.narrow("test", List.class)
            .ifPresentOrElse(
                o -> System.out.println("ERROR: String is NOT List: " + o),
                () -> System.out.println("SUCCESS: String is NOT List")
            );
    }

}

```

GitHub Repository: [java-playground](https://github.com/ikysil/java-playground)
How to get the count of child elements of an element using JavaScript?
Tags: javascript
Published: 2020-10-09 00:00:00

---
  title: How to get the count of child elements of an element using JavaScript?
  published: true
  tags: JavaScript
  date: Fri Oct 09 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/length-of-child-elements-from-parent-element
  cover_image: https://melvingeorge.me/_next/static/images/main-51a32cc188f07ff7f5ef8ad390ca6a42.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/length-of-child-elements-from-parent-element)
  
To get the count of child elements inside a parent element, You can use the

`childElementCount`

property in the DOM element in JavaScript.

Let's say we have a `div` element with some `paragraph` elements inside it like this,

```html
<div>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
  <p>I'm a Paragraph</p>
</div>
```

Now let's get the count of the child `paragraph` elements using the `childElementCount` property in the `div` element.

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

// get the length of children
// inside the div element
const lengthOfChildren = div.childElementCount;

console.log(lengthOfChildren); // 13
```

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

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

---
Is it Visual studio or online MMORPG?
Published: 2020-10-08 23:48:31

### What is it? 🤷‍♂️
[CyberCode Online](https://cybercodeonline.com/) is a Cyber Punk inspired, Text Based MMORPG Browser Game where gameplay interface are 'Stealthily' mimicking the VSCode interface. To start, please Login or Register by typing your email and password on the string variable, then click login/signUp function to proceed.
### CyberCode Online Community 👋
The CyberCode online community is one of the friendliest I have every had the pleasure of speaking with. They were really helpful to get started. If you want to connect with other players, or there is something you want to talk to me about you can find me at CyberCode Online's [Discord Channel](https://discord.gg/JREx8xz).

![Screenshot 2020-10-04 011527](https://dev-to-uploads.s3.amazonaws.com/i/24tqimrip70c4z7oos73.png)

### There is also a mobile app 📱
The mobile app does not have the stealthy visual appearance but is just as fun. You can get it for free on the [Google Play](https://play.google.com/store/apps/details?id=com.cybercodeonline.cybercode) store. 

### Gameplay 🕹️
Calm and relaxing but interesting and addictive! Best of all is the appearance since you are able to play it at work and none of your colleges will notice.

![Screenshot 2020-10-04 012325](https://dev-to-uploads.s3.amazonaws.com/i/fu10rt65b37ibna11k1l.png)
Pull (fetch) from a forked GitHub repository
Tags: github, hacktoberfest
Published: 2020-10-08 09:22:42

You are working on a project outside of your or your organisation account--an open source project for [Hacktoberfest](https://dev.to/devteam/happy-hacktoberfest-here-s-how-to-show-up-for-open-source-this-month-4cee), perhaps. You forked the repo and started working on it.

Meanwhile, the original repo has been updated with new changes. To prevent conflict, you need to pull these changes from the _original_ repo and merge it to your local, forked branch. But wait... how do you do that? ❓🤔

Follow these steps and you'll be good to go. 😎

(1) add remote

```sh
git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
```

(2) fetch

```sh
git fetch upstream
```

Commits to the remote `main` branch will be stored in a local branch called `upstream/main` (same with other branches).

(3) merge to local, then merge to your working branch (if necessary)

```sh
git checkout main
git merge upstream/main

# merge to working branch
git checkout eka/working-branch
git merge main
```

Done!

## References
- https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/configuring-a-remote-for-a-fork
- https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/syncing-a-fork
Luxon to Django Forms
Tags: javascript, django, vue, luxon
Published: 2020-10-08 23:35:31


The following is a micro tutorial, on how I sent dates from the front end using Luxon to my backend Django.

# Dot Point Context

- User will record start and end date for their project in NearBeach 
- The datetime picker used is [vue-datetime](https://github.com/mariomka/vue-datetime) for the datetime picker.
- Vue-datetime uses the new [Luxon](https://moment.github.io/luxon/) library
- The project I am talking about is this micro tutorial is [NearBeach](https://github.com/robotichead/NearBeach)

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

# Method

The vue-datetime widget wants the datetime input to be a simple string. So - lets convert

```
this.localEndDateModel = this.endDateModel.toISO();
this.localStartDateModel = this.startDateModel.toISO();
```

When the user hits the submit button, we use Axios to send the data through the POST method. First we have to compile the data we want to send

```
//Create data_to_send
const data_to_send = new FormData();
data_to_send.set('project_name',this.projectNameModel);
data_to_send.set('project_description',this.projectDescriptionModel);
data_to_send.set('organisation',this.stakeholderModel['value']);
data_to_send.set('project_start_date',this.projectStartDateModel);
data_to_send.set('project_end_date',this.projectEndDateModel);

// Insert a new row for each group list item
this.groupModel.forEach((row,index) => {
    data_to_send.append(`group_list`,row['value']);
});
```

As you can see in the code - it does not matter that we are sending the string value. We will be modifying the Django Form to accept this string value.

In the Django form, we want to edit the input format for the datetime fields to accept the [ISO_8061](https://en.wikipedia.org/wiki/ISO_8601). This requires placing the attribute `input_formats=['c'],` inside the DateTimeField.

```
class NewProjectForm(forms.ModelForm):
    project_start_date = forms.DateTimeField(
        input_formats=['c'],
    )
    project_end_date = forms.DateTimeField(
        input_formats=['c'],
    )
    group_list = forms.ModelMultipleChoiceField(
        required=True,
        queryset=group.objects.filter(
            is_deleted=False,
        )
    )

    # Basic Meta Data
    class Meta:
        model = project
        fields = [
            'project_name',
            'project_description',
            'project_start_date',
            'project_end_date',
            'organisation',
        ]
```

The form will now accept your Luxon iso string.

## Quick notes

The ISO 8061 standard was implemented in Django 3.1 as discussed in the [release notes](https://docs.djangoproject.com/en/3.1/releases/3.1/)
Hacktoberfest 4 of 4
Tags: hacktoberfest, 11ty
Published: 2020-10-08 22:32:04


![completed progress bar. Show 4 filled in boxes ](https://dev-to-uploads.s3.amazonaws.com/i/ekhzparqr6g09yi9pctq.jpg)

I have completed HacktoberFest2020. I had my fourth PR accepted for the month. 

>You did it! Congratulations on submitting four (or more) pull requests and contributing to open source projects this month.

I had wanted join Hacktober to since I learned of the challenge. I registered last year. During the preview time I found an issue. I coded it and submitted a PR. But it didn't count for my total since It was done before the event started. I jumped the gun. During that October things were busy and I didn't come back to work on projects. This year I made the time.

This latest commit was for the community for which I made a  Favicon. This time they wanted to signify the group's founders on screen. I modified some JavaScript to id the community founders and then display them to a separate section of the page. I labeled the sections for founders and members.  
Once I submitted the PR. The Maintainer added some suggestion to how change the section titles to better made the site's styling. I updated and my PR was accepted.

For this issue I learned a little about elventy and its templating system. I like what I seen of it. 

I plan on doing some more Open source PRs this month. Before I can do that I have to update a personal project and do interview prep.

How is you Hacktoberfest going? Have you made commits? What did you work on?

 -$JarvisScript git push
How to update child npm modules to fix vulnerabilities
Tags: npm, security, github, beginners
Published: 2020-10-08 22:30:23

Often you get messages from GitHub saying that one of the dependencies needs to be updated to fix a vulnerability. Every time I find myself Google-ing how to do that. I should Google no more, for I am writing this post... to remember!

1. Often the alert is about modules that are dependencies, of dependencies, of dependencies of libraries you have installed. You can type `npm ls {{type_package_name}}` to find what's the parent module. Not that it is important or anything, but I am also curious. 

Source: [https://stackoverflow.com/a/49523073/3630417](https://stackoverflow.com/a/49523073/3630417)

2. `npm update` updates modules but it inspects only the top level. There is a param that you can pass to the command: `--depth`. So `npm update --depth 5` will update modules up to 5 levels deep.

Source: [https://stackoverflow.com/a/60725984/3630417](https://stackoverflow.com/a/60725984/3630417)

##OR..##

As I have just discovered after writing this post (facepalm..), you can click on the title of the dependabot GitHub alert and it will create an automatic PR that fixes the issue. This one seems much easier... but it doesn't always work for me.

##Edit##

###Other useful npm commands related to dependencies###

- `npm list {{type_package_name}}` ([Source](https://stackoverflow.com/a/10986132/3630417))

Returns the tree where dependency sits, and its version. for instance:

```
`-- react-scripts@3.4.1
  `-- webpack-dev-server@3.10.3
    `-- selfsigned@1.10.7
      `-- node-forge@0.9.0
```

###Delete node_modules folder and package.lock.json###

I have noticed that sometimes the above does not work. I have read [here](https://stackoverflow.com/a/57266372/3630417) that you can delete the `node_modules` folder and the `package.lock.json` files. You then run `npm install` and the packages should be updated. Worked for me anyway.
Day 234: The Key
Tags: hiphop, code, coding, lifelongdev
Published: 2020-10-08 22:18:17

_liner notes_:
- Professional : Had a meeting with the team to do a retrospective. Pretty good to take some to see what we've done so we can see where we are going. Rest of the day, worked on the live stream I'll be doing next week.

- Personal : Last night, finally installed some library to build the chat and questions sections on my side project. Of course I ran into some issues. The main one is that I need to pass in a private key, but there is an error somewhere. I want to be able to store the private key in my database instead of as an environment variable so it will be easier to change if I need to. I don't want to have to redeploy the application. Also got a chance to check out some tracks for the radio show.

![Some houses and roads in a valley between mountains in Klaussen Pass, Switzerland](https://dev-to-uploads.s3.amazonaws.com/i/ah375p4v4wrxza09o3lp.png)

So I think I may have found out why the private key wasn't working. Basically, I can't type and name the key something different in the database than what I was looking for in the code. haha We'll see if it works now. If it does, I'll continue working on it. If not, going to take some time to get this week's radio show together.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 2OXYJuHKLzU %}
The NaijaHacks 2020: Hackathon for the Web December 2020
Tags: africa, hackathon, beginners, webmonetization
Published: 2020-10-08 21:10:17

We are excited to announce NaijaHacks 2020 x Hackathon for the Web with a significant focus on Web Monetization. Registrations are ongoing.

Top projects and winners of NaijaHacks will have the opportunity to join the AfricaHacks Startup program to transform their Hackathon idea into Startups with support from AWS, Twilio, Hubspot, Segment, Notion, and others.

## Recommended Web Monetization Project Categories
### Foundational Technology:
Supporting technology, tools, and infrastructure that innovate around the Web Monetization standard and the Interledger Protocol. Some useful resources include:
- Coil API and Developer portal
- Interledger website
- webmonetization.org website

### Creative Catalyst:
Supporting experiments in the creation, distribution, and discoverability of content monetized using the Web Monetization standard and the Interledger Protocol. Some examples:
- Search engines
- Browser extensions
- Newsletter and curation platforms

## Prize
We have some many amazing prizes planned for NaijaHacks 2020. The Web Monetization prizes supported by Grant for the Web's Mid Level grant include:
Laptop for each team member
- Opportunity for one of the Team Members to join the AfricaHacks Startup program and receive
  - $10k in AWS credit
  - $100k in Twilio/Sendgrid credit
  - $1,000 in Notion credit
  - $200k in Segment benefits

## How to Participate
The NaijaHacks 2020 Hackathon for the Web is open to anyone regardless of skill level. Even if you are not in tech, you are welcome to participate. A hackathon is a great place to gain valuable experience. There will be tutorials, workshops, and mentors to help throughout the event!
Apply at [apply.africahacks.com](https://apply.africahacks.com/).

## Post-Hackathon
Up to ten teams that build Web Monetization will have an opportunity to apply to join the AfricaHacks Incubator program. Past cohorts of the program had access to:
- Weekly mentorship from the AfricaHacks team
- Up to $300k in benefits (AWS, Twilio/Sendgrid, Segment, - Hubspot, and others).
- Product development sprint or Produthon
- Business skills training from the Canadian organization, BizSkills Academy
- Access to attend events with Business and world leaders, including President Obama, Trevor Noah, Executives from Nike, Total, PwC, and many more.
- Access to technical and business support from AfricaHacks
- Pitch events like the Student Build pitch, weekly pitches, and many more.
- AfricaHacks 2020 Pitch day (Upcoming) and
Many more…

See the FAQ section on NaijaHacks.com for more questions and apply at [apply.africahacks.com](https://apply.africahacks.com/).
Ruby 2.7.2 has revised Rdoc for Hash
Tags: ruby, hash, documentation
Published: 2020-10-08 21:10:14

---
title: Ruby 2.7.2 has revised Rdoc for Hash
published: true
description: 
tags: ruby, hash, documentation
---

I've spent a good part of this year working on revisions to the RDoc for Hash. The revisions include all methods documentation in addition to much of the introductory text (class documentation). Lots more example code.

Check it out:

- 2.7.2: https://ruby-doc.org/core-2.7.2/Hash.html

- 2.7.1: https://ruby-doc.org/core-2.7.1/Hash.html