teleren/devto huggingface dataset:
🛠 Testing Laravel APIs Using PHPUnit
Tags: testing, laravel, phpunit
Published: 2021-01-11 21:08:10

📚 Learn how to test Laravel APIs using PHPUnit. In this tutorial, we will learn how to build and test various endpoints of a RESTful API created with Laravel.
[Read more...](https://auth0.com/blog/testing-laravel-apis-with-phpunit/?utm_source=content_synd&utm_medium=sc&utm_campaign=test-laravel)
What I Learned Building My First App
Published: 2021-01-11 21:04:24

I've just completed my first app build, and even though it's been a few days since writing my last line of code, there's already been a flood of ideas for how to improve, iterate, and evolve its functionality. In fact, it's an *almost* annoying barrage of ideas (that may or may not actually be good) - it'll stop eventually, right?

My first app is the [PHL Covid Testing](https://github.com/bfirestone23/phl_covid_testing) Ruby gem. It uses OpenDataPhilly's testing location API and allows the user to search for a nearby testing site in Philadelphia, PA (by name, zip code, drive-thru, or walk-up) and then view full details for a selected location. While I created this app to flex my object oriented Ruby muscles, I also wanted its functionality to be meaningful and truly useful in the user's day-to-day life.

The biggest thing I learned about development in the process is this: 
> "Focus on the step that is in front of you, not the whole staircase". 

Not only does this apply to something like setting up your environment before diving into writing code, but it also applies to learning to code as a whole! 

When first starting my app build, like many, I felt lost and had little confidence in the code I was writing. At every turn I was looking back through lessons I had completed for refreshers on concepts, reading through far too many StackOverflow posts, and wasting time watching YouTube tutorials that attempted to boil a million concepts down to a 30 minute video. Feeling frustrated, I put my trust in the quote above, and stubbed out the basics - starting with creating classes and identifying their responsibilities, then establishing the necessary has-many and belongs-to relationships, I began to feel the momentum building and giving me a clearer and clearer picture of what steps I needed to take next. 

That momentum is what I've come to recognize as a true sign of progress in my coding journey. If you would have asked me a month ago if I could've built a Ruby Gem from scratch, of course I would've asked, "what's a Ruby Gem?" - but the cumulative result of consistent incremental change is truly a force to be reckoned with. If I hadn't spent months laying a foundation of fundamental coding practices and concepts, I would've completely fallen flat trying to create my own (extremely simple) CLI app. If I hadn't started development by stubbing out the core structure of my code, I wouldn't have been able to see the path to the finish line so clearly. Looking to the future, without building my first CLI, I wouldn't be able to build by first web app. 

In short, while it may sometimes be hard to see the big picture in the midst of uncertainty - put your trust in baby steps.
Get architecture of NodeJS installation on Apple Silicon
Tags: node, applesilicon, m1, arm
Published: 2021-01-11 20:50:22

I had the privilege to get one of the new MacBook Pros with an M1 chip very early. Because of the new ARM architecture of the new processor I try to look if most of my tools and programs already run that architecture. 
Today I checked if my node version is already running on the ARM builds of NodeJS.

To quickly check this for yourself open up a terminal and enter `node` to open up the node repl. Inside enter `process.arch` this will return either `x64` or `arm64`. As one can guess the latter shows that NodeJS already runs on the ARM version. `x64` means that NodeJS still runs via Rosetta 2 emulation.

NodeJS started experimental support of native arm64 builds in version 15.3.0.

You can find this and more posts at [niklasmtj.de](niklasmtj.de)
Day 11 - Merge Sorted Array
Tags: leetcode, python
Published: 2021-01-11 20:42:03

## The Problem

>Given two sorted integer arrays `nums1` and `nums2`, merge `nums2` into `nums1` as one sorted array.

>The number of elements initialized in `nums1` and `nums2` are `m` and `n` respectively. You may assume that `nums1` has enough space (size that is equal to `m + n`) to hold additional elements from `nums2`.

__Example 1:__

```
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
```

__Example 2:__

```
Input: nums1 = [1], m = 1, nums2 = [], n = 0
Output: [1]
```

__Constraints:__

* `0 <= n, m <= 200`
* `1 <= n + m <= 200`
* `nums1.length == m + n`
* `nums2.length == n`
* `-109 <= nums1[i], nums2[i] <= 109`

## My Tests

[Link to code](https://github.com/ruarfff/leetcode-jan-2021)

```python
import pytest
from .Day11 import Solution

s = Solution()


@pytest.mark.parametrize(
    "nums1,m,nums2,n,expected",
    [
        ([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3, [1, 2, 2, 3, 5, 6]),
        ([1], 1, [], 0, [1]),
        ([0], 0, [1], 1, [1]),
    ],
)
def test_merge(nums1, m, nums2, n, expected):
    s.merge(nums1, m, nums2, n)
    assert nums1 == expected
```

## My Solution

[Link to code](https://github.com/ruarfff/leetcode-jan-2021)

```python
from typing import List


class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        i = len(nums1) - 1

        while m >= 1 and n >= 1:
            if nums1[m - 1] < nums2[n - 1]:
                nums1[i] = nums2[n - 1]
                n -= 1
            else:
                nums1[i] = nums1[m - 1]
                m -= 1
            i -= 1

        nums1[:n] = nums2[:n]
```

## Analysis

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

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


## My Commentary

This one was straightforward enough. The fact that we are supplied `n` and `m` is a hint that we need to do more than simply merge the 2 lists to get an optimal solution.

Because we know the lists are sorted we can use that to do this all in one pass and in place. Starting at the __end__ of each list (then end of `nums1` is `n -1` even though `len(num1) == n + m`. Then we take the largest number and put it in the buffer space of `nums1` which we index with `i` starting at `len(nums1) - 1`.
 
The very last step is to fill out `nums1` with any values we didn't catch from `nums2`.
Implement tail command in Python
Tags: python, programming, beginners
Published: 2021-01-11 20:40:49

---
title: "Implement tail command in Python"
published: true
description: "A simple implementation of Linux's tail command in Python"
tags: ["python", "programming", "beginners"]
canonical_url: https://ayada.dev/posts/implement-tail-command-in-python/
---

_Originally published at [ayada.dev](https://ayada.dev/posts/implement-tail-command-in-python/)_

## Introduction
In this article, we will write a simple implementation of the `tail` command from Linux. This program will take a file and an integer `n` as input and print the last `n` lines from the file. Also, the goal of the program is to not read the entire file into memory at once. This will make the program memory efficient when dealing with very large files.

## Implementation Details
In order to implement this program, we will use `queue` data structure. We will read the file line by line and push each line into the queue. Every iteration, we will check the size of the queue. When the size of the queue is greater than or equal to `n`, we will remove the element that was first inserted in the queue. Since queue is a FIFO data structure, the element that was first inserted into the queue will be the first element that will be removed from the queue. This will ensure that the queue contains only last `n` lines from the file.

As a bonus, I have used `argparse` to handle the input from cli. Let's look at the implementation of this program.

```python
import argparse
import queue


def tail(filename, n):
    q = queue.Queue()
    size = 0

    with open(filename) as fh:
        for line in fh:
            q.put(line.strip())
            if size >= n:
                q.get()
            else:
                size += 1      

    for i in range(size):
        print(q.get())

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Print last n lines from a file.')
    parser.add_argument('file', type=str, help='File to read from')
    parser.add_argument('-n', type=int, default=10, help='The last n lines to be printed')
    args = parser.parse_args()

    tail(args.file, args.n)
```
MLH brought me here !
Tags: mlh, localhackday, majorleaguehacking
Published: 2021-01-11 20:33:12

After my first post being about HacktoberFest, here i am again to share my experience and thoughts about another Hacker's event: Local Hack Day ! 

Local Hack Day, or LHD in short, is a computer science event organized internationally by Major League Hacking. It takes place thrice a year for it's 3 chapters : Learn, Build and Share. 

Today I am here to talk about LHD: Build 2021 edition (still open if you want to join). 
The key word this year for LHD:Build is CHALLENGE ! everyday from january 10th to january 18th, participants can enrol in coding challenges as easy as writing hello world in a new language or as fun as creating a tic tac toe game from scratch. In addition to these 24h challenges. We can also sign up for weekly challenges if we want to create bigger projects that involve computer vision or maybe build a playlist for parties app ... these are the topics that i personally am interested in but the list of challenges is long ( you can check them out here https://localhackday.mlh.io/build#ChallengesD )

I will probably upload my challenges in a repo so keep an eye out for my Github profile if you are curious ( https://github.com/SarraLKSC)
Bitcoin and Social Standards
Tags: tech, bitcoin, investing, environment
Published: 2021-01-19 08:33:33

---
title: Bitcoin and Social Standards
published: true
date: 2021-01-11 20:29:38 UTC
tags: tech,bitcoin,investing,environment
canonical_url: https://medium.com/coinmonks/bitcoin-and-social-standards-4f4de0f62f8a
---

[![](https://cdn-images-1.medium.com/max/2600/0*0c6tLjCOD5bNT4v6)](https://medium.com/coinmonks/bitcoin-and-social-standards-4f4de0f62f8a?source=rss----721b17443fd5---4)

Energy guzzler or digital gold? The environmental impact, current use-cases and future chances of Bitcoins.

[Continue reading on Coinmonks »](https://medium.com/coinmonks/bitcoin-and-social-standards-4f4de0f62f8a?source=rss----721b17443fd5---4)
Why won't anything draw to my canvas? (fixed)
Tags: help, javascript, webdev
Published: 2021-01-11 20:02:03

[Original post (which has been edited to be fixed)](https://dev.to/baenencalin/why-won-t-anything-draw-on-my-canvas-2g54).


Whenever I try to draw a custom image in JS, it doesn't draw anything, when I try to log X or Y in the loop, it returns normal values, when I log the color, it's perfectly normal.

So, why won't it draw anything?

```javascript
const text = `Example`;



const makeColor = function makeColor(input, maxX=Infinity, maxY=Infinity) {
    let X = 0;
    let Y = 0;

    let peakX = -1;
    let peakY = -1;
    if(maxX < Infinity) maxX;



    const encode = function encode(input) {
        let estr = "";
        for(const chara of input) {
            estr += String(Number(chara.charCodeAt(0), 16));
        }
        return estr;
    };


    const colors = [];
    let color = "";
    let itr = 0;
    for(const chara of encode(input)) {
        color += chara;
        if(color.length >= 6) {
            itr += 1;
            colors.push(color);
            document.writeln(itr+": "+color+"<br/>");
            color = "";
        }
    }

    if(color.length < 6 && color.length > 0) {
        color += "0".repeat(6-color.length);
        colors.push(color);
        document.writeln(color+"<br/>");
        color = "";
    }



    Object.freeze(colors);


    try {
        const canvas = document.getElementById("result");
        const ctx = canvas.getContext("2d");

        try {
            for(const color of colors) {
                console.log(X, Y);
                ctx.fillStyle = "#"+color;
                if(X > maxX) {
                    if(peakX <= -1 || X > peakX) peakX = X-1;
                    X = 0; Y++; ctx.fillRect(X, Y, 1, 1); X++; continue;
                }
                if(Y > maxY) break;
                ctx.fillRect(X, Y, 1, 1); X++;
            }
            if(maxX >= Infinity) peakY = 1;
            canvas.style.width = canvas.width = peakX;
            canvas.style.height = canvas.height = peakY;
        } catch(err) {throw new Error();}
    } catch(err) {console.error("Could not draw image!");}
};



makeColor(text, 30);
```
Uninstalling gems with a specific pattern/same family
Tags: ruby, rails, rubygems, systems
Published: 2021-01-11 19:58:27

Ever wonderered how to uninstall same family of gems without uninstalling everything from your rubygems folder?

I have mistakenly installed `aws-sdk` gem when I all I needed was just `aws-sdk-s3` gem but left the command to complete and after sometime to my horror there were 264 gems installed which correspond to every available AWS services!

So, I wanted to remove all aws-sdk gems and startover again but at the same time didn't want to break my other gems. So I did write up small shellscript like the following: 

```shell
$ for x in `gem list aws-sdk- --no-versions`; do gem uninstall $x -a -x -I; done
```

Voila! All my 264 gems are uninstalled, not touching any other gem which is out of scope(_Thanks to AWS folks with their naming convention as their every gem starts with **aws-sdk-** prefix._).
My 30 days of Js journey: day 5
Tags: learning, javascript
Published: 2021-01-11 19:57:50

#day 5

Today I learnt how to set `style.backgroundImage` property to dynamically change the background image of the div tag. 

At first, I thought that it is a fair easy and straight forward task, but as it goes on I have to change my perception about the problem. I have to append the URL of an image to the empty URL property of the `background-image` CSS property.

Here is the HTML code of that div that i want to change the background-image:
```html
<div id="image">Hover over an image below to display here.</div>

    <img
      class="preview"
      alt="Styling with a Bandana"
      src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"
      onmouseover="upDate(this)"
      onmouseout="unDo()"
    />
```
Here is my CSS code:
```
#image {
  width: 575px;
  height: 650px;
  border: 5px solid black;
  margin: 0 auto;
  background-color: #8e68ff;
  background-image: url("");
  background-repeat: no-repeat;}
```

here is the javascript function to do the same:

```javascript
function upDate(previewPic) {
  var Url = previewPic.src;
  document.getElementById("image").style.backgroundImage = "url(" + Url + ")";
  document.getElementById("image").innerHTML = previewPic.alt;
}
```
In HTML there is a div which has a text in it. While it has some `background-color`. In my function, I want to change the `background-color` to a `background-image` with an image URL. So I have to concatenate the image URL.

This was done as a part of my Coursera course on web design.
OpenSleigh: a Saga management library for .NET Core
Tags: patterns, csharp, dotnet, microservices
Published: 2021-01-11 19:55:32

Hi All! Today I want to talk a bit about a pet project of mine I've been working on in the last few weeks. I called it *[OpenSleigh](https://github.com/mizrael/OpenSleigh)*, it's a Saga management library for .NET Core.

For those who don't know what the Saga Pattern is, Chris Richardson has a very good introduction [on his website](https://microservices.io/patterns/data/saga.html).

The basic idea is quite interesting: in a micro-service architecture, it often happens that we need to handle several long-running operations that span multiple services. [Distributed transactions](https://www.davideguida.com/improving-microservices-reliability-part-1-two-phase-commit/) are a nasty little beast and we also need a way to keep track of the global status and manage the whole flow.

#### There are two main schools of thought for this: ***Choreography*** and ***Orchestration***.

With **Choreography** the logic is decentralized, scattered and shared amongst the participants. They usually communicate using a Message Broker, like RabbitMQ or Kafka, which makes definitely easier adding and removing message publishers and consumers.

With **Orchestration** instead, the logic is centralised in a single component, which is in charge of the entire workflow. Once the process is triggered, this *orchestrator* will take care of calling each microservice (directly or via messaging) and handling responses and faults.

**OpenSleigh** falls into the realm of the orchestrators. It can be added to regular Console or Web applications, will spin up a bunch of **[BackgroundServices](https://www.davideguida.com/consuming-message-queues-using-net-core-background-workers-part-3-the-code-finally/),** and do its magic.

The Core module of **OpenSleigh** can be installed from [NuGet](https://www.nuget.org/packages/OpenSleigh.Core/). However, Transport and Persistence packages are necessary to properly use the library.

These are the packages available at the moment:

-   [OpenSleigh.Persistence.InMemory](https://www.nuget.org/packages/OpenSleigh.Persistence.InMemory/)
-   [OpenSleigh.Persistence.Mongo](https://www.nuget.org/packages/OpenSleigh.Persistence.Mongo/)
-   [OpenSleigh.Transport.RabbitMQ](https://www.nuget.org/packages/OpenSleigh.Transport.RabbitMQ/)

Now, there are already several valuable alternatives on the market, like [MassTransit](https://masstransit-project.com/) and [NServiceBus](https://particular.net/nservicebus). So why did I started this project?

#### Because I was **curious**. And I'm pretty damn sure many of you can relate.

I wanted to see how a Saga system works from the inside. Also, I wondered if I could build one myself from scratch. I wanted to create an open-source project and create a community around it.

So don't hesitate! Take a look at[ the repository](https://github.com/mizrael/OpenSleigh) on GitHub, download the packages, play with them, and send me your feedback!
365 Days of Coding
Tags: challenge, tutorial, webdev, javascript
Published: 2021-01-11 19:49:43

2020 is FINALLY almost over. Starting tomorrow I am going to do a 365 days of coding challenge. Every day of 2021 I will be solving a dev problem. I will do a blog post on here and hopefully put up a video on YouTube for each one. No promises the videos will get up every day but I will do my best and the blog posts will definitely be up every day. Some of the challenges will be easier than others. Some you will have seen before and some will be new! I hope you enjoy and join me in trying them yourself! 

follow me on here, [YouTube](https://www.youtube.com/channel/UCJ-cXLeP-2NJzMGmzJ9JHpQ/featured), and/or [Facebook](https://www.facebook.com/hellodevworldblog)! This will be a fun year! #365DaysOfCoding

I will post the challenge in the morning with the solution later in the day. If you would like to get the challenge emailed to you in the morning subscribe [here](https://lp.constantcontactpages.com/su/p9lFW6y/ChallengeSignUp)!
L’interface et l’objet Screen en JavaScript
Tags: javascript, codenewbie
Published: 2021-01-11 19:38:11

Dans cette leçon, nous allons étudier l’interface Screen à travers l’objet JavaScript Screen et voir les propriétés et méthodes intéressantes de cet objet.
 

# Présentation de l’objet Screen

L’objet Screen nous donne accès à des informations concernant l’écran de vos visiteurs, comme la taille ou la résolution de l’écran par exemple.

On va pouvoir utiliser ces informations pour proposer différents affichages à différents visiteurs par exemple.

On va pouvoir récupérer un objet Screen en utilisant la propriété **screen** de Window.

 

## Les propriétés et méthodes de l’objet Screen

L’objet Screen possède une grosse dizaine de propriétés dont 6 sont bien supportées par les navigateurs et particulièrement intéressantes :


**width** : retourne la largeur totale de l’écran ;
availWidth : retourne la largeur de l’écran moins celle de la barre de tâches ;

**height** : retourne la hauteur totale de l’écran ;

**availHeight** : retourne la hauteur de l’écran moins celle de la barre de tâches ;

**colorDepth** : retourne la profondeur de la palette de couleur de l’écran en bits ;

**pixelDepth** : retourne la résolution de l’écran en bits par pixel.
Notez que si le navigateur ne peut pas déterminer les valeurs de -

colorDepth et de pixelDepth ou si il ne veut pas les retourner pour des raisons de sécurité, il doit normalement renvoyer « 24 ».


Exemple d'utilisation des propriétés de l'objet JavaScript Screen

```
<!DOCTYPE html>
<html>
    <head>
        <title>Cours JavaScript by lawal alao</title>
        <meta charset="utf-8">
        <meta name="viewport"
          content="width=device-width, initial-scale=1, user-scalable=no">
        <link rel="stylesheet" href="cours.css">
        <script src='cours.js' async></script>
    </head>
    
    <body>
        <h1>Titre principal</h1>
        <p>Un paragraphe</p>
        
        <p id='p1'></p>
    </body>
</html>
```
code js
```
document.getElementById('p1').innerHTML =
    'Dimensions totales de l\'écran : ' + screen.width + '*' + screen.height +
    '<br>Surface disponible : ' + screen.availWidth + '*' + screen.availHeight +
    '<br>Palette de couleur : ' + screen.colorDepth +
    '<br>Résolution : ' + screen.pixelDepth;
```
L’objet Screen possède également deux méthodes lockOrientation() et unlockOrientation() mais qui sont aujourd’hui dépréciées et ne devraient pas être utilisées.

Merci a tous
[Typper v1.0.0] Can you type your way to the top? 🎮🏆
Tags: showdev, gamedev, react, javascript
Published: 2021-01-11 19:23:23

---
title: [Typper v1.0.0] Can you type your way to the top? 🎮🏆
published: true
description: 
tags: showdev, gamedev, react, javascript
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/kuyd81u8urub7yln2l89.png
series: 💻 Typper 💻 - A Web-based Typing Game
---

After working on and releasing the core functionality of the game, it was time to focus on getting **Typper** looking and feeling like a real game.

### So, what's new? 

✨ Main menu and game over screens
🏆 Game score and **leaderboard** (*yes!*)
🌈 General UI improvements


Give it a try, have fun and **feel free to reach out** and give feedback 📝 or report a bug ⭕️.

[🎮 PLAY 🎮](https://play-typper.web.app/)

{% github patricepeartree/typper-web no-readme %}

*[PatricePeartree](https://twitter.com/PatricePeartree) @ Twitter*
What's your favorite DO Hackathon submission so far?
Tags: discuss, dohackathon
Published: 2021-01-11 19:23:00

---
title: What's your favorite DO Hackathon submission so far?
published: true
description: Discussion on favorite hackathon submission.
tags: #discuss #dohackathon
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/ayygf5xl1e69habjcgss.jpg
---

The DEV + DigitalOcean Hackathon deadline is here! What project submissions do you like so far?

---
<span>Photo by <a href="https://unsplash.com/@element5digital?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Element5 Digital</a> on <a href="https://unsplash.com/s/photos/election?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span>