teleren/devto huggingface dataset:
What’s your alternative solution? Challenge #31
Tags: challenge, javascript, codenewbie, learntocode
Published: 2020-04-30 22:05:55

# About this series

This is series of daily JavaScript coding challenges... for both beginners and advanced users.

Each day I’m gone present you a very simple coding challenge, together with the solution. The solution is intentionally written in a didactic way using classic JavaScript syntax in order to be accessible to coders of all levels.

Solutions are designed with increase level of complexity.

## Today’s coding challenge

```
Calculate the sum of first 100 prime numbers

```

(scroll down for solution)

## Code newbies

If you are a code newbie, try to work on the solution on your own. After you finish it, or if you need help, please consult the provided solution.

## Advanced developers

Please provide alternative solutions in the comments below. 

You can solve it using functional concepts or solve it using a different algorithm... or just solve it using the latest ES innovations.

By providing a new solution you can show code newbies different ways to solve the same problem.

## Solution

```javascript
// Solution for challenge28

var n = 10;
println("Sum of first ", n, " primes is ", sumPrimes(10));

function sumPrimes(n)
{
    var foundPrimes = 0;
    var i = 2;
    var sum = 0;
    
    while(foundPrimes < n)
    {
        if (isPrime(i))
        {
            foundPrimes++;
            sum += i;
        }
        
        i++;
    }
    
    return sum;
}

// Returns true if number n is prime
function isPrime(n)
{
    if (n < 2)
        return false;
        
    if (n == 2)
        return true;
    
    var maxDiv = Math.sqrt(n);
    
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i === 0)
        {
            return false;
        }
    }
    
    return true;
}

```


