teleren/devto huggingface dataset:
PHPUnit: Returning values and throwing exceptions from the same mocked method
Tags: php, testing
Published: 2019-08-11 14:35:31

Recently I was writing a test case where an initial call to a method would return a value and a subsequent call would throw an exception. I assumed that it could be achieved by using a combination of `will`, `willReturn` and `willThrowException`.

```php
$mockFoo     = $this->createMock(Foo::class);
$mockFactory = $this->createMock(FooFactory::class);

$mockFactory
    ->expects($this->exactly(2))
    ->method('make')
    ->with('Foo', 'Bar')
    ->will($this->willReturn($mockFoo), $this->throwException(new BarException()));
```

PHPUnit only supports one parameter to `will` and as such the exception was never thrown. I was surprised to find that PHPUnit has no documented solution for this issue and I instead resorted to scouring StackOverflow. I found [this](https://stackoverflow.com/a/6286827) answer which put me on the right track.

Instead of creating the `InvokedCount` matcher and immediately passing it to `expects`, we can create it earlier and assign it to a variable. We can then replace our `will` method with `willReturnCallback`, using `$matcher` in the callback. `InvokedCount` provides the method `getInvocationCount` which allows us to track how many times the method `make` has been invoked. Using our callback, we can then handle each invocation separately.

```php
$mockFoo     = $this->createMock(Foo::class);
$mockFactory = $this->createMock(FooFactory::class);
$matcher     = $this->exactly(2);

$mockFactory
    ->expects($matcher)
    ->method('make')
    ->with('Foo', 'Bar')
    ->willReturnCallback(function () use ($matcher, $mockFoo) {
        if ($matcher->getInvocationCount() === 1) {
            return $mockFoo;
        }
    
        throw new BarException();
    });
```

It's worth noting that this solution is not a replacement for `willReturnOnConsecutiveCalls` and is only for use when your mocked method need to do more than return values.
Middleware Logging in Redux
Tags: redux, react, tutorial, explainlikeimfive
Published: 2019-08-11 10:46:53

Every dispatched action flows through middleware. Specific features before dispatched action reaches reducers can be opted-in.

## Redux Logger

This library logs actions in developer console, giving traceable stack of user actions. 

Middleware is applied in state initialization stage with enhancer `applyMiddlware()`
```
    import { applyMiddleware, createStore } from 'redux';
    const store = createStore( reducer,
    undefined, applyMiddleware(...)
    );
```
To use redux-logger, pass instance to this function
```
    import { applyMiddleware, createStore } from 'redux';
    import { createLogger } from 'redux-logger';
    
    const logger = createLogger();
    const store = createStore(reducer,
    	undefined, 
    	applyMiddleware(logger)
    );
```
Now, every action should be visible in developer console when dispatched.

Mind, that numerous middlewares can be passed in

    applyMiddleware(firstMiddleware, secondMiddleware, ...);

This way, the action will flow through each before it reaches the reducer stage. Hence, it's obvious, that you'd want to log the complete action, after it's been modified by every middleware. Place `redux-logger` as latter parameter passed to the middleware enhancer.
How do you split contenteditable text preserving html formatting? [solved]
Tags: javascript, webdev, help, discuss
Published: 2019-08-11 10:36:21

---
title: How do you split contenteditable text preserving html formatting? [solved]
published: true
description: How do you split contenteditable text preserving html formatting?
tags: javascript, webdev, help, discuss
---
I'm using contenteditable divs to represent paragraphs in my editor. I've implemented most of the usual editing features

Splitting paragraphs breaks when any HTML formatting is involved. 

For example, adding a space and hitting enter results in

`&`
`nbsp;`

Of course, '\&nbsp;' being a single character that represents a space.

## Solution (Update)

Okay I figured it out.

innerHTML and innerText aren't useful for DOM manipulation.

However, the selection and ranges API is great for this. `extractContents` automatically splits elements without breaking markup.

```
function splitNode(selection, root) {
  let range = selection.getRangeAt(0);
  let {firstChild, lastChild} = root;

  let previousRange = document.createRange();
  previousRange.setStart(firstChild, 0);
  previousRange.setEnd(range.startContainer, range.startOffset);

  let nextRange = document.createRange();
  nextRange.setStart(range.endContainer, range.endOffset);
  nextRange.setEnd(lastChild, lastChild.length);
  return {
    previous: previousRange,
    current: range,
    next: nextRange,
  };
}

let ranges = splitNode(document.getSelection(), contentEditableDiv);
let nextFragment = ranges.next.extractContents();
```
When did you start programming? Do you wish you started earlier?
Tags: discuss
Published: 2019-08-11 10:01:55

I started programming when I was 15 (I'm 17 now) and I'm quite happy about that I think. I'm happy partly because I've had the chance to explore the world of coding and tech so I can make a good choice about what I want to specialize in later.

Although I say this, I still feel there is so much more to learn and sometimes I wonder if starting out earlier would've helped. Although I should have enough time to learn all those things later in my life, I think starting out early would benefit me as you learn the most when you're young.

This got me wondering about at what age the developers in here started programming and when they wish they started programming.

Thanks for all the replies in advance!
Will Udemy produce too many React devs? 
Tags: codenewbie, react, javascript, education
Published: 2019-08-11 10:00:05

---
title: Will Udemy produce too many React devs? 
published: true
description: Will all these React courses produced by the superstars of Udemy produce an overabundance of React devs? 
tags: codenewbie, react, javascript, education
cover_image: https://thepracticaldev.s3.amazonaws.com/i/qnwghsmc085dmwdnwbsq.png
---

Normally I write in a semi-academic style with fancy headings, coherent paragraphs and lots of references. But today I’m doing something a little stream-of-conscious-y…

Part of my YouTube job is reviewing the latest and greatest from some of the more prominent Udemy instructors. One things I've noticed lately is that if they’re doing a course on a frontend framework/library, odds are it’s React.

Colt Steele has a recent course on React. 

Andrei Neagoie just dropped one. 

Also on this list of React course creators are Stephen Grider, Andrew Mead, Maximilian Schwarzmueller, and Brad Traversy (along with 100s of other instructors on Udemy.)

Like...What about Angular? It’s not like the jobs have dried up. Vue has never had much enterprise adoption but there are still jobs out there. But the only famous people Udemy-wise I’ve seen do a Vue course is Max & Grider. Max also has courses and Angular and Svelte. 

Thoughts on why this is? 

Will all these React courses produced by the superstars of Udemy produce an overabundance of React devs? 

P.S. Check me out on YouTube where I talk about all things web development! [YouTube.com/realtoughcandy](https://www.youtube.com/realtoughcandy)
Extremely minimal Windows dev setup 
Tags: dev, setup
Published: 2019-08-11 09:11:40

From time to time, my auntie asks me to go to her flat and look after the kitty  and usually I don't take my laptop. I want to be able to write some code using her laptop in the fastest way.

After experimenting with multiple set-ups like XAMPP or any programming language + a database, I found out that the fastest setup is drum roll....

NodeJS (Javascript) + Visual Studio Code. Plus a few clicks on Next buttons :)

Seriously !

The installation of Node and VS Code took under 10 minutes and a short restart for updating the path and I was ready to go. At least for console applications, but this setup should be ok for web apps. Also, a database like PostgreSQL or MySql can be installed for persistence.

That's all for today folks !
Cosmin
Something About Grok
Tags: elasticsearch, backend, devops, dataanalysis
Published: 2019-08-11 08:15:11



Here Grok, a filter plugin used in ELK stack. It converts unstructured logs to structured ones.

Grok is built upon regular expression. The syntax is `%{SYNTAX:SEMANTIC}`. For example:

A log line
```
10.0.1.13 GET /home HTTP/2.0 200 13969
```

A filter defined in logstash configure file as below
```
filter {
  grok {
    match => {
      "message" => '%{IPORHOST:ip} \"%{WORD:method} %{DATA:request} HTTP/%{NUMBER:httpversion}" %{NUMBER:response:int} (?:-|%{NUMBER:bytes:int})'
    }
  }
}
```

The log line passes through the filter, it produces the result

```
ip: 10.0.1.13
method: GET
request: /home
response: 200
bytes: 13969

```

With structured data, you can search by specific field while using Elasticsearch.

##Grok Debugger

If you are not so sure the pattern would work on your log or not, here are some grok debugger to help you verify the patterns.
- [Grok Debugger](https://grokdebug.herokuapp.com)
- [Test Grok Patterns](https://grokconstructor.appspot.com/do/match)

Make log processing easier. :D


##See also
[5 Logstash Filter Plugins](https://logz.io/blog/5-logstash-filter-plugins)
[Oniguruma](https://github.com/kkos/oniguruma)

----------------

>The Jargon File, which describes itself as a "Hacker's Dictionary" and has been published under that name three times, puts grok in a programming context:
>
>When you claim to "grok" some knowledge or technique, you are asserting that you have not merely learned it in a detached instrumental way but that it has become part of you, part of your identity. For example, to say that you "know" Lisp is simply to assert that you can code in it if necessary — but to say you "grok" LISP is to claim that you have deeply entered the world-view and spirit of the language, with the implication that it has transformed your view of programming. Contrast zen, which is a similar supernatural understanding experienced as a single brief flash.
>--Wikipedia
Laravel Interview Questions
Tags: laravel, php, interview, phpframework
Published: 2019-08-11 08:07:14

##Top 50 Laravel Interview Questions for freshers and experienced Laravel Developer.

###Q:-1 What is Laravel?
Laravel is a free, open-source PHP web framework, created by Taylor Otwell and intended for the development of web applications following the model–view–controller (MVC) architectural pattern.

###Q:-2 How to Install Laravel via Composer?
*composer create-project --prefer-dist laravel/laravel myproject*

//Composer Command To Install Laravel:
*composer create-project --prefer-dist laravel/laravel ProjectName "VersionNo.*"*

//Example: Install Laravel 5.4 using Composer
*composer create-project --prefer-dist laravel/laravel blog "5.4.*"*

###Q:-3 List benefits of using Laravel over other PHP frameworks?
Reasons why Laravel is the best PHP framework:

=> Artisan - A Command-Line Interface
=> Migrations & Seeding
=> Blade Template Engine
=> Middleware - HTTP middleware provide a convenient mechanism for filtering HTTP => requests entering your application.
=> Eloquent ORM + Built-in Database Query Builder
=> Routing (RESTful routing)
=> Inbuilt packages - Authentication, Cashier, Scheduler, SSH, Socialite
=> Security
=> Unit Testing - Built-in unit testing and simply readable impressive syntax
=> Caching - Laravel provides an expressive, unified API for various caching backends

###Q:-4 What is ORM?
ORM: Object-relational Mapping (ORM) is a programming technique that helps in converting data between incompatible type systems into object-oriented programming languages.
#####Eloquent ORM is being used by Laravel.

###Q:-5 Which Template Engine used by Laravel?
#####Blade is the simple, yet powerful templating engine provided with Laravel.

read more about [Laravel Interview Questions and Answers](https://www.fullstacktutorials.com/interviews/top-50-laravel-interview-questions-and-answers-for-experienced-13.html)
Tricky Javascript Stuff 01
Published: 2019-08-11 06:59:41

---
title: Tricky Javascript Stuff 01
published: true
description: 
tags: 
---
### 1. Javascript has two types of value for empty values - null and undefined. What are the differences for these two?

Undefined -

When the value of a variable is not defined, such that when we create a variable without assigning value, the variable is defined as "undefined". When we check the type with typeOf, the type is also undefined.

Some ways to get undefined:
1. declare a variable without giving it value
2. a function returns an empty value
3. not passing any value to a function's parameter

Javascript has a global variable called undefined and its value and type are shown as undefined.

Null -

Null indicates no value. It is a primitive type and we can assign null to variables. When we check typeOf null it returns as object, however, it's not really an object because we can not add properties to it.

### 2. == vs === || is the more the better?

The double == comparison operator will not check types, only checks values. It will return true for 8 == "8", even though 8 is a number and "8" is a string.

The tripe === operator will check both type and values. Therefore, 8 === "8" will return false since their types are different.

NaN is a not a number type, along with null and undefined, these three are unique types, and will not equal to other types. 

Nan does not even equal to itself. NaN == Nan or NaN === NaN both will return false.

Source: https://www.thatjsdude.com/interview/js2.html#nullVsUndefined
I’m now a coding bootcamp graduate
Tags: blogging, codingbootcamp
Published: 2019-08-11 04:20:22

---
title: I’m now a coding bootcamp graduate
published: true
description: I graduated from Codeable, a Peruvian coding bootcamp, and this is how I feel
tags: blogging, coding bootcamp
---
I graduated from Codeable. I now have the title of Full-Stack Software Developer. I still can’t believe it. *Me*, an 18-year-old girl with many passions, a mind full of dreams, and a heart full of hope, a software developer? After six months of nonstop learning, practicing and doing my best, I am **now** in a place I’d have never considered myself to be in seven months ago. 

To give you all context: I graduated high school last year, my plans were kinda different, I was a totally different person. However, now I’m someone who just had one of the best experiences ever, a new Valeria, someone more confident about her capacity, someone who isn’t afraid of speaking her mind without doubting everything that would come out of her mouth, someone who has new friends that are going to stick around no matter what, someone... different... for the better. 

I couldn’t have asked for anything else. Codeable, definitely one of the best coding bootcamps in the whole wide world, gave me so many opportunities and I’ll be forever thankful. I want to thank my instructors, the whole staff, and my teammates, or better said, my awesome friends. All of this wouldn’t have been possible without the constant support I had throughout the whole bootcamp. These amazing human beings have been there for me whenever I needed it, just like I tried to be there for them as well. They all taught me so much and made me feel so comfortable,,,,, I couldn’t be any more grateful. I just want them to know that they can always count on me, always. I’m literally one text away. 

And to finish this (I’m kinda getting emotional), to all the people out there who want to change their lives, go for it. You’re not really living if you don’t take any risks. Choose what you truly think is best for you. You will know what that is, you’ll feel it. Don’t second guess any decision. You won’t regret it. In my case, after risking some things, I gained new, interesting knowledge, incredible friends and an experience I won’t be able to forget. Just go for it, it’s worth it :D 

Oh! And having finished this bootcamp doesn’t mean I’ll stop here, this is just the beginning. I’m excited to see what the future holds for me, for all of us.
Best resources for a beginner developer?
Tags: discuss, dev
Published: 2019-08-11 06:19:02

---
title: Best resources for a beginner developer?
published: true
description: What are the best resources for a beginner developer?
tags: discuss, dev
---

I’m often asked: “What is the best resource to learn programming for a beginner?”

Some of the places I recommend are:
- [FreeCodeCamp](https://freecodecamp.org)
- Youtube videos - by searching a certain topic like: JavaScript, Python, etc... (Brad Traversy has a lot of very good Crash Courses on Youtube)
- [Udemy](https://udemy.com) - same as above - search for a certain topic and you can find tons of nice courses

I believe that one of the most important things while learning programming is to **practice** as much as possible! Build, build, build!

[Here](https://github.com/florinpop17/app-ideas) is a list of app-ideas that I’ve put together if you need a little guidance on what to build to practice while learning! ☺️

What other resource would you recommend for beginners?
Passing Arguments in Routes (CakePHP)
Tags: cakephp
Published: 2019-08-11 04:57:07

<b>Question:</b> How to pass arguments to a url in CakePHP

<b>Solution: </b>

In <b>app/Config/routes.phg</b>

Router::connect('/:arg', array('controller' => 'homes', 'action' => 'index', 'pass' => ['arg']));

Inside <b>Homes/index()</b>

index()
{
  ...
  $passedOne = $this -> request -> params["arg"];
  ...

}


Hope it will be of use to someone. :D
Python and timezones
Tags: python, timezone
Published: 2019-08-11 04:23:53

---
title: Python and timezones
published: true
description: 
tags: python,timezone
---

I recently needed to see what time it was in another timezone. Again this is a good task for Python (everything is really).

There is a great package named pendulum that is made exactly for this.

See here: https://pendulum.eustace.io/

So if I need to know what time it is in Japan...

```python
import pendulum
now_in_japan = pendulum.now("Japan")
now_in_japan
```

That is easy to read and showed me exactly what I wanted.

Also if you want to know what timezones your system knows about look in /usr/share/zoneinfo. Not sure about windows :(
FlatGA Email Reports
Published: 2019-08-12 13:33:17

---
title: FlatGA Email Reports
published: true
tags: 
canonical_url: https://kambanthemaker.com//posts/flatga-email-reports-2/
---

I am pleased to introduce email report feature for your website analytics, now you can receive the same beautiful FlatGA interface into your email as an embedded image. Take a look at a [sample report here](https://flatga.io/img/gmail.png). The email can also include top pages and referrers data as a CSV file for easier reference.

**Features**

- Daily or weekly email report
- Referrers and top pages as attachments
- Embedded image to save you from one additional click
- The pageview/user chart will have previous days included for easier comparison. i.e if you have chosen weekly report, the series will include last 2 weeks data while all other statictics will be for only one week.

**Cost**

It has 15 days trial period without requiring any credit card. Its $12 per year for upto 5 websites. That's just $1 per month. After the trial period, get your [gumroad.com](https://gum.co/zKiDs) license key and enter it on your settings page.

**How to activate this feature?**

Login at [flatga.io](https://flatga.io), click "Subscribe via Email!" button next to duration. You can now add a new report from this page!

Never miss to see your website growth and see who are your influencers!

Feel free to contact me on [Twitter](https://twitter.com/barsareillusion) for any questions!
Missing features are not "bugs"
Tags: opinion, debugging, communication
Published: 2019-08-11 00:05:57

{% twitter 1123105667030704128 %}

"Debugging" is a frequently misused term in the development ecosystem nowadays. It began as an actual verb when Grace Hopper [literally had to remove a moth from a computer](https://en.wikipedia.org/wiki/Debugging#Origin_of_the_term) to fix it. But now people use it to describe anything from unexpected errors to issues with (technically error-free) code.

Don't get me wrong, "buggy" code exists in the wild. Race conditions, unsafe error handling, lack of cross-browser support, the list goes on. But it's important to differentiate between implementation issues like this and incorrect assumptions based on an incomplete feature spec. Calling good code "buggy" can make the person who wrote it feel like they did a bad job.

It's difficult to gauge the level of granularity appropriate for a spec though - skirting the line between over-information and over-assumption. The former isn't practical, but the latter requires the developer to put on their product hat and make decisions about how things should work. If that developer makes a wrong assumption, that's okay! It's not buggy code, it just means their interpretation of something didn't _align_ with someone else's.

So next time you're doing this sort of "debugging", try referring to it as "recalibrating" - the developer will appreciate it! 😇
Forgit me nots
Published: 2020-12-30 14:57:35

---
title: Forgit me nots
published: true
date: 2019-08-11 00:00:00 UTC
tags: 
canonical_url: https://blog.koenvangilst.nl/for-git-me-nots/
---

## Squashing commits on Windows

I know there’s a better way to do this (using rebase) but I like this way since it gives me more control.

```
git merge-base master yourBranch

# note commit hash

git reset --soft # enter commit hash

# all changes can now be committed again
```

It’s easier on \*nix using the following oneliner:

```
git reset $(git merge-base master $(git rev-parse --abbrev-ref HEAD))
```

## Rebasing without pulling master

Rebase using the remote master to make sure you’re really up to date. Useful when updating merge requests (on GitLab).

```
git pull --rebase origin master
```

## Copy file from master to current branch

```
git checkout master -- yarn.lock
```

## Useful aliases

### Add all and commit

```
ac=!git add . && git commit
```

### Pretty log

```
ls = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
```

### Update last commit with current changes

```
amen = !git add --all && git commit --amend
```

### Undo last commit

```
git reset --soft HEAD^
```

Or add as an alias:

```
git config --global alias.undo 'reset --soft HEAD^'
```

## Oh no, I deleted all my work!?

Use the following command:

```
git reflog
```

and `cherry-pick` any commits you think could still have all your work.

## If .gitignore is not working

Do:

```
git rm -r --cached .
```

And after that:

```
git add --all
```

## After Rebasing

Instead of using -f or —force developers should use

```
git push --force-with-lease
```

Why? Because it checks the remote branch for changes which is absolutely a good idea. Let’s imagine that James and Lisa are working on the same feature branch and Lisa has pushed a commit. James now rebases his local branch and is rejected when trying to push. Of course James thinks this is due to rebase and uses —force and would rewrite all Lisa’s changes. If James had used —force-with-lease he would have received a warning that there are commits done by someone else. I don’t see why anyone would use —force instead of —force-with-lease when pushing after a rebase.

Source: [https://stackoverflow.com/questions/8939977/git-push-rejected-after-feature-branch-rebase](https://stackoverflow.com/questions/8939977/git-push-rejected-after-feature-branch-rebase)