teleren/devto huggingface dataset:
Live Discord Bot in development
Tags: discord, bot, python
Published: 2022-06-27 01:43:48

## Live Updates

Working on a bot can become troublesome when attempting to implement a new feature or when working on a new command that entails many changes. Some commands may also be refactors of pre-existing ones which will make the deployed bot go a little crazy.

The best way that I've found to working on my bot while currently running is to run two separate instances of the bot. I have the live bot running on a Raspberry Pi with up to date Python and Git installed (which was a bit of a challenge to work around).

In the past I've had a separate line that was commented out during my commits for the bot until I needed to develop it using a different prefix. This worked for a while but was a bit tiresome to keep switching the comment on and off. Sometimes forgetting entirely and pushing the uncommented line up to the live code. This called for a `git --amend --no-edit` commit which was again another step out of the way.

## The Git fix

As of Git version 2.22, calling `git branch --show-current` would output the current name of the checked out branch. With a few lines, that name can be placed in a file and checked during each command to tell the bot what prefix to use.

For my use I placed this in a generic Functions.py file and import the function for when I call on the Client().

```python
import nextcord
import json
import os

client = nextcord.Client()

def getPrefix(client, message):
  try:
    os.system("git branch --show-current > ./references/git-current-branch")
    with open("./reference/git-current-branch", "r") as currentBranch: 
      repo = currentBranch.read()
  finally: 
    # If on development branch or
    # If not main branch whichever is easier
    if repo == "development\n":
      return "."    # Prefix to separate from live code
    # Return the prefix for whichever server called the command
    else:
      with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)
      return prefixes[str(message.guild.id)]
```

The `os.system` is a neat way of having the bot pass commands directly to the command line, in this case to show the current git branch name.

**NOTE:**
> When using the '>' this will mean to overwrite the data in that file which is what we want.
>> Using '>>' instead will append to the existing file and cause a lot of clutter and won't be usable without the use of writing another function to trim it out.

This will be just another tool to help aid with development of a live bot without disruption and prevent errors like sending the wrong prefix like I had done a few too many times.
Don’t prioritize speed for e2e testing but consider smarter test schedules
Tags: webdev, testing, javascript
Published: 2022-06-27 01:33:43

End-to-end(e2e) testing such as by Cypress and Playwright is considered slow compared to unit/integrated testings such as by Jest.

In this post, however, I would like to argue that a few devOps practices can dodge this slow performance issue in the devOps cycle and the developers can take fully advantage of e2e based quality assurance.

**Why is the slow performance considered an issue, by the way?**

Testing performance is usually considered significant because developers want to include it in the CI/CD cycle, which should get completed as fast as possible.

It usually takes more than 30 secs to execute one e2e testing for one web page. And thus, it would take more than 5 mins when e2e testing covers more than 10 pages.

**Common CI/CD pipeline**
1. Make a pull request on a feature branch
2. Build/compile the application
3. Run tests
4. Merge the new branch to the main branch
5. Deploy the new application to servers

Due to the popularity of the above CI/CD pattern, front-end developers struggle to include e2e testing in Step 2. However, it means that the testing tightly binds with its development & deployment flow.

**Problems**
1. Every new push to the remote repository runs entire new tests. Too much waste of computing resources.
2. New development/refactoring/configuration easily breaks some of the tests. And we want to fix broken tests at a different time.

## Run entire tests only in specific situations

Include static test (eslint/prettier) and unit test (Jest) in Step 2, but not entire e2e tests.

Of course, it is necessary to run prepared e2e tests before releasing the application to the production environment. But Git tags usually come into play for controlling a production release these days. In fact, the Github action supports [tag based actions](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on). Thus, we can separate the CI/CD phase and the production release phase.

## Run e2e tests for only affected parts 

We can search modified files by git commands on a feature branch and run e2e tests to these files only on push to the remote repository.

So, for example, if a developer modified pageA.js, pageB.js and pageC.js, the CI/CD pipeline runs pageA.jstest.js, pageB.jstest.js and pageC.jstest.js 

```
git ls-files | -I % /bin/bash -c '<test-command> %test.js;'
```

