teleren/devto huggingface dataset:
PHPUnit mock function with different values
Tags: php, testing, beginners
Published: 2020-11-21 23:27:51

When writing unit test, we sometimes mock a function with different
parameter values and expect different return value(s). For example in the popular e-commerce system magento, it's product model class has a getData function. Using this function you can get different attribute(s) of a product.

#####Function signature#####

```
getData($key = '', $index = null)
```

We wish to get the product color and product size attributes. The code $product->getData('color') should return value "red" and the code $product->getData('size') should return "s". The second parameter $index is null, you can change it to any other value depending on your requirement.

#####Example mock code#####
```
$product = $this->createMock(Product::class);
$product->method('getData')->willReturnMap([
       ['color', null, 'red'],
       ['size', null, 's'],
]);
```

**Learning objectives**
Test your php classes
Continuous integration

**Prerequisites**
Experience with the basics of variables, data types, and running php scripts
Experience setting up PHPUnit, ideally with Composer


Article originally published on http://www.rosenborgsolutions.com/articles/phpunit/phpunit-mock-same-function-with-different-parameters
How to empty the contents in an array in JavaScript?
Tags: javascript
Published: 2020-11-22 00:00:00

---
  title: How to empty the contents in an array in JavaScript?
  published: true
  tags: JavaScript
  date: Sun Nov 22 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/how-to-empty-array-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-a0d41aa3a50c25251a00c1141ebf015a.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/how-to-empty-array-javascript)
  
There are many ways to empty the contents in an array in JavaScript.

## Using assignment operator `=`

One of the ways is to use the assignment operator `=` like this,

Consider this array of numbers,

```js
// number array
let numbersArr = [23, 45, 56, 78];
```

Now let's emtpty the contents array using the assignment Operator `=`,

```js
// number array
let numbersArr = [23, 45, 56, 78];

// empty contents in array
// using = operator
numbersArr = [];

console.log(numbersArr); // []
```

