teleren/devto huggingface dataset:
Have a Handy JS Snippet You Want to Share?
Tags: javascript, showdev
Published: 2018-01-23 01:07:14

---
title: Have a Handy JS Snippet You Want to Share?
published: true
description: Quick ES5/ES6 snippets for doing awesome things in Javascript.
tags: javascript, showdev
canonical_url: https://www.iamdeveloper.com/posts/handy-js-snippets-352f/
cover_image: https://c2.staticflickr.com/8/7282/8995095069_9e88b3bba5_b.jpg
---

So it's pretty simple. I'm looking for **one or two lines of JavaScript** that do something useful.

I'll get the ball rolling and start with some examples:

* Shallow array clone via Array spread.
```javascript
const originalArray = [1, 2, 3];
const shallowArrayClone = [...originalArray];

```

* Shallow array clone via `Array.protoype.slice`.

```javascript
const originalArray = [1, 2, 3];
const shallowArrayClone = originalArray.slice();

```

{% twitter 908547800442404864 %}

* Shallow clone of an object via object spread.
```javascript
const originalObject = { a:1, b: 2, c: 3 };
const shallowObjectClone = {...originalObject};

```

* Shallow clone of an object via object spread with one property overridden.
```javascript
const originalObject = { a:1, b: 2, c: 3 };
const shallowObjectClone = {...originalObject, c: 45 };

```

* Get unique values of an array using `Set`
```javascript
const arrayWithDuplicateValues = [1, 2, 3, 3, 1, 5];
const uniqueArray = Array.from(new Set(arrayWithDuplicateValues);
```

or

```javascript
const arrayWithDuplicateValues = [1, 2, 3, 3, 1, 5];
const uniqueArray = [...new Set(arrayWithDuplicateValues)];
```

* See if two arrays have the same values (unordered and for primitive values).

```javascript
const a = [1, 2, 3];
const b = [2, 3, 4];

const uniques = new Set(a.concat(b));
const haveSameValues = uniques.length === a.length // or uniques.length === b.length;
```

* Flatten an array with the ES spread operator and Array.prototype.concat. Great tip care of Jonathan Z. White.

{% twitter 985726458466263042 %} 

```javascript
const arrayToFlatten = [ [1,2,3], [4,5,6], [7,8,9] ];
const flattenedArray = [].concat(...arrayToFlatten);
```

2020 Update for the above is

```javascript
[ [1,2,3], [4,5,6], [7,8,9] ].flatMap(x=>x)
```

And go!

