teleren/devto huggingface dataset:
Matt's Tidbits #79 - RxLifecycle woes
Tags: mattstidbits, android, rxlifecycle, tidbittuesday
Published: 2020-08-25 17:58:08

[Last week, I gave a quick update on an existing tidbit.](https://medium.com/@matthew.b.groves/matts-tidbits-78-a-new-build-view-6f8f67e5f168) As promised, this week I have a tidbit about RxLifecycle.

The app I'm currently working on uses RxLifecycle: https://github.com/trello/RxLifecycle

It's a neat concept - instead of having to use Rx `CompositeDisposable` objects to clean up your subscriptions, you can use a special Rx operator to have your subscription cancelled automatically when your Android view (Fragment, Activity, etc.) transitions to a particular lifecycle state:

```kotlin
observable
.compose(view.bindUntilEvent(ActivityEvent.PAUSE))
.subscribe()
```

RxLifecycle has some quirks - it may not call `unsubscribe()`, depending on the type of Rx stream you were using (Completable, Single, and Maybe types emit an error, instead of truly unsubscribing) - this leads to special error-handling code in your app that has to ignore certain types of errors that may be emitted by your Rx streams.

However, in my opinion, the worst part about RxLifecycle is that it is *REALLY* hard to unit test. Its `bindUntilEvent` method returns a final class, `LifecycleTransformer` (instead of an interface), which means you have to resort to using something like PowerMock to override its behavior.

[I've written before](https://medium.com/@matthew.b.groves/matts-tidbits-32-you-should-really-really-really-avoid-powermock-140d4de5b0ed) about why not to use PowerMock. This should be enough to convince you that maybe RxLifecycle isn't the best choice.

However, if you're still holding on, then please read this article, from the author of RxLifecycle about why you should switch to something else:
https://blog.danlew.net/2017/08/02/why-not-rxlifecycle/

If I come up with a good way to unit test RxLifecycle without using PowerMock, I will definitely let you know! For now though, I am switching over to manually managing my disposables.

Do you know of a way to unit test RxLifecycle that doesn't require PowerMock? Let me know in the comments below! And, please follow me on Medium if you're interested in being notified of future tidbits.

*This tidbit was originally delivered on August 14, 2020.*
Day 7 of 100DaysOfCode
Tags: 100daysofcode, javascript, eloquentjs, freecodecamp
Published: 2020-08-25 17:32:04

Today was a great learning day! Worked on some more JavaScript with both the Eloquent JavaScript book and FreeCodeCamp. Time went super quickly!

Higher-order functions were quite difficult for me to grasp and took some time but at least it felt like I was learning!

Have a great day and good luck with your challenges, whether it be in the form of code or other aspects of life.

## What I did today:

### 1. Read the rest of Chapter 5 of Eloquent JavaScript book
https://eloquentjavascript.net/05_higher_order.html
####What I learned from it:
* Using higher-order functions
* Array methods: filter, map, reduce, some
* Introduction to Composability

### 2. Did the exercises of Chapter 5 of Eloquent JavaScript
https://eloquentjavascript.net/05_higher_order.html
####What I learned from it:
* Higher-order functions are super tricky for me to grasp
* Got some great problem-solving experience

### 3. Worked on the Basic JavaScript lessons at FreeCodeCamp
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-javascript/
####What I learned from it:
* Working with objects
* Manipulating and creating complex objects

####Time spent learning:
Task 'reading_EJS'. Elapsed time: 59 min 34 s
Task 'ESJ_exercises'. Elapsed time: 96 min 48 s
Task 'FCC'. Elapsed time: 22 min 7 s

####Time spent actually coding: 2h 14 min

#### Total time: 2h 58min 29s
Tracked by using my [TaskTimer](https://www.arttupyykonen.com/tasktimer/) script and the [WakaTime app](https://wakatime.com/about)

### Further reading

####Summary of Chapter 5 - Higher-Order functions
"Being able to pass function values to other functions is a deeply useful aspect of JavaScript. It allows us to write functions that model computations with “gaps” in them. The code that calls these functions can fill in the gaps by providing function values.

Arrays provide a number of useful higher-order methods. You can use *forEach* to loop over the elements in an array. The *filter* method returns a new array containing only the elements that pass the predicate function. Transforming an array by putting each element through a function is done with *map*. You can use *reduce* to combine all the elements in an array into a single value. The *some* method tests whether any element matches a given predicate function. And *findIndex* finds the position of the first element that matches a predicate." [link](https://eloquentjavascript.net/05_higher_order.html#h_ErccPg/l98)

#### [FreeCodeCamp](https://www.freecodecamp.org/learn)
Check out FCC for best interactive exercises!

###Psst
You can check my answers to the exercises of Eloquent JavaScript. You'll find them [here](https://www.arttupyykonen.com/ejs-solutions/).

That's it. See you all tomorrow!
Creating a custom pipe | split() | Angular
Tags: angular, beginners, javascript, tutorial
Published: 2020-08-25 17:29:35

Pipes are a great way to manipulate data in a template. Out of the box, we get pipes for a date, currency and etc.
<br>
But there is always a situation occurs where you need to create your own custom pipes.
<br>
In my case, I needed to split `tracking_number` which was in a format like: `10001-TY778899` (user id-package id)
<br>
Now, I could serialize package_id alone in the backend, but, let's face it. I was too lazy for that. So I had to do it in the frontend.
<br>
Let's come to the actual part.
<br>
### Step 1: Create a pipe template and name it `split`

```bash
ng g pipe pipes/split
```

We will have this template:
```ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'split'
})
export class SplitPipe implements PipeTransform {

  transform(value: unknown, ...args: unknown[]): unknown {
    return null;
  }
}
```

Change parameters and write the code that splits string.

### Example use case

we have `text` argument which is the text in a template
```ts
{{ this is where we'll split | split: " " }}
```
I tried to split by `space` in the above example.

### The Code 

```ts
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'split'
})
export class SplitPipe implements PipeTransform {

  transform(text: string, by: string, index: number = 1) {
    let arr = text.split(by); // split text by "by" parameter
    return arr[index] // after splitting to array return wanted index
  }
}
```

Now, about that `tracking_number`, I needed the right part of 10001-TY778899 after splitting by - (hyphen) so in my case, I set default index number 1 hoping that I will get TY778899 which I actually did!

### Use Case
Before:

![before_photo](https://i.imgur.com/kA8VLrY.png)

```ts
<tr *ngFor="let p of user.stored_packages" (click)="package = p">
    <td>{{ p.id }}</td>
    <td>{{ p.tracking_number | split: "-" }}</td>
    <td>{{ p.courier_id }}</td>
</tr>
```

After:
![after_photo](https://i.imgur.com/UzrzhPm.png)

If you ever need particular index, keep in mind that you can use it like this

```ts
<td>{{ p.tracking_number | split: "-": 0 }}</td>
```

Well, this was a simple custom pipe example in Angular
---
---
If you are interested in Django, Vue.js too, I invite you to check out these projects that I made with love ❤

{% github Kenan7/corvento_backend %}
{% github Kenan7/corvento_frontend %}
Chainlink Hackathon
Tags: blockchain, react
Published: 2020-08-25 17:06:51

The Chainlink project is proud to announce the Chainlink hackathon! Let's build the next generation of universally connected smart contracts. 

Totaling $40k+ in prizes, this is Chainlink's biggest hackathon of the year. Get the opportunity to learn and work with some of the best in the business and build something stellar. We've seen MAJOR adoption of blockchain in the past few months, with Defi rocketing up over $6B. This is your chance, to be apart of the history of the #4IR. This is the window of opportunity to be apart of something great!

Truffle, Loopring, DappU, Aave, Tezos, Gelato, ENS, and more are joining as some of the esteemed sponsors - we're looking forward to seeing some awesome projects! 

Register here: https://hack.chain.link/
Installing a github server/database project locally
Tags: github, npm, beginners, javascript
Published: 2020-08-25 17:03:14

On the [Founders and Coders](http://foundersandcoders.com/) course, we make a new project each week, and then each team spends time at the end of the week reviewing the code of another team's project. 

When testing the projects (especially if the team hasn't managed to deploy them in our quick sprints-- which definitely happens-- it's the learning, not the finished product that matters!), we often want to install them locally and it confused me a couple of times so I've written it down. I hope you find it helpful, too! 

### **Clone & install dependencies**

Clone this repo to a new folder on your local machine using  `git clone` + the HTTP link from the Code dropdown menu in the project. Move in to the folder with `cd` + folder name

First, we want to: 

- Run `npm install` in your terminal to install all npm packages 

### **Initialise a local database**

Now we need to to create a local database for testing and connect to it with the project's init.sql file. 

Run:

- `psql` to enter into the postgres terminal
- `CREATE USER myuser SUPERUSER PASSWORD 'mypassword';` to create a dedicated psql local user for the application
- `CREATE DATABASE test_database WITH OWNER myuser;` to create a database
- `\connect test_database` to connect to your test database file
- `\include init.sql` to initialise and run the sql file
- handy hint: `ctrl + d` at any time while running psql in the terminal to get out of it

### **Create environment variables in a .env**

Next, set up your own environment variables for the JSON secret key, database_url and test_database_url (if applicable)

- Create an .env file in the very *root* of the project, the top file. It won't work anywhere else! 

    Add the following to this file: 

    - DATABASE_URL = "remote Heroku URI", if applicable 

    The Heroku config variables will be in the 'settings' section of your app, at a url like this: `https://dashboard.heroku.com/apps/APPNAME/settings`

    - TEST_DATABASE_URL  = "`postgres://username:password@localhost:5432/database_name`" - sub in the details we created earlier
    - SECRET- a secret key which will be used to create a JSON Web Token (JWT) for storing cookies

- Now we can run it using commands in our terminal.  Check the package.json file under 'scripts' to see the project-specific commands, but they are likely to be:
    - `npm run dev` to start the server using nodemon. Nodemon auto restarts anytime you change something, so you don't have to do it! 
    - `npm test` to run tests locally if there are tests to run

And you're good to go! If I've missed something, let me know. :octopus:
Laravel-Vue-q-uploader
Tags: laravel, vue, quasar, uploader
Published: 2020-08-25 17:02:21

# laravel-vue-q-uploader
fast and easiest way to upload files in [Laravel](https://laravel.com/) [Vue](https://vuejs.org/) app using [quasar-framework](https://quasar.dev/)  QUploader

Create [Vue](https://vuejs.org/) component 
```[vue]

<template>
    <div class=" row my-card">
      <q-uploader
        class="my-card"
        accept="image/*"
        :fieldName="(file) =>`image${file.name}`"
        :headers="[ { name: 'Authorization', value: $toks }]"
        with-credentials
        multiple
        batch
        @uploaded="useUploaded"
        :url="files=>`${$url}/upload-image`"
        label="Select Course Image to Upload"

      />
    </div>
</template>

<script lang="ts">
import {
  defineComponent
} from '@vue/composition-api'

export default defineComponent({
  name: 'ImageUploader',
  setup () {
    function useUploaded (info:{files:string[];xhr:{response:string}}) {
      console.log('files :>> ', info.files)
      console.log('url :>> ', JSON.parse(info.xhr.response))
    }
    return { useUploaded }
  }
})
</script>
```
[Laravel](https://laravel.com/) route in my case i will API
```[php]

Route::post('upload-image', 'ImageController@ImageUpload');

```

[Laravel](https://laravel.com/) controller 

```[php]

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Storage;
use Validator;

class ImageController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:api'])->except([]);
    }

    public function ImageUpload(Request $r)
    {
        $validator = Validator::make($r->all(), [
            'image.*' => 'required|file|image|mimes:jpeg,png,gif,svg'
        ]);
        if ($validator->fails()) {
            logger(['error' => $validator->errors()]);
            return ['status' => 0];
        }
        $images = $r->all();
        $paths = [];
        foreach ($images as $image) {
            $extension = $image->getClientOriginalName();
            $filename  = 'image-' . time() . '.' . $extension;
            Storage::disk('public')->putFileAs('/images/', $image, $filename);
            $paths[] =   url(Storage::url('images/'.$filename));
        }

        return $paths;
    }
}


```

if any issue [check](https://github.com/diadal/laravel-vue-q-uploader/issues)

*also you can buy me a coffee @ [Patreon](https://www.patreon.com/diadal)*
Badge it- A Github Action to automate the process of adding Badges to your Readme.
Tags: actionshackathon, github, javascript, showdev
Published: 2020-08-25 16:58:53

Hi, Myself [Rocktim](https://rocktim.xyz) and this is my submission for Actionshackathon.

[Instructions]: # (To submit to the GitHub Actions x DEV Hackathon, please fill out all sections.)


### My Workflow
#### _What is Badge-it?_
***Badge-it*** is a simple GitHub action that automates the process of adding the [Badges](https://shield.io) to your projects Readme :zap: We all love to add badges to our GitHub projects to decorate it in a way so that the project does not look dull.

But the process of adding badges every time you create a GitHub project can be quite tedious. From all the copy-pasting to configuring your `github_username` and `repo_name`. And that's what I tried to solve with ***Badge-it***. It saves you the time of configuring and adding badges
yourself manually.

### Submission Category: 
I am submitting this action under the following categories.

* Interesting IoT 
* Wacky Wildcards)


### Yaml File or Link to Code
 ***Usage***

The action takes 3 inputs. 
- A Github token
- A string of badges separated by ```commas(,)```
- A base style for your badges.

```yml
      - name: Add Badges
        uses: rocktimsaikia/badge-it@master
        with:
          GITHUB_TOKEN: ${{ secrets.MY_TOKEN }}
          badges: 'gh_license, gh_version, github_stars'
          badge-style: 'flat-square'
```

***Bagde-it Repo***

{% github https://github.com/RocktimSaikia/badge-it %}


### Additional Resources / Info

Currently, there is no open-source project using this action. So in the meantime, I am linking [a demo repository](https://github.com/RocktimSaikia/badge-it-demo) for demo purposes.

Thank you for taking the time and checking out ***badge-it***. If you like the project don't forget to add a star :zap: or if you want to contribute you are more then welcome. :rocket:

### Update :rocket: :zap:
***newly added badges will be updated here***

![avavilabe badges](https://dev-to-uploads.s3.amazonaws.com/i/6ns7ipvhauguqzh1sm1s.png)
Trajectory LIVE starts Wednesday - register for free
Tags: devops, testing
Published: 2020-08-25 16:58:18

---
title: Trajectory LIVE starts Wednesday - register for free
published: true
description: TrajectoryLIVE is two days of talks, product updates, live Q&A, and fun interactive sessions brought to you by LaunchDarkly. Discover how leading development teams use Feature Management for improved visibility, testing in production, and safer progressive releases. 
tags: devops, testing
//cover_image: https://launchdarkly.com/img/trajectory/brand/trajectory_live.jpeg
---

![Trajectory LIVE](https://launchdarkly.com/img/trajectory/brand/trajectory_live.jpeg)

# Break orbit, not systems

Trajectory LIVE is two days of talks, product updates, live Q&A, and fun interactive sessions brought to you by LaunchDarkly. Discover how leading development teams use Feature Management for improved visibility, testing in production, and safer progressive releases. 

[Register](https://trajectoryconf.com)
Do you know WebRTC?
Tags: career, freeswitch, webtrc, remote
Published: 2020-08-25 16:49:54

Are you sick of bad web conferencing? Feeling the "zoom fatigue"? Be a part of the SOLUTION!

We have a USA-based developer/tester opening at Immersitech (https://immersitech.io). We have developed a next generation spatial (3D) sound engine for web conferencing, distance learning, and gaming. This is a local (Rochester, NY) or remote USA-based position. 

This role will involve working on client-side WebRTC and SIP applications that interact with a wide variety of host collaboration applications, as well as creating adapters to host systems to interact with our sound engine. 

* WebRTC/OPUS, SIP, VoIP
* JavaScript, ES6+, Typescript, Python, HTML5 with embedded media, JSON, XML
* Experience with C/C++
* React/Hooks, JSX, RxJS, Node, Meteor, Electron, Angular
* OS experience with Linux/Ubuntu, Android, iOS, MacOS, Windows and associated browsers - Chrome, Firefox, Safari, Edge
* Git, GitHub
* Using and developing secure REST-based APIs and secure websocket applications

Other skills:
* Audio software engineering experience a plus
* Additional consideration for development experience with communications platforms such as (but not limited to) Freeswitch, Slack, WebEx, Zoom, MS Teams, Big Blue Button, Blackboard, Twillio supporting multi-party collaboration/learning.
* Strong documentation and communication skills
* Experience with automated testing platforms

If you think you have the skills, and want to be a part of a growing startup, let us know! Email us at hiring@immersitech.net
3 SIMPLE TRICKS FOR RECURSION OVER A TREE STRUCTURE in JavaScript / NodeJS
Tags: javascript, node
Published: 2020-08-25 16:40:20

---
title: 3 SIMPLE TRICKS FOR RECURSION OVER A TREE STRUCTURE in JavaScript / NodeJS
published: true
description: 
tags: javascript, nodejs
---

There are a few simple tricks I use to help simplify the process of creating a recursive function.

Recursion doesn't have to be difficult. These tricks, not only help you in writing and reasoning about a recursive function, but will also help reduce the complexity of that function.

{% runkit %}
const rxIsoDate = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/
const isIsoDate = value => typeof value === 'string' && rxIsoDate.test(value)

const raw = {
	a: 1,
	date: '2020-07-17T01:32:26.206Z',
	second: {
		b: 2,
		createdAt: '2020-07-17T01:32:26.206Z',
		third: {
			c: 3,
			updatedAt: '2020-07-17T01:32:26.206Z'
		}
	}
}

const toJsDate = obj => {
	if (isIsoDate(obj)) return new Date(obj)
	if (typeof obj !== 'object') return obj

	const nextObj = {}
	for (const [prop, value] of Object.entries(obj)) {
		nextObj[prop] = toJsDate(value)
	}
	return nextObj
}

toJsDate(raw)
{% endrunkit %}

As a BONUS, check out the Runkit here which also includes an example replacing the for loop with reduce https://runkit.com/joelnet/5f1344792ad936001ad53c94

Be sure to [subscribe](https://www.youtube.com/c/JoelCodes?sub_confirmation=1) for more videos like this!

[![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xb6e84yj8yc2gqelz4op.png)](https://www.youtube.com/c/JoelCodes?sub_confirmation=1)
How to restore native browser code
Tags: javascript, webdev
Published: 2020-08-25 16:33:13

<p>Native code is functionality that has been included by the browser's engine and not defined by you, the programmer. Some browsers like Chrome allow you to see if a function is native by simply entering it in the console (and not calling it with parentheses):</p><img src="https://res.cloudinary.com/dzynqn10l/image/upload/v1600924032/JS%20Bits/chrome_uYVLnVqDXB_dx0xlc.png" style="width: 350px;">

<p>Occasionally, you may encounter a scenario where some native code has been overwritten. In my experience as a 3rd party dev, I've seen a few instances where the console has been overwritten to an empty function. This is usually done by clients who are hyper-cautious about sensitive customer information being shown (<i>but seriously, if someone really wants to find this info they will!</i>). Trying to write code without a functioning console is a giant pain so I had a good use case to restore the console's native functionality. (Note this was only done for local development and not deployed live!).</p>

<p>For example, the <a href="https://m.kohls.com/" target="_blank">Khols.com</a> mobile site has all their console methods overwritten to an empty function (Be sure to simulate the mobile site in your emulator).</p><img src="https://res.cloudinary.com/dzynqn10l/image/upload/v1600924032/JS%20Bits/console_1_t2vatq.png" style="width: 160px;">

<p>So here's how we can restore it:</p>

```js
function createConsoleProxy() {

  // Create dummy iframe to steal its fresh console object
  const iframe = document.createElement('iframe');

  // Add iframe to current window's scope in a hidden state
  iframe.id = 'console-proxy';
  iframe.style.display = 'none';
  document.body.insertAdjacentElement('beforeend', iframe);

  // Reassign value of console to iframe's console 
  const proxyIframe = document.querySelector('#console-proxy');
  window.console = proxyIframe.contentWindow.console;
}
```

<p>When we enter <code>console.log;</code> in the console... BAM! It's back to it's "native" state!</p><img src="https://res.cloudinary.com/dzynqn10l/image/upload/v1600924032/JS%20Bits/chrome_G2uvuA5ckm_ayqcf6.png" style="width: 240px;">

<p>Before this method was used, a coworker came up with a clever alternative to view messages by creating a custom <code>log()</code> function that would take user input and prepend it to the body:</p>

```js
function log(msg) {
  const body = document.body;
  body.insertAdjacentHTML('afterbegin', `<div>${msg}</div>`);
}
```

<p>This worked enough to see simple messages but we quickly realized we needed the ability to expand objects so it had limited use. But challenges like this are always fun. 🤪</p>

----------
Check out more #JSBits at my blog, [jsbits-yo.com](http://jsbits-yo.com/). Or follow me on [Twitter](https://twitter.com/JS_Bits_Bill)!
How to hide the number of Viewers and ratings on Youtube.
Tags: extension, youtube, beginners, chrome
Published: 2020-08-25 16:20:48

I created a Chrome extension to hide the number of Watching now and ratings on Youtube.

## Download Link
[Youtube同時接続数非表示- HideYoutubeViewersAndRatings](https://chrome.google.com/webstore/detail/youtube%E5%90%8C%E6%99%82%E6%8E%A5%E7%B6%9A%E6%95%B0%E9%9D%9E%E8%A1%A8%E7%A4%BA-hideyoutu/ibdkcdjfoahbpcoajafabdokfdgcjijd)

##  What is this?
It hide the number of viewers and concurrent connections on youtube.
It also hide the number of Watching now people on Twitch.

## Directory structure
this is simple.It loads the appropriate CSS for the site.
- HideYoutubeViewersAndRatings📁
  - manifest.json 
  - images
      - get_started48.png (for icon
  - option
      - option.html
  - youtube
      - style.css(for erasing elements on youtube
  - Twitch
      - style.css(for erasing elements on Twitch

## Feedback
[Note](https://note.com/siroiudon/n/nfcdb37f1bb52)
[お題箱](https://odaibako.net/u/siroiudon)
[ChromeExtensionPage](https://chrome.google.com/webstore/detail/youtube%E5%90%8C%E6%99%82%E6%8E%A5%E7%B6%9A%E6%95%B0%E9%9D%9E%E8%A1%A8%E7%A4%BA-hideyoutu/ibdkcdjfoahbpcoajafabdokfdgcjijd)

## social tipping💸
[PaypalMe](https://paypal.me/shiroiudon)

Twitter🐦:[@siroiudon](https://twitter.com/siroiudon)