Or you can manually run tests regarding the affected pages and upload the test results to the pull request description as a part of the internal regulations. 

## Run all tests in parallel

Most e2e automation tools such as Cypress and Playwright support running tests in parallel. 

Each test should not be too lengthly because parallel processing mechanism is file-based. If the test file length is more than 200 lines, it would be wise to split the test file into two.
How to make your JS/TS app logging better
Tags: webdev, javascript, tutorial, typescript
Published: 2022-06-27 01:33:04

I recently released a blog post about implementing [Adze](https://adzejs.com/) into your web application to vastly improve your logging experience. Check it out!

[https://www.andrewstacy.com/blog/better-javascript-logging-with-adze/](https://www.andrewstacy.com/blog/better-javascript-logging-with-adze/)
Mufi Lang v0.1.0 Released
Tags: c, computerscience, programming, rust
Published: 2022-06-27 00:54:02

Mufi v0.1.0 is finally out after starting to work on it at around March. The language is fairly small, documentation is still in progress but the actual language is readily available to download. 

The language uses a C bytecode compiler and a standard library written in Rust utilizing C bindings. This release, codenamed _Baloo_ is purposely unoptimized, v0.2.0 will be and using a benchmarking program written in the repo, it will help compare the performance gains between them. 

The language is only officially supported for Unix systems, Windows is sadly complicated to set up in my native Linux environment, but I am still looking to add some functionality to provide Windows support. 

For installation instructions look at the README in the [repo](https://github.com/MKProj/Mufi-Lang).
[Algorithms] 2 - Review(2)
Tags: algorithms
Published: 2022-06-26 23:13:00

#4. Binary Search

## Definitions

- It is designed to enhance the linear search

- Finds the median value, and compare with the target value and throw away half of the array including the median value if the median value does not match with the target value.

## Things to keep in mind

- Time complexity: O(logn)

- The array needs to be sorted.

#5. Heaps

## Definitions 

- Basically an array, but structured to function as heap.

- Min heap: The smallest value is the root

- Max heap: The greatest value is the root

## Things to keep in mind

- Parent: floor(index-1/2)

- Left: index*2 + 1

- Right: index*2 + 2

- Insertion takes O(logn) (Keep swapping values)

# 6. Binary Tree

## Defintions

- Full Tree: Every node can have **either zero or two children.**

- Complete Tree: Every level has to be full except the last level + the last level nodes need to be pushed to left as much as possible.
5 gamified learning experiences to learn Web Dev
Tags: webdev, javascript, css, tutorial
Published: 2022-06-26 23:11:51

---
title: 5 gamified learning experiences to learn Web Dev
published: true
description: learning should be fun. Learn some web dev skills while learning in gamified setting.
tags: webdev, javascript, css, tutorial
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z31htweun25cscry0y03.png
---


> Does learning have to be boring, not in my opinion. I'm sure you also agree that you learn better if you have fun. Here's a list of 5 gamified experiences that will help you learn web development.

{% embed https://youtu.be/mkbGAI3uNn0  %}

- [Flexbox froggy](http://flexboxfroggy.com/). Learn to navigate a frog by and learn about Flexbox at the same time.
- [Minecraft Education](https://education.minecraft.net/) You have code window that helps you affect the world in Minecraft, who doesn't want to build things faster? Blocks, JavaScript as well as Python available.
- [CodeCombat](https://codecombat.com/) Imagine using code to take yourself through dungeons. This might look like it's made for 10 year olds but I had a ton of fun :)
- [Twilio Quest](https://www.twilio.com/quest) This is seriously good. Travelling the Universe while learning JavaScript, Python and Twilio API, sounds pretty good to me.
- [MakeCode arcade - skillmaps](https://arcade.makecode.com/#) You learn to build various games while being introduced to coding. You may start with blocks, but you will be able to advance to JavaScript or Python prettty quickly.

There are a ton of these gamified platforms so I would love to hear your favourite in the comments and why :)
Laravel how to set app environment during tests
Tags: tests, laravel, enviroment
Published: 2022-06-26 23:09:26

---
title: Laravel how to set app environment during tests
published: true
date: 2022-06-26 22:59:00 UTC
tags: tests, laravel, enviroment
canonical_url: https://dcblog.dev/laravel-how-to-set-app-environment-during-tests
---

 ![Laravel how to set app environment during tests](https://dcblog.dev/images/posts/laravel-how-to-set-app-environment-during-tests.png) 

If you need to set an environment to be a specific one such as staging you can override the environment by changing the config value **app\_env**

```php
config(['app.env' => 'staging']);
```

Then doing a dd on config(‘app.env’) will return that environment you’ve just set.

I haven’t found a way to set environments with **app()->environment()** so instead, I recommend using this `in_array` function and passing in the `config(‘app.env’)` and then specifically defining the environments. 

```php
in_array(config('app.env'), ['local', 'staging'])
```

For example, say you have this in a command:

```php
if (! in_array(config('app.env'), ['local', 'staging'])) {
    $this->error(‘Will only run on local and staging environments’);
    return true;
}
```

Test this runs when the environment is set to production

```php
test(‘cannot run on production’, function () {

    config(['app.env' => 'production']);

    $this->artisan('db:production-sync')
        ->expectsOutput(‘DB sync will only run on local and staging environments’)
        ->assertExitCode(true);
});
```
Day 79: Busy weekend
Published: 2022-06-26 22:31:51

Hi!
So last Friday I had many plans for the weekend including me time some learning and writings but it turned out to be one of the busiest weekends and a fully occupied. I was mainly working on authentication with firebase the phone and email authentications but there was many things to consider and learn so it took longer tan expected. I didn't do most of the things I planned to do but it was a productive one and at the end of the day I'm the one making the rules so..., yeah 😀
this week will be mainly focusing on the dashboard part of the application and expect it to be intense as well many meeting and alot to learn but for now I rest we will get to it when we get to it...

Signing off...
Show Spotify Now Playing in Twitch Studio
Tags: webdev, spotify, twitch, tutorial
Published: 2022-06-26 22:08:24

I decided recently that I would start live coding my personal projects outside of work on [Twitch](https://www.twitch.tv/)🚀. It's something I've always considered and after reading about how it can help improve your productivity I thought I'd give it a go (here's [my channel](https://www.twitch.tv/n1ckdm) 😎).

Obviously, before actually starting my first stream I had to procrastinate a little.. so I spent some time getting everything setup. I had originally planned on using [OBS](https://obsproject.com/) as my streaming software, but ended up choosing Twitch's own software "Twitch Studio" as it seemed to be more user friendly for the newbie streamer. For the most part it is, but I quickly ran into a problem.

I managed to get everything setup apart from the ability to display my currently playing song from Spotify. While this is a little bit of an unnecessary addition to my overlay - I thought a tiny bit of extra effort to get it right would be worth it.

Turns out it's not that straight forward to setup 🙄. I couldn't easily find a solution without writing my own HTML page - so that's what I did. I thought I'd post what I came up with here to save someone else 30 minutes of their life...

The full HTML page is saved in a [Gist ](https://gist.github.com/n1ckdm/6eb52bee0950596ecf802e2ecc2109ed)on GitHub (sorry for my terrible JavaScript):

{% embed https://gist.github.com/n1ckdm/6eb52bee0950596ecf802e2ecc2109ed %}

The JS just uses the last.fm API to grab your most recently played track(s) from their API. It continues to ping it every 10 seconds (which is fast enough for a Now playing feed). I made a little card to display it nicely.

To get it up and running, just add a Browser Source Layer to the scene you want your feed to appear in and then open the HTML file (which you should save locally). You'll need to edit the HTML to include your own Auth Token from LastFM - which you can grab from their API documentation easily enough. You will also need to hook up your Spotify account to LastFM. Obviously you shouldn't host this page anywhere or people could steal your Token...

A brief note as well that you shouldn't stream with any copyrighted music or you could get banned from Twitch. There are lots of playlists you can choose from, two of my favourites are [this one](https://open.spotify.com/playlist/3zR71nMKdPoFo46SYKxFhf) and [this one](https://open.spotify.com/playlist/7KacetCAhxUX5la5Kj88Ld?si=fa88dca2373e41e8) 🦄.

That's all really, not too much to it!

Cover art by [Maik Jonietz](https://unsplash.com/@der_maik_?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
React - You might not need that many states!
Tags: webdev, javascript, react, tutorial
Published: 2022-06-26 21:59:51

You probably know not to use one single state for everything a component needs.
But in avoiding that, sometimes you feel compelled to split the state in one for each thing you need.

But you don’t need to do that!

If you have things that change together, then you end up setting a “waterfall“ of events that could be bundled together. 

## The form example:

Let’s say you have this form example:

```jsx
function FormExample(){
	???

	return (
		<form>
			<input name="data1" />
			<input name="data2" />
			<input name="data3" />
		</form>
	)
}
```

You can have it split into three states:

```jsx
const [data1, setData1] = useState(data1Default)
const [data2, setData2] = useState(data2Default)
const [data2, setData3] = useState(data3Default)
```

But you could also:

```jsx
const [allData, setAllData] = useState(dataDefault)
// and then...
const updateData = (event) => {
	setAllData((oldState) => ({
		...oldState, 
		[event.target.name]: event.target.value
	}))
}
```

With this, as long as you name the inputs you can update all the state in one go.

And it doesn’t need to be a `form`, anywhere the data will always change together is a place you might not need to split.

And if one piece depends on another one, you would have a harder time dealing with it or having `useEffects` using the values as dependencies or risk having outdated data showing.

### TIL: this works with nested data too!

The dependency array of hooks works with nested data `[data.like.this]` and not only that… even if you have data that might not be there it works! 
So, you can have the state in one place and use `[data?.optional?.chaining]` instead of splitting or putting the entire object in the array with a `if` value then `do stuff`.

---

TLDR: Split if it makes sense for the data to be in different places, else, as long as it’s readable and maintainable… you might want to consider sticking to one state. 

---

Cover Photo by [Kelly Sikkema](https://unsplash.com/@kellysikkema?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/full-basket?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
Why in Python does PEP-8 set the line to a maximum of 79 characters?
Published: 2022-06-26 21:42:02

You may have already wondered why in Python we write code with only 79 characters per line, and there are three good reasons, one  is official, and the others are just practical.  Let's talk about them next:

The first reason is that, on some older monitors, the limit of columns displayed on the screen was 80 characters, so that the code wouldn't be broken in the display (who has never had this problem with a line break at the wrong time, right? ?) the code was written to fit in 80 columns.

The second reason is accessibility. Keeping few columns makes it easier for those who need larger letters, as they have some difficulty seeing. This for me was reason enough for us to use only 79 columns!

The third reason is practical. With 79 columns, you can easily mirror your code and have two editors open at the same time on an HD+ monitor. This detail when resolving a conflict or debugging the code is very useful!

And you, did you already know why use only 79 characters per line? I really enjoyed knowing! And if you want to know more style tips, you can consult Python's PEP-8, there are several tips to make your code more readable!
Skymiles Estimator Project
Tags: kotlin, aurelia, hobby, showdev
Published: 2022-06-26 21:22:38

---
title: Skymiles Estimator Project
published: true
description: A web-based calculator to estimate earnings for the Delta SkyMiles program, including MQM, MQS, MQD, and redeemable Miles.
tags: kotlin, aurelia, hobby, showdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7rvdqd3r7nbp5ntcues.png
canonical_url: https://fwmotion.com/projects/skymiles-estimator/
---

Skymiles Estimator is a calculator for estimating the potential earning of Delta SkyMiles status and awards from flights operated by SkyTeam partner airlines. Skymiles Estimator breaks down earnings for a segment-by-segment view of earning potential across entire itineraries.

* [Try Skymiles Estimator on your own itinerary](https://fwmotion.com/projects/skymiles-estimator/skymiles-estimator.html)
* See a sample:
  1. [Sample 1](https://fwmotion.com/projects/skymiles-estimator/skymiles-estimator.html#sample)
  2. [Sample 2](https://fwmotion.com/projects/skymiles-estimator/skymiles-estimator.html#sample2)
  3. [Sample 3](https://fwmotion.com/projects/skymiles-estimator/skymiles-estimator.html#sample3)
* Read more about it on my [Skymiles Estimator project page](https://fwmotion.com/projects/skymiles-estimator/)
* Or view the source on the [GitHub project page](https://github.com/FwMotion/skymiles-estimator)
Why the real metaverse is doomed to never appear.
Published: 2022-06-26 20:10:44

Well, I'm open to criticism, but I want to discuss why the true metaverse never comes. Let's start with terminology. The Metaverse is a permanent virtual space in which people can interact with each other and with digital objects through their avatars using virtual reality technologies. Interaction can take place with the help of various technological devices, both with the help of traditional personal computers and with virtual and augmented reality headsets.
I also want to add some of my thoughts. The Metaverse shouldn't be dependent on any big company like Facebook or Microsoft, as that would bring it all down to business. It seems to me that the metaverse should be supplementable by ordinary users or other programmers, and for this you need some kind of standard library or utility for free development.
Using fetch() API on cocktailsDB API to display random cocktail inspirations with their recipes
Published: 2022-06-26 20:09:00

**Introduction**
The fetch()api allows us to make HTTPS requests from the server to the browser.
We create a simple application that generates random cocktail inspirations to the users using the[CocktailsDB API](https://www.thecocktaildb.com/api/json/v1/1/random.php)
Used Fetch API to get a list of cocktails from the Cocktails DB api Getting:
Cocktail image, Cocktail name, Cocktail glass,cocktail ingredients and measures
**_JavaScript concepts used_**
 DOM manipulation
 fetch() API
 Event listeners

![Screenshot](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkx8zd7qtel5r9prcfd3.png)
Create an empty folder where you will store the project.
The folder should have an index.js file , an index.html file and a style.css for custom styling 
We start by making a fetch request to the CocktailsDB API URL.

```
fetch('https://www.thecocktaildb.com/api/json/v1/1/random.php')
		.then(res => res.json())
		.then(res => {
		createCocktail(res.drinks[0]);
	});
});
```
After sending a fetch request to the API we get the list of the random cocktails, their images,ingredients, measure and recipe instructions and we update it on the DOM.

```
const createCocktail = (cocktail) => {
	const ingredients = [];
	// Get all ingredients from the object. Up to 20
	for(let i=1; i<=20; i++) {
		if(cocktail[`strIngredient${i}`]) {
			ingredients.push(`${cocktail[`strIngredient${i}`]} - ${cocktail[`strMeasure${i}`]}`)
		} else {
			// Stop if no more ingredients
			break;
		}
	}
	
	const newInnerHTML = `
		<div id="rowa" id="cocktail-dataa">
			<div id="five">
				<img src="${cocktail.strDrinkThumb}" >
            </div>
            <div id="seven">
               <h4>${cocktail.strDrink}</h4>

			   <div class="likes"> 
			      <button id="likeButton">
			        <i class="fa fa-thumbs-up"></i>
			      </button>
				  <input type="number" id="inputLike" value="0" name="">likes</input>
		       </div>
			 
			   
				<p><strong>Category:</strong> ${cocktail.strCategory}</p>
				<p><strong>Glass type:</strong> ${cocktail.strGlass}</p>
				<p><strong>Type:</strong> ${cocktail.strAlcoholic}</p>
				<h5>Ingredients:</h5>
				<ul>
					${ingredients.map(ingredient => `<li>${ingredient}</li>`).join('')}
				</ul>
                <h5>Instructions:</h5>
				<p>${cocktail.strInstructions}</p>
				
			</div>
		</div>

	`;

```
You can go ahead and click on the getcocktail button to display a random cocktail on the screen.

Also, we use the click event listener to allow the user to add likes to the cocktails they like most

```
	cocktail_container.innerHTML = newInnerHTML;
	let likebtn = document.querySelector('#likeButton');
    let inputLike= document.querySelector('#inputLike');

    likebtn.addEventListener('click', () => {
	inputLike.value = parseInt(inputLike.value) + 1;
	// inputLike.style.color = "#12ff00";
})
	
```