See this example live in [JSBin](https://jsbin.com/desuqefeli/1/edit?js,console).

But as you can see the assignment operator works only if the array is declared with the keyword `let` or `var` and doesn't work if declared `const` keyword.

## Setting the `length` property to `0`

To overcome the above problem, You can use set the `length` property of the array to `0` like this,

```js
// number array
const numbersArr = [23, 45, 56, 78];

// empty contents in array
// by setting length property to 0
numbersArr.length = 0;

console.log(numbersArr); // []
```

See this example live in [JSBin](https://jsbin.com/tolizaqiqa/2/edit?js,console).

## Using the `splice()` array method

Another way to empty the contents in an array is using the `splice()` array method like this,

```js
// number array
const numbersArr = [23, 45, 56, 78];

// empty contents in array
// using the splice() array mehtod
numbersArr.splice(0, numbersArr.length);

console.log(numbersArr); // []
```

We have to pass the starting index as the first argument and the number of elements to delete from the starting index as the second argument, in our case `0` as the first argument and `length` of the array as the second argument.

See this example live in [JSBin](https://jsbin.com/foluvikeda/1/edit?js,console).

### Feel free to share if you found this useful 😃.

---
Warnings against using unofficial installers
Tags: wordpress, beginners, mysql, security
Published: 2020-11-21 23:48:50

I was trying to install Pterodactyl, a panel for managing servers for Minecraft, Discord bots, etc, easier. Looking back now, it was stupid of me to use a script to install it. Installing it manually only took me a couple hours anyways.

[parkervcp](https://github.com/parkervcp) and [his team](https://github.com/pterodactyl) have no official install script for Pterodactyl. Stupidly, I went in search of **unofficial** install scripts, without realizing that most of them would be deployed on a fresh machine. Can you see where this is going?

It wiped ***all of my SQL databases***. What did these databases contain you ask? Oh nothing, just about **10 domains worth of content including 2 forums and 6 WordPress installs**. Stupid, I know. Luckily, all my previous articles, I had decided to publish on this website as well! Dev.to to the rescue!

In the aftermath, I decided that from now on, my articles will be published *mainly* on dev.to, with links to these articles on my website, [onyxcode.net](https://onyxcode.net).

Bottom line, if the program doesn't have an installer, do it yourself. Don't go in search of unofficial methods. They could potentially contain malicious code, and you don't always know what deployment conditions they are meant for.

Thank you for coming to my TED talk.
Showing password with HTML5 and JavaScript
Tags: password, html, javascript, tutorial
Published: 2020-11-21 23:01:46

[[Clique aqui para ler em português]](https://medium.com/walternascimentobarroso-pt/exibindo-senha-com-javascript-3cfb2d011c7a)

When creating a login form, it is common to require the ‘little eye’ functionality, which when clicking is displayed the password and clicking again is hidden, therefore, today we will do this functionality.

## Code

First we will create the interface, we will do something simple, using only HTML.

```html
<h1>Show Password</h1>
<form name="form_main">
  <input type="password">
  <button type="button" id="togglePass">😣</button>
</form>
```

The main elements here are:

* **input** = You will receive the password value, and it will be displayed in the password format (***);
* **button** = Clicking will convert the password type to text type and vice versa;

```javascript
"use strict";
const input = document.querySelector("input");
const button = document.querySelector("#togglePass");
button.addEventListener('click', togglePass);

function togglePass() {
  if (input.type == "password") {
    input.type = "text";
    button.textContent = "🤩";
  } else {
    input.type = "password";
    button.textContent = "😣";
  }
}
```

In javascript we have, the `input` and the `button`, in the button a function called `togglePass` is added.

The `togglePass` function checks whether the `input` type is `password`, if it changes the type to `text` and if not, it changes to `password`.

ready as simple as that.

## Demo

See the complete project working below.
{% codepen https://codepen.io/WalterNascimento/pen/KKMgoPp %}

## Youtube

If you prefer to watch, I see the development on youtube (video in PT-BR).

{% youtube AWRGbdEwv1Q %}

***

## Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you! 😊😊
Solving LeetCode - Median of Two Sorted Arrays
Published: 2020-11-21 22:46:51

# Question

Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.

Example 1:
```
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
```
Example 2:
```
Input: nums1 = [1,2], nums2 = [3,4]
Output: 2.50000
Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
```
Example 3:
```
Input: nums1 = [0,0], nums2 = [0,0]
Output: 0.00000
```
Example 4:
```
Input: nums1 = [], nums2 = [1]
Output: 1.00000
```
Example 5:
```
Input: nums1 = [2], nums2 = []
Output: 2.00000
```

Constraints:

* nums1.length == m
* nums2.length == n
* 0 <= m <= 1000
* 0 <= n <= 1000
* 1 <= m + n <= 2000
* -106 <= nums1[i], nums2[i] <= 106

## Let's Go!

Solve by using [PREP](https://dev.to/phariale/prep-technique-for-algorithms-in-js-5b0g).
* **P** - Two parameters. Both are an array of integers _(nums1 & nums2)_.
* **R** - A number which represents the median of the combined arrays.
* **E** - Examples provided by question. (See Above)
* **P** - See Below

```javascript
var findMedianSortedArrays = function(nums1, nums2) {
    // Use Reduce method to combines nums1 & nums2 to single array named data
    
    // Sort array from smallest to largest number
    
    // Return the below
    // Conditional if even or odd length data
      // If odd grab middle idx of data
      // Else even grab middle 2 numbers and divide by 2
};

```

Translate into code...

```javascript
var findMedianSortedArrays = function(nums1, nums2) {
    // Use Reduce method to combines nums1 & nums2 to single array named data
    let data = nums1.reduce((result, num) => {
        result.push(num)
        return nums2
    }, nums2)
    
    // Sort array from smallest to largest number
    data.sort((a,b) => a - b)
    
    // Return the below
    // Conditional if even or odd length data
      // If odd grab middle idx of data
      // Else even grab middle 2 numbers and divide by 2
    if (data.length % 2 === 0) {
      return (data[data.length/2 - 1] + data[data.length/2]) / 2
    } else {
      return data[data.length / 2 - .5]
    }
};

```

### Conclusion

& Remember... Happy coding, friends! =)

#### Sources
* https://leetcode.com/problems/median-of-two-sorted-arrays/
Easy learning part 2
Tags: motivation
Published: 2020-11-21 22:04:20

Today I spent the entire day, trying to write the app that will generate MCQ’s from input text.

It shouldn’t have taken that long, and I’m not even halfway through.
And all because, being the tech junkie that I am, plus maybe just a tad bit hard headed.
I decided that this is a good opportunity to write a web server backend in go, which I learned about 2 days ago, and also learn tailwind.

This post is a bit of cheating. I don’t have the product that I promised to deliver in my previous post.
I am writing this one just to technically claim that I followed through and successfully succeeded in writing and putting a post online today. Since where I’m from, it will be 00:00 in 5 minutes.

However, I start writing the next post now with the purpose of posting it in the coming 2 hours.

Hopefully, I’ll manage to finish the app by then.

I do not regret being so stubborn to the point of not delivering what I said I will.

I put learning new things and persistence in the face of difficulty above all else.
Am I right or wrong in this attitude?

Time will tell.
Spring Security
Tags: spring, security, java
Published: 2020-11-21 22:02:05

There are many authentication mechanisms (basic, digest, form, X.509, etc), and there are many storage options for credentials and authority information (in-memory, database, LDAP, etc). Authorization depends on authentication and determines if you have the required Authority. The decision process is often based on roles (e.g. ADMIN, MEMBER, GUEST, etc).

There are three steps to set up and configure Spring Security in a web environment:

1. Setup the filter chain: The implementation is a chain of Spring configured filters (Spring Boot does it automatically)
2. Configure security (authorization) rules
3. Setup Web Authentication

In the next example, it is defined as specific authorization restrictions for URLs using mvcMatchers.

```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.formLogin().loginPage("/login").permitAll().and().exceptionHandling().accessDeniedPage("/denied").and()
				.authorizeRequests().mvcMatchers("/accounts/resources/**").permitAll().mvcMatchers("/accounts/edit*")
				.hasRole("EDITOR").mvcMatchers("/accounts/account*").hasAnyRole("VIEWER", "EDITOR")
				.mvcMatchers("/accounts/**").authenticated().and().logout().permitAll().logoutSuccessUrl("/");
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().passwordEncoder(new StandardPasswordEncoder()).withUser("viewerUser")
				.password("abc").roles("VIEWER").and().withUser("editorUser").password("abc").roles("EDITOR");
	}

}
```

As you can see, you can chain multiple restrictions (using the and() method). The first method sets up a form-based authentication. The second method uses a UserDetailsManagerConfigurer. You can use jdbcAuthentication() instead of inMemoryAuthentication().

Learn more at [Spring Security Reference](https://docs.spring.io/spring-security/site/docs/current/reference/html5/) and [Security Architecture with Spring](https://examples.javacodegeeks.com/security-architecture-with-spring/)
Javascript Regex Part 3 More Character Matching
Published: 2020-11-21 22:01:15

**Negated character set**

Negated character sets are a set of characters you do not want to match. To create a negated character set you place ^ after the opening bracket. Here is an example:

```
let mySample = "Hello"
let myRegex = /[^aeiou]/gi
let result  = mySample.match(myRegex)

console.log(result) // [ 'H', 'l', 'l' ]
```

**Match characters that occur 0 or more times**

To search for characters that occur 0 or more times you use an * after the word:

```
let happy = "yessssss"
let myRegex = /yes/
let myRegex2 = /yes*/
happy.match(myRegex) //'yes'
happy.match(myRegex2) // 'yessssss'

```

**Match characters that occur 1 or more times**

You can also match characters that occur 1 or more times using the + symbol after the word:

```
let happy = "aabc"
let myRegex = /a/
let myRegex2 = /a+/
happy.match(myRegex) //'a'
happy.match(myRegex2) //'aa'
```

**Lazy matching**

A lazy match finds the smallest part of the string that satisfies the regex pattern.

To use lazy matching put a ? after the characters you are searching for:

```
let happy = "basketball"
let myRegex = /b[a-k]l/ // not lazy matching or 'greedy matching'
let myRegex2 = /b[a-k]l?/ //lazy matching
happy.match(myRegex) //'bal'
happy.match(myRegex2) //'ba'
```
ReactJS - Tailwind CSS Starter
Tags: react, tailwindcss, javascript
Published: 2020-11-21 21:49:47

Do you like **tailwindcss** and **ReactJS**?

If the answer is yes, a few weeks ago I created a template for React (cra) that allows you to create a `create-react-app` project with **Tailwind CSS** already configured.

in order to avoid setting **tailwindcss** in every project you use.

## Setting Up

To use this template, you need to open your terminal or CMD in your preferred folder or path. Then, write the following command and press enter:

```sh
npx create-react-app myproject --template tailwindcss-starter
# or
yarn create react-app myproject --template tailwindcss-starter
```

This command will start generating a `create-react-app` project with all the basic dependencies for React and in turn, it will download each file and package that I have configured so that you can use Tailwind CSS.

## Project Structure

Once your project has been generated you will see the following structure of your project.

```sh
└─ projectfolder
  ├─ node_modules
  ├─ public
  ├─ src
  ├─ .gitignore
  ├─ .prettierrc
  ├─ package.json
  ├─ postcss.config.js
  ├─ README.md
  ├─ tailwind.config.js
  └─ tailwind.css
```

- `tailwind.config.js`: here you can edit your tailwindcss configuration, add more colors, animations, etc.

- `postcss.config.js`: if you need something related to postcss here you can set up.

- `.prettierrc`: here you can find a little configuration of prettier. This project has a prettier-plugin that help you regrouping all of the classes of tailwindcss in your JSX code.

- `tailwind.css`: entry CSS file of tailwindcss, here you can add your custom classes or create components with the `@apply` directive. 

## Available Scripts

With this template, you have available the basic scripts that create-react-app proved us, but I added three more scripts in our projects.

- The first script allows us to generate the fully CSS file of tailwindcss available in `src/styles.css`. This file contains all of the classes that tailwindcss provides us.
  ```sh
  npm run build-css:develop
  # or
  yarn build-css:develop
  ```

- The other script allows us to generate a purged CSS file of tailwindcss. This means that the output CSS file only will have the classes that we used in our project.
  ```sh
  npm run build-css:production
  # or
  yarn build-css:production
  ```

- The last one allows us to "format" our classes in our HTML or JSX code, this will regroup the tailwindcss classes in a certain order that you can find in `.prettierrc`file.
  ```sh
  npm run format
  # or
  yarn format
  ```


And this is my template, I hope you find helpful this project, any advice or request is welcome. You can find the repository [here](https://github.com/angelmtztrc/cra-template-tailwindcss-starter).


> Original post [here](https://angelcodes.hashnode.dev/reactjs-tailwind-css-starter?guid=9ba340b8-26e5-4e0c-a3dd-162f2623965f&deviceId=a4cbdef3-8873-42c7-b5d0-0a4c69096369).
Why do most websites end with .com?
Tags: computerscience, webdev, discuss
Published: 2020-11-21 21:44:03

Have you ever wondered why most websites end with a .com? what does it really mean? Did you know website domains ending with a .com cost a lot more than .org or a .in? But why? Interesting isn't it?
Well, read on.

The name com was first heard in the year 1985, its name is derived from the word commercial, indicating its original intended purpose for domains registered by commercial organizations. Later on, the domain opened for general purposes.

Although .com domains were initially intended to designate commercial entities, the domain has had no restrictions for eligible registrants since the mid-1990s. With the commercialization and popularization of the Internet, the domain was opened to the public and quickly became the most common top-level domain for websites, email, and networking. The popularity was mainly driven because the domains using .com flourished in the early 2000s, and the usage of .com more became a norm and a universally accepted extension to a website!

Now, a lot of Hosting platforms see the demand for a .com to be much higher over its counterparts edu, gov, mil, net, org, and int. and is clearly more expensive because:
1.Lesser expenditure of funds on PPC advertising. Organic traffic will be greater from a higher ranking premium domain name.

2.A premium domain name will enhance funding and partnership opportunities with established companies in your industry.

3.It is also somehow associated with security. A large portion of uninformed audiences thrive on familiarity and feel more secure.

So, probably with time, as people learned to use websites, they learned it along with the .com and hence could be more instinctive to type a .com against a domain name. And is today seen as a business opportunity!
PHP - Create a QueryBuilder object for the SQL language
Tags: php, mysql, tutorial, laravel
Published: 2020-11-21 21:38:47

*PHP version required 7.3*

#Building SQL Queries with Query Builder

Let's create the class that will build sql language.

```php
<?php

namespace DevCoder;

/**
 * Class QueryBuilder
 */
class QueryBuilder
{
    /**
     * @var array<string>
     */
    private $fields = [];

    /**
     * @var array<string>
     */
    private $conditions = [];

    /**
     * @var array<string>
     */
    private $from = [];

    public function __toString(): string
    {
        $where = $this->conditions === [] ? '' : ' WHERE ' . implode(' AND ', $this->conditions);
        return 'SELECT ' . implode(', ', $this->fields)
            . ' FROM ' . implode(', ', $this->from)
            . $where;
    }

    public function select(string ...$select): self
    {
        $this->fields = $select;
        return $this;
    }

    public function where(string ...$where): self
    {
        foreach ($where as $arg) {
            $this->conditions[] = $arg;
        }
        return $this;
    }

    public function from(string $table, ?string $alias = null): self
    {
        if ($alias === null) {
            $this->from[] = $table;
        } else {
            $this->from[] = "${table} AS ${alias}";
        }
        return $this;
    }
}

```
**How to use ?**
```php
$query = (new QueryBuilder())
->select('email', 'first_name', 'last_name')
->from('user');

$pdoStatement = $pdo->prepare($query);
$pdoStatement->execute();

$users = $pdoStatement->fetchAll(\PDO::FETCH_ASSOC);
```
```php
$query = (new QueryBuilder())
->select('u.email', 'u.first_name', 'u.last_name', 'u.active')
->from('user', 'u')
->where('u.email = :email', 'u.active = :bool');

$pdoStatement = $pdo->prepare($query);
$pdoStatement->execute([
    'email' => 'dev@devcoder.xyz', 
    'bool' => 1
    ]
);

$user = $pdoStatement->fetch(\PDO::FETCH_ASSOC);
```
Ideal for small project
Simple and easy!
[https://github.com/devcoder-xyz/php-query-builder](https://github.com/devcoder-xyz/php-query-builder)

**How can we improve this object?**
* add methods join, limit, offset, groupBy etc..
* Create insert, update and delete statement
Weekly Update #002
Tags: docker, azure
Published: 2020-11-21 20:54:40

---
description: Time sync in docker containers
---
I know Active Directory is fussy about clocks being in sync however not sure how todays issue happened. 

I run my docker compose file from Visual Studio and I get a weird error.

```
SecurityTokenNotYetValidException: IDX10222: Lifetime validation failed. The token is not yet valid. ValidFrom: 'System.DateTime', Current time: 'System.DateTime'.
```

I deleted my containers, open and close Visual Studio a few times, nothing helps. Eventually I think to find out what the time is on my container. It has yesterday's date. What has happened here? Surely recreating containers would have caused them to have todays date? I reboot and everything is fine again.

Turns out that it is a know issue, see https://thorsten-hans.com/docker-on-windows-fix-time-synchronization-issue I am using WSL2 and I have now changed back to using Hyper-V and the issue hasn't come back.

Earlier in the week I spotted my build step was failing.

```yaml
  - task: NuGetToolInstaller@0
```

Swapping to the next version of the step is all I needed to do to fix it.

```yaml
  - task: NuGetToolInstaller@1
```
My guess is that support was dropped for this earlier version or there is some other incompatability with .Net 5.