teleren/devto huggingface dataset:
Assert testing with Ruby's Minitest
Tags: testing, ruby
Published: 2019-12-16 07:45:27

The more interviews and take home challenges I get, the more I realize how important it is to know how to write and read tests for my code. Every single recruiter for all of the backend positions that I have asked me to demonstrate my test writing skills, in one way or another. After diving into Ruby docs and scanning Youtube for how-to videos, I feel like I have the fundamentals I need to be proficient with Ruby's testing suite Minitest.

Assert/Refute style testing is the most basic way to write tests for your code. You simply write a method that will either assert that a parameter is true or refute that a parameter is true. The outcome of the function will be either true or false.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/s0xobyralpdbt9e6hjhj.JPG)

This example test will fail, as it is an assert test that returns false. The first parameter in this method is the test, while the second parameter is the failure message. The failure message can be a string or a proc. If the message is a string, it will be used as the failure message. Otherwise, the result of calling message will be used as the message if the assertion fails. If no message is given, a default message will be used. This particular test would have passed if it was written as a refute, instead of assert.

There are a number of different ways to write assert/refute tests with Minitest. Below are some basic testing methods:


**assert_block( failure_message = nil )**
This method tests the result of the given code block. If the block does not return true, the assertion will fail.


**assert_equal( expected, actual, failure_message = nil )**
This method tests if expected is equal to actual.


**assert_not_equal( expected, actual, failure_message = nil )**
This method tests if expected is not equal to actual.


**assert_not_nil( expression, failure_message = nil )**
This method tests if expression is not nil.


In the same way that there are endless ways to write and structure your code, there are copious ways in which you can write these assert/refute tests to verify your code. I would highly recommend picking up a testing suite written for your most familiar language and really digging in. The ability to write and read tests for code is extremely important.


REFERENCES

https://docs.ruby-lang.org/en/2.1.0/Test/Unit/Assertions.html
https://blog.codeship.com/getting-started-with-minitest/
Advent of Code 2019 Solution Megathread - Day 16: Flawed Frequency Transmission
Tags: adventofcode, challenge, adventofcode2019, spoilers
Published: 2019-12-16 07:20:18

---
title: Advent of Code 2019 Solution Megathread - Day 16: Flawed Frequency Transmission
published: True
description: Lets try to optimize the frequencies!
tags: adventofcode,challenge, adventofcode2019, spoilers
series: Advent of Code 2019 Solutions
cover_image: https://i.imgur.com/KeFhZog.png
---

Can't stop the signal!

### [Day 16 - The Problem](https://adventofcode.com/2019/day/16)
Communication speed and quality has become a problem out here in the gas giants. Communication takes so long that we need to come up with a way to verify and repair the signals we receive to avoid having to have Control repeat itself.

Part 1 has us apply the "Flawed Frequency Transmission" algorithm supplied in the problem statement. We need to run it 100 times to get our solution.

If you brute forced your way through Part 1, Part 2 is a whole lot of hurt. The "actual" signal is 1000 times as long as in Part 1, so once again we need to find a good way to cheat.

### Ongoing Meta

#### Dev.to List of Leaderboards