To quickly verify this solution, copy the code above in this coding [editor](https://codeguppy.com/code.html) and press "Run".

> Note: The solution was originally designed for [codeguppy.com](https://codeguppy.com) environment, and therefore is making use of `println`. This is the almost equivalent of `console.log` in other environments. Please feel free to use your preferred coding playground / environment when implementing your solution.
How to use Graphql fragments.
Tags: graphql, react
Published: 2020-05-01 02:12:17

---
title: How to use Graphql fragments.
published: true
description: DRY your query fields.
tags: graphql, react
---


Let’s imagine you developing an app and you need a user to login to access some features. 
This app has a page when you show a list of all your users and for that, you need to get the user's data in order to render some UI.
Also, if someone clicks on a single user you need to show the data from that particular user.

```graphql
query User {
  user {
    id
    firstName
    lastName
    username
    email
    URL
    thumbnailUrl
    occupation
  }
}

query Users {
  users {
    edges {
      node {
	      id
	      firstName
	      lastName
	      username
	      email
	      url
	      thumbnailUrl
	      occupation
      }
    }
  }
}
```


## How can we avoid writing these fields every time we need the user data?

Fragments are a reusable piece of a query. You can use them to avoid repeating code in some cases.
According to the Apollo documentation, one of the principal uses for fragments are _Sharing fields between multiple queries, mutations, or subscriptions_.

> DRY: Don’t Repeat Yourself.

Let’s see how we can use fragments on a `.graphql` file.

```graphql
fragment userAttributes on User {
  id
  firstName
  lastName
  username
  email
  url
  thumbnailUrl
  occupation
}
```

The component after the `on`, in this case `User` is the type we are selecting the fields from.
In order to use this fragment in a `graphql` file, we must import it in this way.

```gql
#import "./userFragment.graphql"

query User {
  user {
    ...userAttributes
  }
}

query Users {
  users {
    edges {
      node {
	    ...userAttributes
      }
    } 
  }
}
```
 
That reducer our code significantly.
Let’s see the way to embed the fragments in our queries if we use the `gql` helper.

```js
const userFragment = gql`
  fragment userAttributes on User {
    id
    firstName
    lastName
    username
    email
    url
    thumbnailUrl
    occupation
  }
`;

const userQuery = gql`
  query User {
    user {
      ...userAttributes
    }
  }
  ${userFragment}
`;

const userListQuery = gql`
  query Users {
    users {
      edges {
        node {
	      ...userAttributes
        }
      } 
    }
  }
  ${userFragment}
`;
```

If we need to get more data about the user, it’s as easy as adding new fields to our fragment.
Can you push commits altogether at the end of the day on Bitbucket?
Tags: Bitbucket, github
Published: 2020-05-01 10:13:08

I'm used to developers pushing commits just after they've made a change.
However, my current developer says he's going to make one commit at the end of the day to save time.
He says that I will see the different commits separately, but the only difference is that he'll post them at the end of the day.
Is that okay or do you see any disavantage?
Redis 6 is out
Tags: redis, news
Published: 2020-05-01 10:47:19

Huge fan of Redis here :-)

Its latest version adds the following:

* [Access control lists (ACL)](https://redis.io/commands/acl-setuser) so that clients/users can be barred from performing dangerous operations
* Multithreaded I/O (Redis until now has been largely single threaded with async) which is bound to make Redis even faster
* Client side caching: this is really cool in my opinion, reminds me of the evergreen article about [how StackOverflow does layered caching](https://nickcraver.com/blog/2019/08/06/stack-overflow-how-we-do-app-caching/#layers-of-cache-at-stack-overflow)
* [Longest common substring (LCS)](https://redis.io/commands/stralgo) command which works both on text and binary data

See [Redis Labs: Diving Into Redis 6.0](https://redislabs.com/blog/diving-into-redis-6/) and the [official release notes](https://raw.githubusercontent.com/antirez/redis/6.0/00-RELEASENOTES).
WordPress theme starter kit that saved me hours | Understrap
Tags: wordpress, webdev
Published: 2020-05-01 12:22:34

When I started building websites, all my clients wanted websites with custom designs. WordPress was the choice here in Australia, and I needed to build out heaps of custom themes, I found a great resource called <strong>[understrap](https://understrap.com/)</strong>, which is a theme starter kit for WordPress.

Having made hundreds of Wordpress websites over the years, these guys have been my favourite. So hope you can check them out if you ever need help building a site yourself!

<strong>Understrap:</strong> [https://understrap.com/](https://understrap.com/)

Some of the things I really like about them include:
* Bootstrap 4 integration
* Font Awesome integration
* Custom Form 7 integration
* WooCommerce Ready
* All templates, posts, pages separated our and well documented.
* SASS ready with gulp and npm pre-configured
* Minify CSS automatically along with other files
* Easy to modify update and use
* Great GitHub community with lots of commits and regular updates.


{% youtube C7lahTmnuVM %}
<center>[Youtube: Understrap Theme Starter](https://youtu.be/C7lahTmnuVM)</center>

You can check out their github below:
https://github.com/understrap/understrap

Swiper Js can be installed into any project, plain HTML, WordPress or even react. If you are interested in them, you can check them out at their official URL:

## Follow and support me: 
Special thanks if you subscribe to my channel :)
* [🎞️ Youtube](https://www.youtube.com/channel/UCvM5YYWwfLwpcQgbRr68JLQ?sub_confirmation=1)
* [🐦 Twitter](https://twitter.com/adrian_twarog)
* [💬 Discord](https://discord.gg/nGdThpE)
* [❤ Patreon](https://www.patreon.com/adriantwarog)

## Want to see more:
I will try to post new great content every day. Here are the latest items:
* [Adobe XD to Fully Responsive WordPress Site](https://dev.to/adriantwarog/adobe-xd-to-fully-responsive-wordpress-site-16e0)
* [Adobe XD to HTML Full Process](https://dev.to/adriantwarog/adobe-xd-to-html-full-process-ao6)
* [Full Tutorial on how to use SASS to improve your CSS](https://dev.to/adriantwarog/full-tutorial-on-how-to-use-sass-to-improve-your-css-57on)
* [Creating a Mobile Design and Developing it](https://dev.to/adriantwarog/creating-a-mobile-design-and-developing-it-5c4o)
Googel Brain : Intro to TFLite and TFLite Micro
Tags: tutorial, python, machinelearning, android
Published: 2020-05-01 20:40:46

Meghna Natraj is a software engineer on the Google Brain team, USA working on TensorFlow Lite, an open source deep learning framework for on-device inference. Previously, she worked at Bloomberg as a software engineer building scalable machine learning services and completed her M.S in Computer Science from Georgia Institute of Technology.

Agenda :
1. Intro to TFLite and TFLite Micro
2. Training a model for mobile deployment (+ discuss dos and don'ts to ensure common issues are not encountered). Discuss new features such as Model Maker + Support Library + Quantize Aware Training + Op compatibility.
3. Deploy a model and test it.

RSVP here https://www.meetup.com/TFUG-Mysuru/events/270390225/
MySQL almost got me fired
Published: 2020-05-02 15:45:03

A few years ago I was working for a University with some financial troubles, so instead of buying a super-expensive Student Information System we decided to build our own.

Using a mix of SugarCRM and Java Servlets we were able to ship a first fully functional version in less than a year. Students, professors, admins and everyone was happy. Especially that it came with self-service allowing students and professors to view and edit grades and absences online.

As the lead developer I became a hero. But not for long. With the first final exams period, the response time of the web app increased significantly. To the point that saving a set of grades for 30 students took about 2 minutes. All eyes were on me again, but this time to blame.

After a quick investigation I discovered that MySQL was guilty, not me, MySQL. The code and the SQL statements were sound and optimized. But MySQL was not able to handle the load. A few Googling sessions later I found myself facing the tough reality: MySQL is not designed to scale up out of the box. Configuring MySQL to scale up is a whole science which I wasn't prepared for.

The slow response time lasted for almost a year, until we got professional help to reinstall the whole server and configure it properly. The new installation improved the response time, but only until the next spike in user requests.

Lesson learned: MySQL is not free. Given the cost of hosting and maintaining a scalable instance, there are far less expensive options out there. For the last 2 years I am full steam on Firestore and didn't regret it. Do you have other, may be better, options in mind? Leave a comment.
Cypress Observables in 20 Minutes
Tags: cypress
Published: 2020-05-02 22:11:29

 
**Consider this exportable function**

```typescript
//get all divs and return an Observable
export function getDivs() :Observable<any> {
  return   
    // an observable using the from operator in RxJS
    from(
      //get all divs; then return them to the observable
      cy.get("div").then((divs) => {
        //this happens sometime in the future
        return divs;
      })
    );
}
```

**Importing Functions in Cypress Tests**

```typescript
import {getDivs} from "../../support/commands"

context('Actions', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io/commands/actions')
  })
  it("it proves how we can use observables for any cypress result", () => {
   //lets use our new Cypress Function
    getDivs().subscribe(divs => {
      debugger;
    });
  });
```
When we hit the debugger statement in the test, pressed F12 and looked into what was returned, we saw that there were [105 Divs on this page](https://example.cypress.io/commands/actions)

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

Note that Cypress does not return an array of elements rather, it returns an array of { index : element }. This is why the divs.map function will map numbers as the key, and not elements. Let's create a helper function to strip out the numbers.

```typescript
//convert to just an array of elements
export function ToArray(eles) {
  let elementArray = [];
  eles.each((item) => {
    elementArray.push(eles[item]);
  });
  return elementArray;
}

//How to use ToArray 
let divArray = ToArray(divs);
//map now works as expected
let collection = divArray.map(function (div) {
    //these are html elements, we may access their properties
    return div.textContent;
});

```

We discovered the exportable function, contained in the command.js file worked as a container for our functions.  
 This bypasses the [Cypress Commands Syntax](https://docs.cypress.io/api/cypress-api/custom-commands.html) which doesn't work; for Typescript intellisense. 

The amazing thing was that the time it took to get all divs was as fast as: 
 
[document.getElementsByTagName('div')](https://www.google.com/search?q=getelementsbytagname) 

It's very impressive that Cypress fully supports the module system and the ability to export/import. When we import our own functions, we have intellisense for any of our custom commands. 

Maybe we should name this construct the 'Cypress Custom Function'. I predict a huge market for Cypress Extensions could emerge using this construct. 
 

JWP2020
All the best Intentions
Tags: software, productivity, leadership, computerscience
Published: 2020-05-06 10:14:43

Can you trust someone if they demonstrate an intent to *harm you*? What if they simply have **goals** that happen to be **harmful to you**?

Would you trust them? Of course not! You'd be crazy.

*Definition: intention*

* *noun: An aim that guides action; an objective.*

Perceived intentions fundamentally impact how much a rational person can trust another person. It's in our DNA.

Trust is undermined by suspicions that people or processes are working against our own goals. On the other side, trust is supported when we feel people or processes are working toward our goals.

Perceived intentions have a huge impact in how much we trust, or don't trust, people and the things they create.

## Intentions of Things

The equivalent of `intention` for a `thing` is it's purpose. For inanimate things such as simple machines, the purpose is clear. We know a ceramic mug is for hot drinks. We know the purpose of television is to waste our time.

What about software? That one is more complicated. Would you download a random program by an unknown author from the internet? Please don't, it's not a good idea.

**What about software you create?** Is it worth thinking about the perceived *intentions of that software in the minds of your intended users*?  Of course it is if you want them to trust it.

## Communicating Intentions

How can we ensure our intended users feel comfortable trusting that the software we build for them, and sometimes with them, will help them in their goals? 

Let's talk about that next time. If you are inspired to share some thoughts on this topic, please add a comment here.
Happy International Astronomy Day 2020!
Tags: universe, solarsystem, javascript, 100daysofcode
Published: 2020-05-03 00:27:24

Hello folks! 👩‍🚀👨‍🚀

Today, to celebrate our **International Astronomy Day**, I created a Codepen example [here](https://codepen.io/jdnichollsc/full/yLYogYz) about our **Solar System** using [Web Animations API (WAAPI)](https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API) and **Web Components** with [StencilJS](https://stenciljs.com). ☄️

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

With this is possible to create any other solar system easily! 🚀

Remember to check the repository of this **Web Component** [here](https://github.com/proyecto26/animatable-component). 📡🛸

I hope you enjoy this day with your family staying at home while we're contemplating the vastness of the **Universe**! 🌌🛰️

Enjoy the heavens together! 🔭💫

## Supporting 🍻

I believe in Unicorns 🦄 Support [me](http://www.paypal.me/jdnichollsc/2), if you do too.


Made with ❤️

Juan D. Nicholls
A REPL for your node project
Tags: mongodb, javascript, repl, productivity
Published: 2020-05-03 12:19:30


Having a REPL / console to play with your application code is always handy. So here is a little piece of code that enables me to use a mongoose User model inside a node repl:

{% gist https://gist.github.com/the-architect/bbdceea1d115cd341520b5028de3c6d2 file=repl.js %}
Schema Alerting (Data Contract) Framework or Service
Tags: testing
Published: 2020-05-03 14:03:50

I am searching for a framework or a service that alerts front-end developers that the schema of the backend has changed so to make the available changes in the front-end.

The problem I am facing as a mobile developer is that often the backend developers are making changes to their json objects. As a result the app is unable to parse the object.

Is there such a service that you know of?
Multiple Playbooks in Ansible
Tags: devops, ansible, cloud, infrastructure
Published: 2020-05-03 15:34:38

Ansible is a simple IT automation engine that automates cloud provisioning, configuration management, application deployment, intra-service orchestration, and many other IT needs.

Ansible works by connecting to your nodes and pushing out small programs, called "Ansible modules" to them. These programs are written to be resource models of the desired state of the system. Ansible then executes these modules (over SSH by default), and removes them when finished.

___

### TL;DR

Ansible has the option to import multiple playbooks into a single one using the method: `import_playbook`:

```
/playbooks/main.yml
---
- name: Playbook_1
	import_playbook: 00-playbook-1.yml
- name: Playbook_2
	import_playbook: 01-playbook-2.yml
```

When you execute `ansible-playbook playbooks/main.yml` Ansible will execute first the Playbook1, and then Playbook 2.

We're going through an example to see it in action

---

The first playbook executes a ping into your servers:

```
/playbooks/00-ping.yml
---
- hosts: all
  tasks:
    - name: Ping All Servers
      action: ping
    - debug: msg="Success"
```

The second playbook upgrades all your yum packages:

```
/playbooks/01-upgrade.yml
---
- hosts: all
  tasks:
    - name: upgrade all packages
      become: yes
      yum:
        name: '*'
        state: latest
```

The third playbook download a node binary distribution:

```
/playbooks/02-download-node.yml
---
- hosts: all
  tasks:
    - name: Download node binary distro
      shell: curl sL https://rpm.nodesource.com/setup_12.x | sudo bash -
```

The fourth playbook install node:

```
/playbooks/03-install-node.yml
---
- hosts: all
  tasks:
    - name: Install Node
      become: yes
      yum:
        name: nodejs
        state: present
```

The fifth playbook copy your app into the remote servers:

```
/playbooks/04-provisioning.yml
---
- hosts: all
  tasks:
    - name: Copy app files
      copy:
        src: ~/documents/my-app-folder/
        dest: /home/ec2-user/my-app
        force: no
    - debug: msg="Success"
```

And finally you need to install dependencies based on your package-json:

```
/playbooks/05-install-dependencies.yml
---
- hosts: all
  tasks:
    - name: Install packages based on package.json.
      npm:
        path: /home/ec2-user/my-app
```

Once you have all your playbooks ready, if you want to execute all of them in the desired order you need to create a main playbook, and import all of them as follow:

```
/playbooks/main.yml
---
- name: Ping
  import_playbook: 00-ping.yml

- name: Update
  import_playbook: 01-update.yml

- name: Download Node
  import_playbook: 02-download-node.yml

- name: Install Node
  import_playbook: 03-install-node.yml

- name: Provisioning
  import_playbook: 04-provisioning.yml

- name: Install Dependencies
  import_playbook: 05-install-dependencies.yml
```

That's it. You are ready to execute `ansible-playbook playbooks/main.yml` and you'll upgrade all your packages, download and install node, provision all your selected servers, and install your dependencies.
25 days into the #100daysofcode challenge
Tags: ssl, continuousdelivery, docker, kubernetess
Published: 2020-05-04 13:43:50

Hello there, being in the middle of the Covid-19 quarantine in NYC, I decided to resume the challenge I started last summer: Remstrava.
The last few days were focused on Continuous Delivery and SSL/TLS.

The goal is simple: being able to deploy any change without any sort of overhead and have the data refreshed in a near-instantaneous fashion.
 
The application is made of:
- an angular front-end
- a back-end that returns activities
- a logic app that integrates data from strava to Azure Data Storage
- a standalone github repository 


## Github repo split :page_facing_up:
- https://github.com/remster85/remstrava-frontend
- https://github.com/remster85/remstrava-backend


## Docker :whale:
I dockerized my front-end using https://docs.docker.com/toolbox since I am running on Windows 10 from an Asus zenbook. One tricky part was to view my front-end running from my local docker image using 192.168.99.100 and not localhost.

```Docker
### STAGE 1: Build ####
FROM node:12.7-alpine AS build
WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
RUN npm run build

### STAGE 2: Run ###
FROM nginx:1.17.1-alpine
COPY --from=build /usr/src/app/dist/remistrava /usr/share/nginx/html
```

## CD Pipelines :wrench:
Then I deployed my image to Azure container registry and created an AKS cluster to deploy my image. Creating the Azure pipeline was very smooth using the available templates on Azure Devops.
 

## Events :mailbox_with_mail:
I created a [webhook](https://developers.strava.com/docs/webhooks) on strava using Azure function and then configured the Azure pipelines for my webhook strava api.

I also created an Azure Event Hub to be notified from new activities and decouple my webhook from the Logic App instance (at the time of writing).


## SSL/TLS :lock:
It was tedious to configure SSL/TLS all the way as the certificate request was pending or some other issue happened using LetsEncrypt. It turned out that I had to clean all my resources in order to have something consistent.
The following workshop was pretty useful https://docs.microsoft.com/en-us/learn/modules/aks-workshop and replaying step by step for my own application was successful.  

:eye_speech_bubble: https://remstrava.westus.cloudapp.azure.com


Next, I would like to:
- Explore database options / Improve data retrieving performances
- Offer anyone the option to load its own data using OAuth2 
- Enhance Security