Cover image care of Flickr user [Wayne Grivell](https://www.flickr.com/photos/56462773@N07/8995095069/in/photolist-eGSdo2-eVj8Xm-F7SDKj-gyziYJ-5GmieA-aQjZ5Z-qB3MDY-gG1f-4CPscx-bdrdAv-Mcpb8-Ds5Ck5-UPFRjE-cooZaE-7JL9Ce-6hB26p-5JFmTS-aDC2mi-4RCrCE-8qaRq-adbMyX-8pCVMh-bnJfyw-sXQZ7-fnCVbL-4RCroh-dVzSH6-fckNay-pA6MdP-6VHf97-662aRZ-aiJwYD-9Liq36-pfXnJ2-81t4TV-fnoErz-76pUCy-aDFSfu-8GBKvz-dBM5-e4tTWW-9kHH6Q-r6hZzK-95uyfv-rdHr-qBJTsu-fc3tgQ-cwgbMh-7ZQGwo-UA7SdP).
When Writing a Reason Library with JS Included
Tags: reason, javascript
Published: 2018-01-22 22:41:53

---
title: When Writing a Reason Library with JS Included
published: true
description: A tip on what to do when writing a Reason library that imports JS code with relative paths.
tags: Reason, Javascript
---

I found myself writing some package code in Reason today (specifically, a localforage wrapper). And for various reasons that I won't dip into here, I wanted to vendor some JS code, including the Javascript file in the project, and linking to it with a relative path `./foo.js` from my Reason code.

Here's the problem. Bucklescript (the Javascript backend compiler) strips out unnecessary code when it can, so my library wrapping code (which was just a few `external` declarations) got stripped completely, and the `import` statement got moved directly into the file that was calling the wrapper library.

This a nice optimization, and works well when the Javascript being wrapped lives inside of `node_modules` and can be reached from any file in the project without changing the import path. But when using relative imports, it doesn't work out so well.

The Reason Discord channel informed me that if the library includes an `.rei` file, or a [Reason interface file](https://reasonml.github.io/docs/en/module.html#every-rei-file-is-a-signature), the wrapping code won't be compiled away, and the relative import will stay in the file where it was defined, instead of getting moved to the call site.

This *should* enable Reason library authors to include raw Javascript that's linked using relative paths in their Reason projects.

There's another method, too, suggested in the Discord channel:

Just copy all of the Javascript you want to include, and paste it into a `[%%bs.raw ]` block at the top level of some Reason file. That will include all of the JS directly into the compiled output of that file, and the author won't need to worry about relative imports at all after that.
Can you guess what the most popular search term on dev.to is so far this year?
Tags: discuss
Published: 2018-01-22 22:15:58

---
title: Can you guess what the most popular search term on dev.to is so far this year?
published: true
description: Please only make one guess per comment.
tags: discuss
---

Please only make one guess per comment. Once I reply to you with yes or no, you can guess more. I'll ignore comments that don't follow that rule.

Let's see who guesses it. 😊

Edit: We have a winner:

# 🎉 LARAVEL 🎉
Simple Number-Theoretic Insights with Python
Tags: mathematics, python, modulo, cryptology
Published: 2018-01-22 21:39:58

---
title: Simple Number-Theoretic Insights with Python
published: true
description: A small tool for quickly looking for Number-Theoretic patterns
tags: Mathematics,Python,Modulo,Cryptology
---

Sometimes I learn about a new operator, or equivalence class, or some other such function from `ZxZ` to `Z`.  Often looking at a grid of the numbers `0 - 9` on `x` and `y` axes illuminates interesting properties of such functionals.  Here I will give some code with which to do just that.

Before I continue, here's a picture of `I/O` from the code I will be writing in this blog post / article / thing.  I am including this at the start so that anyone who reads this knows what the goal of the code is to begin with.

![I/O Examples](https://thepracticaldev.s3.amazonaws.com/i/taae353uijgo5es5faia.png)

First let's define a few functionals, or functions, or operations, or whatever.  This way we can quickly see the utility of our `number_table` code once we get to that.

Here are mine, but I encourage you to write your own.  Note that I am coding in `Python3`.  The code is simple and I think could be fairly easily ported to your language of choice.

```PYTHON
# Euclid's Algorithm for Greatest Common Denominator (GCD):
# See https://en.wikipedia.org/wiki/Euclidean_algorithm for more info
euclid = lambda a, b: a if b == 0 else euclid(b, a % b)

# Two numbers are called "relatively prime" if their gcd is 1
relatively_prime = lambda a, b: int(euclid(a,b) == 1)

modulo = lambda a, b: a % b

and_ab = lambda a, b: a & b

```

Ok, now that we've got a couple cool little functions to investigate out of the way, let's get to the meat of making number grids.  I like to colorize my number-grids by number, so I made a little function for coloring numbers in Python.

```PYTHON
number_color = lambda n: "\033[1;3" + str(n) + ";40m " + str(n)
```

It doesn't really do anything for numbers greater than 8, but that's ok because if this bothers you then you can find a clever way to fix it.  (This does not bother me.)  Also, if you're interested in numbers bigger than 9 you'll have to modify my code a bit anyway, because I don't currently take that into account in the spacing of my table.

Now, here's my `number_table` code:

```PYTHON
def number_table(method):
    # We assume method is defined
    print("    " + " ".join([number_color(n) for n in range(1,10)]))
    print("     _________________________")
    for a in range(1, 10):
        line = number_color(a) + ": "
        for b in range(1, 10):
            r = method(a, b)
            line += number_color(r) + " "
        print(line)

```

... And here is some more `I/O`:

![Primality](https://thepracticaldev.s3.amazonaws.com/i/ojifpvx66jvjkaa168v1.png)

Hope this proves useful!
Python GUI Examples
Published: 2018-01-22 18:36:22

---
title: Python GUI Examples
published: true
description: 
---

1 Create your first GUI application
2 Create a label widget
2.1 Set label font size
2.2 Setting window size
3 Adding a button widget
3.1 Change button foreground and background colors
3.2 Handle button click event
4 Get input using Entry class (Tkinter textbox)
4.1 Set focus to entry widget
4.2 Disable entry widget
5 Add a combobox widget
6 Add a Checkbutton widget (Tkinter checkbox)
6.1 Set check state of a Checkbutton
7 Add radio buttons widgets
7.1 Get radio button value (selected radio button)
8 Add a ScrolledText widget (Tkinter textarea)
8.1 Set scrolledtext content
8.2 Delete/Clear scrolledtext content
9 Create a MessageBox
9.1 Show warning and error messages
9.2 Show askquestion dialogs
10 Add a SpinBox (numbers widget)
10.1 Set default value for Spinbox
11 Add a Progressbar widget
11.1 Change Progressbar color
12 Add a filedialog (file & directory chooser)
12.1 Specify file types (filter file extensions)
13 Add a Menu bar
14 Add a Notebook widget (tab control)
14.1 Add widgets to Notebooks
15 Add spacing for widgets (padding)

https://likegeeks.com/python-gui-examples-tkinter-tutorial/
Качество кода: 'взбиваемость' (churn) и сложность (complexity). Как отслеживать легаси.
Tags: php, testing, webdev
Published: 2018-02-19 20:39:15

---
title: "Качество кода: 'взбиваемость' (churn) и сложность (complexity). Как отслеживать легаси."
published: true
tags: php, testing, webdev
canonical_url: http://phpprofi.ru/blogs/post/95
---

![](https://matthiasnoback.nl/assets/2018/01/churn.png)

## Cложность кода (code complexity)

Сложность часто измеряется путем вычисления [цикломатической сложности](https://ru.wikipedia.org/wiki/%D0%A6%D0%B8%D0%BA%D0%BB%D0%BE%D0%BC%D0%B0%D1%82%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%B0%D1%8F_%D1%81%D0%BB%D0%BE%D0%B6%D0%BD%D0%BE%D1%81%D1%82%D1%8C) на единицу кода. Показатель можно рассчитать, принимая все ветви кода во внимание.

Сложность кода является показателем для нескольких вещей:

- <u>На сколько трудно понять кусок кода</u>. Большое значение показателя говорит о многочисленном ветвлении в коде. При чтении кода, программист должен отслеживать все эти ветки, чтобы понять все различные пути, в которые может "зайти" приложение при исполнении.
- <u>На сколько трудно протестировать этот кусок кода</u>. Большое значение показателя указывает на множество ветвей кода, и для того, чтобы полностью протестировать этот кусок кода, все эти ветви должны быть покрыты отдельно.

----
Читать далее: http://phpprofi.ru/blogs/post/95

----
En: https://matthiasnoback.nl/2018/01/churn-legacy-code/
Here are my 5 Blog ideas for the 'Blog More' challenge on CNC2018.
Tags: discuss, cnc2018, codenewbie
Published: 2018-01-22 14:28:41

---
title: Here are my 5 Blog ideas for the 'Blog More' challenge on CNC2018.
published: true
tags: discuss #CNC2018 #CodeNewBies
---
What will be the best choice for my first challenge?

1. Adding Role based permissions using policies in Laravel.
2. Deploying Laravel to a Digital ocean server.
3. The development tools I make use of.
4. Writing unit tests in Laravel.
5. An introduction to arrow functions.
The 7 Most Popular DEV Posts from the Past Week
Tags: top7
Published: 2018-01-22 13:44:17

---
title: The 7 Most Popular DEV Posts from the Past Week
published: true
description: A round up of the most-read and most-loved contributions from the community this past week.
tags: icymi
cover_image: https://thepracticaldev.s3.amazonaws.com/i/xsr1z6iqv0pd7p3s6ns3.png
---

#1. Really.Big.Design.Error

In case you weren't tuned in, Hawaii residents recently received an emergency alert that stated "BALLISTIC MISSLE THREAT INBOUND TO HAWAII. SEAK IMMEDIATE SHELTER. THIS IS NOT A DRILL." It was, in fact, a drill and the alert was a big big mistake. We learned later that the mistake was made because of an obvious design flaw that this post dives into.

{% link https://dev.to/ben/the-hawaii-missile-alert-was-the-software-developers-fault-2bid %}

#2. Beyond January Blues

If you have any nagging doubts about your jobs, ask yourself if any of thse scenarios might be playing a role in your workplace happiness. 

{% link https://dev.to/ky1e_s/when-is-it-time-to-leave-26l7 %}

#3. Kubernetes, in action.

Daniel shares his observations with how Kubernetes behaves with load balancing, self healing of services and auto scaling. 

{% link https://dev.to/danielkun/kubernetes-its-alive-2ndc %}

#4. Customize Everything

Nitya gives us a thirty-second run down of Flutter, an open source SDK from Google. 

{% link https://dev.to/nitya/flutter-in-30-seconds-1nk1 %}

#5. 800ms to 500ms

Inada shares how they used import time profiling to optimize application startup time, and how that led to a few PRs.

{% link https://dev.to/methane/how-to-speed-up-python-application-startup-time-nkf %}

#6. Making Spotify Less Boring

Eric got tired of listening to the same suggested songs and playlists on Spotify, so he dove into their API to make something better for himself. 

{% link https://dev.to/ericbonfadini/finding-my-new-favorite-song-on-spotify-4lgc %}

#7. You Aren't Gonna Need It

Tips on how to practice YAGNI, a principle of eXtreme programming -- a programmer should not add functionality until deemed necessary.

{% link https://dev.to/gonedark/practicing-yagni-3n1d %}

_That's it for our weekly wrap up! Keep an eye on dev.to this week for daily content and discussions...and if you miss anything, we'll be sure to recap it next Monday!_
Gerrit notifications: How to tame them?
Tags: discuss, gerrit
Published: 2018-01-22 13:24:11

---
title: "Gerrit notifications: How to tame them?"
published: true
description: As a developer, I would like to have proper notification system in Gerrit, so that I can follow the updates on relevant code review.
tags: discuss, gerrit
---

We are currently required to use Gerrit for our code reviews. While in general I am okay with the "one-review-per-commit" mechanism and I actually like how the review is done.

On the other hand, **the user experience provided by Gerrit web UI is just terrible**. For example you cannot even sort the changes by specific columns in table, which does not have even/odd lines in different colors (yes, I need to use my pen to track the information on one line on my 24" screen).

But the main productivity killer for us is the notification system. **Only push-like notifications are sent via email**, and they cannot be fine tuned (well, you can switch between plain-text and HTML or "all comments" and "comments left by others"). Therefore, you get a lot of SPAM which you need to manually go through.  And it is not even aggregated like in other tools (e.g. BitBucket). While you can write scripts'n'filters in your favorite e-mail client, Outlook, for instance, is not my favorite client to tweak.

Therefore, I would really like to know, **are there any alternatives to get meaningful push-like notifications**?
Method Name As Documentation
Tags: ruby, testing, programming, coding
Published: 2018-01-22 12:56:18

---
title: Method Name As Documentation
published: true
description: 
tags: ruby, testing, programming, coding
---
Hey, Ruby coders!

Do you recognize this idiom?

```ruby
Object.const_get(class_name)
```

Or this one?


```ruby
Object.const_get(class_name).new(*args)
```

When I wanted to do these two things in my RubyTest project, I had to Google to find out how.

Now if I put this code into my project, will I recognize these idioms later on?  Next month?  Next year?

I could add comments to explain, but a comment can get stale (not keep up with code changes), or get separated from its code, or even get deleted.

You can help your downstream code enhancer/maintainer by pushing an unusual idiom into a well-named method.

(Hint:  If you're not sure who is the downstream enhancer/maintainer, it's you!)

Thus, I created this:


```ruby
class ObjectHelper

  def self.get_class_for_class_name(class_name)
    Object::const_get(class_name)
  end

  def self.instantiate_class_for_class_name(class_name, *args)
    self.get_class_for_class_name(class_name).new(*args)
  end

end
```

PS:  My GitHub project is about test automation in Ruby.  It has a <a href="https://github.com/BurdetteLamar/RubyTest/blob/master/examples/github/TesterTour.md#tester-tour">Tester Tour</a> of the demo testing for a web UI and for a REST API.

Cross-posted from my <a href="https://burdettelamar.wordpress.com/">blog</a>.
Should blockers be part of the Definition of Done?
Tags: discuss
Published: 2018-01-22 12:19:53

---
title: Should blockers be part of the Definition of Done?
published: true
description: 
tags: discuss
---

In Scrum, there is something called the Definition of Done. It's basically a set of conditions which is used to objectively determine is a user story is done (in a sense that is understood by all parties).

Let's say that I've implemented a story, but upon testing the QA team finds one or more bugs that are critical (i.e. blockers).

Obviously that blockers will have to be fixed ASAP.
But can/should you consider that story done?
More specifically, <b>should blockers be part of the definiton of done?</b>

Also, what if it's not a blocker (just a P2 or lower)?

*All answers are welcome, but I'd especially appreciate those coming from people who actually have experience with Scrum.*

Thanks.
Using Next.js With Styled Components
Tags: javascript, react, next, styledcomponents
Published: 2018-02-01 09:59:33

---
title: "Using Next.js With Styled Components"
published: true
tags: javascript, react, next, styled-components
canonical_url: https://bilalbudhani.com/using-next-js-with-styled-components/
---

I have been fiddling around with [Next.js](https://github.com/zeit/next.js/) library for the past couple of months and it has been really fun so far.

[Styled-Components](https://github.com/styled-components/styled-components) is another great library I've started using in my production applications which has improved my development cycle.

Let's talk business now, Next.js is server-rendered library we will need to utilize Styled-Components [server side rendering](https://www.styled-components.com/docs/advanced#server-side-rendering) functions to get them working together.

Add styled-components package in your Next.js project:

```
yarn add styled-components
```

Now in the `pages` folder create a new file called `_document.js` and paste the following code snippet in it.

```
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'

export default class MyCustomDocument extends Document {
  static getInitialProps ({ renderPage }) {
    const sheet = new ServerStyleSheet()
    const page = renderPage(App => props => sheet.collectStyles(<App {...props} />))
    const styleTags = sheet.getStyleElement()
    return { ...page, styleTags } // return styles collected
  }

  render () {
    return (
      <html>
        <Head>
          <title>My Page Title</title>
          {this.props.styleTags}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}
```

Above code collects all the styles defined using styled-components in the application and return them to be populated as `props` before the page is rendered. Now inside `render` function the `{this.props.styleTags}` injects those collected styles in the `head` part of the page. Makes sense?

Moreover, If there is a need to apply global styles then import another function called `injectGlobal` and provide your styles before defining your custom document component.

```
import { ServerStyleSheet, injectGlobal } from "styled-components";

injectGlobal`
  html {
    font-size: 10px;
  }
  body {
    font-family: "Merriweather", serif;
    font-size: 1.6em;
    line-height: 1.6;
  }
`;

export default class MyCustomDocument extends Document {
//....
```

That's it! I'm finding Next.js + Styled Component combination very productive and flexible. You can let me know your thoughts on this combo on twitter.

_P.S: originally posted on personal blog: https://bilalbudhani.com/using-next-js-with-styled-components/_
How to put Google Invisible reCaptcha on your website
Tags: invisiblerecaptcha, webdev, php, security
Published: 2018-01-22 11:38:42

---
title: How to put Google Invisible reCaptcha on your website
published: true
description: A quick guide to put Google Invisible reCAPTCHA on your WordPress website
tags: InvisiblereCAPTCHA, webdev, php, security
---
<img src="https://product.hubspot.com/hubfs/recaptcha-preview.png?t=1516140244757">

Hackers are targeting WordPress for a long time just because of its popularity. Securing our WordPress website should be our top priority just like speed and SEO optimization

Today I am going to tell you how to configure Google Invisible reCAPTCHA plugin to control spam and fake signups as well as securing your WordPress site. 

<img src="https://product.hubspot.com/hubfs/invisible-recaptcha-preview.png?t=1516140244757">

Google Invisible reCAPTCHA is a plugin for WordPress that enables a reCAPTCHA that is only visible when a user is suspected to be a bot. It comes with amazing features including:

1. Login form protection
2. Comments form spam protection
3. Forgot password form protection from spammers
4. Product review form protection spammers
5. Registration form protection

<img src="https://product.hubspot.com/hs-fs/hubfs/Screen%20Shot%202017-07-25%20at%203.42.18%20PM.png?t=1516140244757&width=320&name=Screen%20Shot%202017-07-25%20at%203.42.18%20PM.png">

<b>Installation and Configuration</b>

<img src="https://www.wpblog.com/wp-content/uploads/2018/01/search-recaptcha.png">

Go to plugins then Add new and search for Google Invisible reCAPTCHA . Once you installed then go to setting to configure the Google Invisible reCAPTCHA plugin.

<img src="https://www.wpblog.com/wp-content/uploads/2018/01/settings-860x493.png">

After that, you see that the plugin requires a secret key and a site key. Follow this <a href="https://www.wpblog.com/add-google-invisible-recaptcha-in-wordpress/">Google Invisible reCAPTCHA Guide</a> to go through the authentication process.