* `120635-5c140b9a` - provided by [Linda Thompson](https://dev.to/lindakatcodes) 

 If you were part of [Ryan Palo](https://dev.to/rpalo)'s leaderboard last year, you're still a member of that! 

If you want me to add your leaderboard code to this page, reply to one of these posts and/or send me a DM containing your  code and any theming or notes you’d like me to add. (You can find your private leaderboard code on your "[Private Leaderboard](https://adventofcode.com/2019/leaderboard/private)" page.)

I'll edit in any leaderboards that people want to post, along with any description for the kinds of people you want to have on it. (My leaderboard is being used as my office's leaderboard.) And if I get something wrong, please call me out or message me and I’ll fix it ASAP.

There's no limit to the number of leaderboards you can join, so there's no problem belonging to a "Beginner" *and* a language specific one if you want.

#### Neat Statistics

I'm planning on adding some statistics, but other than "what languages did we see yesterday" does anyone have any ideas?

##### Languages Seen On Day 15

> Under construction
Recursion in Python(A Gentle Introduction)
Tags: python, resources, beginners
Published: 2019-12-16 06:53:20

The topic of *recursion* can be intimidating and daunting at first to newcomers, and one can get frustrated and find difficulties wrapping their heads around this topic. 🤔    
##MIT OpenCourseWare
Prof. Eric Grimson framed recursion in a straightforward and easy to understand way. He also introduced a simple yet powerful concept that goes with recursion called *memoization*. 🤯
{% youtube WPSeyjX1-4s %}
One can think of *memoization* is essentially a list of performed tasks and its values, and if the task at hand is in the list, just get the value; else add the task and value to the list.😀   


Notes:
Here is a great resource for Python beginners on *recursion*: 
{% link https://dev.to/ejbarba/python-recursion-4jcd %}
Jokes aside, after watching the video, you're at least a little confident with *recursion*👏👏👏 Happy Coding!
How to make money with gaming apps
Tags: apps, gamingapp, money, mobile
Published: 2019-12-16 06:47:06

Statistics reveal that users are starting to prefer mobile apps over websites. Can you guess which type of apps users engage with the most, 'gaming apps'.

As a developer, I always come across the question: "How do you generate income from a mobile app?"
This question is more highlighted when it comes to 'gaming apps'.
Well folks, let's talk about all the ways that revenue can be generated from mobile apps. I'm gonna mention a few ways that come to my mind, feel free to contribute your ideas.

**1. Provide premium features that users have to purchase in the mobile apps.**
**2. Provide game boosters like lives and coins that users can purchase to improve their gaming experience.**
**3. Launch a paid app (only do this if you really think that your app is worth spending money on).**
**4. Sell merchandise on your gaming app.**
**5. Run advertisements on your app for other companies (this is also called referral marketing).**

What are your thoughts?
Awesome Css loading animation 
Tags: css, animation, beginners
Published: 2019-12-16 06:40:54

One of the best ways to avoid your visitor from clicking away from your website is by displaying a loading animation when data is taking time to load, so guys I made this css interative loading animation with just html and css

Click on the link to learn how to
<a href="https://youtu.be/-7H_KKBftOM">youtube video link<\a>

Video duration 6 mins

Subscribe for more videos 💪🏿
How to Fetch Data from API with React Hooks | Example
Tags: react, reactnative, typescript
Published: 2019-12-16 06:22:24

If you haven't one already, you can create react application using create-react-app by running this command.

> create-react-app <YOUR_APP_NAME>

After successfully created app, create a file fetchData in /src/fetchData.js.

# About useEffect() :

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. You should check out the docs.

Note –
Inside the component where you want to fetch a data, you must need to add a useEffect hook i.e.

<div style="background: #f0f0f0; overflow:auto;width:auto;border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"><pre style="margin: 0; line-height: 125%"><span style="color: #007020; font-weight: bold">import</span> React, { useEffect } from <span style="color: #4070a0">&quot;react&quot;</span>

<span style="color: #007020; font-weight: bold">export</span> <span style="color: #007020; font-weight: bold">default</span> () <span style="color: #666666">=&gt;</span> {

    useEffect(() <span style="color: #666666">=&gt;</span> {
        <span style="color: #60a0b0; font-style: italic">// Fetch data right here!</span>
    }, [])

    <span style="color: #007020; font-weight: bold">return</span> (
        <span style="color: #666666">&lt;&gt;</span>
            <span style="color: #666666">&lt;</span>h1<span style="color: #666666">&gt;</span>You are welcome<span style="color: #666666">!&lt;</span><span style="border: 1px solid #FF0000">/h1&gt;</span>
        <span style="color: #666666">&lt;</span><span style="border: 1px solid #FF0000">/&gt;</span>
    )
}
</pre></div>

# As an Example, to load countries –
You should check out the <a href="https://www.code-sample.com/2019/12/react-fetch-data-from-api-example.html" target="_blank">Example</a>
Redux and Higher Order Components

Published: 2019-12-16 04:58:13

As I've mentioned in previous posts, I taught myself the quick and dirty of Redux to use it for my Flatiron final project, The World Builder's Tome. There are a few stories I could tell about that experience, but here I just wanted to go over one little mystery I ran into and the solution I found. 

For Tome I was using Higher Order Components (HOCs) to manage authorization. This meant wrapping each React component that I wanted hidden behind the auth check in the authorization HOC. Here's what this looks like on the SearchPage component in one of my other projects:

`export default PrivacyHOC(SearchPage);`

Now, here's the thing. Redux works very similarly. Here's the export line on the Login Page component for Tome, where Redux is in play but not the authorization HOC:

```export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginPage);```

As you can see, both essentially involve wrapping the exported component in something higher up. So I ran into an issue. For the majority of the pages throughout Tome, I needed both. The Auth HOC would need to be wrapped, as well as the base level component. My initial reaction was of course, What the heck is that supposed to look like??? (I was rather stressed at the time.) The layering was mind bendy.

So I did a little digging. I poked around online and found the answer I needed in a Stack Overflow response, which I have not been able to locate again, or I would link it here.

The key, as it turns out, was very simple. There is something you can do called "composing" that essentially combines the components for you.

Here is the code from my AuthHOC component:

```
import React from "react";
import { Redirect } from "react-router-dom";
import { connect } from "react-redux";
import {compose} from 'redux'

const AuthHOC = WrappedComponent => {
…
};

const mapStateToProps = state => {
…
};


const composedAuthHOC = compose(
connect(mapStateToProps), AuthHOC
)
export default composedAuthHOC;
```


Using 'compose,' I was able to simply export this new 'composedAuthHOC' component for use elsewhere instead of the simpler AuthHOC which did not have access to state. This meant that wherever I wanted to both use the AuthHOC and reference the redux state later on, I could put this in the export statement of a component:

```export default connect(
mapStateToProps,
mapDispatchToProps
)(composedAuthHOC(EditForm));```


Tada! Clean and simple. Solved my problem, anyway.

Alright it is late and I am way more tired than I thought I was. I hope this was at all coherent, hah!
Tries
Tags: computerscience, algorithms, datastructures, csharp
Published: 2019-12-16 04:46:39

## Resources

1. [Trie Overview](https://www.interviewcake.com/concept/java/trie)
1. [Trie Overview + Implementation](https://www.techiedelight.com/trie-implementation-insert-search-delete/)
1. [Trie Operations + Implementations](https://www.baeldung.com/trie-java)
1. [In Depth Trie Explanation](https://www.toptal.com/java/the-trie-a-neglected-data-structure)
1. [A good implementation of the delete operation](https://github.com/trekhleb/javascript-algorithms/blob/master/src/data-structures/trie/Trie.js)

(Also worth mentioning is [this article from the Visual Studio Magazine](https://visualstudiomagazine.com/articles/2015/10/20/text-pattern-search-trie-class-net.aspx). The article explains tries and why you might want to use them.)

Takeaways:

* A **trie** is an ordered tree that compactly stores strings. Each **node** in a trie represents a single character in a string. Say we store the words "car" and "cars" in a trie - the trie would only use four nodes for both - one for each distinct letter of the words (c,a,r,s).
* They are also known as **digital trees** and **prefix trees**.
* A trie is most efficient when it is storing strings with similar prefixes, but in general tries are usually not space efficient. They have a space complexity of `O(n + k)`. 
* They are useful for queries involving string prefixes, such as suggesting the next character(s) for a given prefix.
* Tries are not usually found in standard libraries of popular languages (Java & C#, for example, do not have a trie data structure).
* Tries are typically implemented using arrays or hash tables.
* Although hash table implementations are more flexible, array implementations can be more efficient by placing limitations on the trie (like only allowing characters a-z)
* Many trie implementations will use booleans to mark the end of words/strings. But some implementations will use an additional node appended after the last character of the word. This additional node might contain a `NULL` value or a special character.
* Similarly, the root/head node of a trie can be represented in various ways. For my implementations I used a special character (`$`) to denote the root node.
* Inserting and searching are both `O(k)` operations.
* A related data structure is a **radix tree**
* Radix trees are basically a space efficient trie. A trie only stores one character per node, whereas a radix tree can store many. A radix tree is essentially a trie where all nodes that are the only child are merged with their parent nodes - this means less total nodes are required for the same number of words.

Below you will find two trie implementations:
{% gist https://gist.github.com/jbolton209/fb589da26c23ebd123ea7c084172dc9e %}

As always, if you found any errors in this post please let me know!
Bash Alias
Tags: bash, discuss
Published: 2019-12-16 04:16:50

Bash alias's are a way to save some time when typing in the terminal. Simple enough. Luckily the syntax to create an alias for a command is just as easy!
```bash
alias <name>="<command>"
```
But, what are some things you might want to create an alias for? Well, here are some personal examples of mine, that I use quite frequently:
```bash
# Alias for pushd
alias pd="pushd"

# Alias for popd
alias p="popd"
```
I've fallen in love with pushd and popd. It's another way of moving around the terminal. It's like cd but different. When you push from one directory to another, you create a history that you can use to pop backwards, if you want to. So if you are in your `~/Downloads` directory and you `pushd ~/Documents/projects/my-project` all you would have to do is type `popd` to return to your Downloads directory. I've aliased them so they are a little shorter and easy to use all the time. I can `pd my-project` and then to go back all I need to do is type `p` and hit enter and --BAM!-- I'm in my projects folder again. It also creates a little synergy with my next group of alias's.
```bash
# Alias for lambda directory
alias lam="pushd ~/Documents/lambda"

# Alias for notes directory
alias note="pushd ~/Documents/notes"

# Alias for pets directory
alias pet="pushd ~/Documents/pets"

# Alias for experiments directory
alias exp="pushd ~/Documents/experiments"

# Alias for experiments directory
alias pack="pushd ~/Documents/packages"

# Alias for bin directory
alias bin="pushd ~/bin"
```
These are the directory's I spend the vast majority of my time working in. So, why not create small little key words that use to easily navigate to these folders from any location in my terminal? Again, using pushd so I have that history I can pop through. 
```bash
# Alias for clearing terminal
alias x="clear"

# Alias for opening directory in VS Code
alias vs="code ."
```
Simple enough, make clearing your terminal and opening a project in VS Code that much easier. I can't tell you how many times I've typed `code ,` only to open a file named `,` in VS Code, instead of opening my project...

#### And there we go!
Just a simple list of bash scripts I commonly use. Hopefully this inspires you to write some of your own alias and start saving time in your terminal today!
Better way to create projects and microservices
Tags: productivity, microservices
Published: 2019-12-16 04:14:45

Fellow developers I need your help.

I am planning to build a tool that will prove to be a better way to spin up a new project/microservice. Help me understand if this is a real problem that needs to be addressed by answering 4 questions in following questionnaire.

Your inputs are highly appreciated.

arpitbbhayani.typeform.com/to/X6Oelv
PHP jQuery form formData 20: input text textarea using ajax ($.ajax)
Tags: php, jquery, form, ajax
Published: 2019-12-16 03:38:28

<hr />

<center>Happy Coding</center>

<hr />

index.php

		<form method="post" action="process.php" >

			Firstname: <input type="text" name="firstname" />
			<br />

			Lastname: <input type="text" name="lastname" />
			<br />

			Description: <textarea name="description" rows="10" cols="50" ></textarea>
			<br />

			<hr />

			<input type="submit" value="Submit" />

		</form>

		<hr />


display result form server

		<div id="output"></div>

get formHTML element and add onsubmit event, and create formData, then call ajax function with arguments formHTML, formData and output display ("#output") 

		<script>

			/* submit form */

			// https://api.jquery.com/jquery.each/
			/*
			 *	array.each( function( index, element ) )
			 *	$.each( array, callback )
			 */

			// https://www.w3schools.com/jquery/misc_each.asp

			/* get all form */
			$( "form" ).each( function () {

				/* each form add onsubmit event */
				$( this ).bind( "submit", function (event) {

					event.preventDefault(); // return false


					var formHTML = event.target; // $( this ) => not work !!

					console.log( formHTML ); // formHTML element


					// https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
					var formData = new FormData( formHTML );

					console.log( formData );


					// https://api.jquery.com/jquery.ajax/
					// https://www.w3schools.com/jquery/ajax_ajax.asp
					// https://www.w3schools.com/jquery/jquery_ref_ajax.asp

					/* AJAX request */
					ajax( formHTML, formData, "#output" ); // ajax( form, data, destination )

				} );

			});

		</script>

ajax function

		<script>

			function ajax( form, data, destination )
			{

				$.ajax({

					method: form.method,
					url: form.action,

					data: data,

					/*
						result type data
						JSON.parse(data)
						http://api.jquery.com/jQuery.ajax/
						https://stackoverflow.com/questions/14322984/differences-between-contenttype-and-datatype-in-jquery-ajax-function
						https://forums.asp.net/t/2087039.aspx?what+is+difference+between+dataType+and+contentType+in+jquery
					*/
					dataType: "HTML",

					/* formData */
					contentType: false, // formData with $_POST or $_FILES in server (PHP)
					processData: false

				})

				/* handle success */
				.done( function(result) {

					$( destination ).html( result );

					console.log(result);

				} )

				/* handle error */
				.fail( function(error) {

					alert("Cannot Set Data!");

					console.error(error);

				} );

			}

		</script>

<hr />

process.php

    echo "<pre>";

    var_dump($_POST);

    echo "</pre>";

<hr />

Demo <a href="https://repl.it" >repl.it</a>

<ul>
  <li><a href="https://repl.it/@antelove19/jQuery-form-formData-20" >Editor</a></li>
  <li><a href="https://jquery-form-formdata-20.antelove19.repl.co/" >Live</a></li>
</ul>

<hr/>

<center>Thank for reading :)</center>

<hr/>
PHP jQuery form formData 10: input text using ajax ($.ajax)
Tags: php, jquery, form, ajax
Published: 2019-12-16 03:30:38

<hr />

<center>Happy Coding</center>

<hr />

index.php

		<form method="post" action="process.php" >

			Firstname: <input type="text" name="firstname" />
			<br />

			Lastname: <input type="text" name="lastname" />
			<br />

			<hr />

			<input type="submit" value="Submit" />

		</form>

		<hr />


display result form server

		<div id="output"></div>

get formHTML element and add onsubmit event, and create formData, then call ajax function with arguments formHTML, formData and output display ("#output") 

		<script>

			/* submit form */

			// https://api.jquery.com/jquery.each/
			/*
			 *	array.each( function( index, element ) )
			 *	$.each( array, callback )
			 */

			// https://www.w3schools.com/jquery/misc_each.asp

			/* get all form */
			$( "form" ).each( function () {

				/* each form add onsubmit event */
				$( this ).bind( "submit", function (event) {

					event.preventDefault(); // return false


					var formHTML = event.target; // $( this ) => not work !!

					console.log( formHTML ); // formHTML element


					// https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
					var formData = new FormData( formHTML );

					console.log( formData );


					// https://api.jquery.com/jquery.ajax/
					// https://www.w3schools.com/jquery/ajax_ajax.asp
					// https://www.w3schools.com/jquery/jquery_ref_ajax.asp

					/* AJAX request */
					ajax( formHTML, formData, "#output" ); // ajax( form, data, destination )

				} );

			});

		</script>

ajax function

		<script>

			function ajax( form, data, destination )
			{

				$.ajax({

					method: form.method,
					url: form.action,

					data: data,

					/*
						result type data
						JSON.parse(data)
						http://api.jquery.com/jQuery.ajax/
						https://stackoverflow.com/questions/14322984/differences-between-contenttype-and-datatype-in-jquery-ajax-function
						https://forums.asp.net/t/2087039.aspx?what+is+difference+between+dataType+and+contentType+in+jquery
					*/
					dataType: "HTML",

					/* formData */
					contentType: false, // formData with $_POST or $_FILES in server (PHP)
					processData: false

				})

				/* handle success */
				.done( function(result) {

					$( destination ).html( result );

					console.log(result);

				} )

				/* handle error */
				.fail( function(error) {

					alert("Cannot Set Data!");

					console.error(error);

				} );

			}

		</script>

<hr />

process.php

    echo "<pre>";

    var_dump($_POST);

    echo "</pre>";

<hr />

Demo <a href="https://repl.it" >repl.it</a>

<ul>
  <li><a href="https://repl.it/@antelove19/jQuery-form-formData-10" >Editor</a></li>
  <li><a href="https://jquery-form-formdata-10.antelove19.repl.co/" >Live</a></li>
</ul>

<hr/>

<center>Thank for reading :)</center>

<hr/>