teleren/devto huggingface dataset:
How do we unit test functions within a functional component?   
Tags: ux, testing, javascript, react
Published: 2020-02-21 13:11:27

With a class component I usually create an instance of that component and I can access the function. I'm not sure how to access the function of a functional component.
```
const errorMessages = {
    browse: {
        fileLimit: 'File size is too big.',
        unsupportedFormat: 'The file you selected is not a supported format. Please upload a file in .csv format.',
        noRows: 'No agent IDS could be found.',
        maxAgents: 'A max of 25 agents can be uploaded at a time.',
        noValidAgents: 'No valid agents could be found.'
    },
    duplicate: 'The following agents are already existing on the table.'
};
```
const UploadButton = (props, ref) => {
    const mimeTypes = ['text/csv', 'application/vnd.ms-excel'];
    let initialValue = false;
    const [browseError, setBrowseError] = useState(initialValue);
    const [uploadError, setUploadError] = useState(initialValue);
    const [duplicateError, setDupplicateError] = useState(initialValue);
    const [uploading, setUploading] = useState(false);
    const fileInputRefs = useRef(initialValue);

    const clearAllErrors = () => {
        setBrowseError(initialValue);
        setUploadError(initialValue);
        setDupplicateError(initialValue);
    }

....
} 

So accessing clearAllErrors for example or errorMessages which outside of the functional component.
Tipe Data
Tags: pemmrogramman, basispemrogramman, indonesia
Published: 2020-02-21 06:28:57

# Basis Pemrogramman - Tipe Data

> In computer science and computer programming, a data type or simply type is an attribute of data which tells the compiler or interpreter how the programmer intends to use the data - Programming Fundamentals (wikibooks)

Setiap [variabel](./variabel.md) mempunyai tipe data. Contoh tipe data yang gampang adalah 'angka' dan 'huruf', biasa disebut `integer` dan `string`. Nah pada JS (JavaScript) terdapat beberapa tipe data :

```js
const integer = 123 // integer cuma angka tanpa koma
const float = 123.12 // float punya koma
const strings = 'Hallo semua' // string huruf
const boolean = true // true / false merupakan boolean
```

```go
// Golang
var integer int = 123
var float float32 = 12.32
```

Setiap bahasa pemrogramman mempunyai tipe data dan tentu lebih dari yang diatas, `function` pada JS / C juga termasuk tipe data ada *pointer*, *signed or unsigned int*. Tapi dalam kehidupan nyata bisa dibilang kita hanya mengenal 2 tipe data yaitu - 'angka' dan 'huruf'.

But why? tipe data mempengaruhi bagaimana semuah data dapat di representasi dan diolah oleh program. misal 1 + 2 = 3? lalu kalau w + 2 = w2?. Mungkin di JS seperti itu tapi mungkin juga di bahasa lain tidak, atau bahasa lain error.

Untuk melatih kebiasan terhadap tipe data mulailah bermain main dengan tipe bahasa yang tersedia di bahasa pemrogramman. Saya beri contoh.

```js
const a = 12
const b = 15
console.log(12 + 15) // 27

const c = '12'
const d = 1
console.log(c - d) // 11

const e = 5
const f = 'h'
console.log(c - d) // NaN
```
Creating APIs that sustain the test of time
Tags: todayilearned, api, architecture, microservices
Published: 2020-02-21 13:00:28

*TL;DR notes from articles I read today.*

### [To create an evolvable API, stop thinking about URLs](http://bit.ly/2SJ3s4L)

- To build an evolvable API, instead of forcing clients to have prior knowledge of URLs, fields and HTTP methods, you should let the client ask the server what is required to complete an operation and indicate the preferred host and path. 
- Critical aspects of evolvable API include:
a) The state of the conversation being stored in the network - not sourced from either client or server. 
b) No versioning needed - when you add or remove data from a response, clients should know how to react. If they don’t know how to react to a new feature, they should be able to ignore it and work in the old way.
c) The server owns actions which contain values for URLs, methods, and fields, so that they control where clients go to continue the conversation, with only the entry point hardcoded in the client.   
- With control of URLs in the server, it can run A/B testing and direct clients to different servers running the same instance of the application. The server can also implement a polling functionality to track the status of requests. 
- Model communication on how people actually operate. Think not only about a generic language but developing a shared domain vocabulary.  

*[Full post here](http://bit.ly/2SJ3s4L), 10 mins read*

---

### [The differences between gateway, microgateway and service mesh](http://bit.ly/2uTVX1W)

- An API gateway is a central interface for all external communications. It typically works by invoking multiple microservices and aggregating results to determine the best path. 
- It may also handle authentication, input validation and filtering, and metric collection, as well as transforming requests and/or results. For the microservices network, it offers lower latency, better efficiency and higher security, as well as easier isolation of single sources of failure. 
- API microgateways are proxies sitting close to microservices for internal communication between microservices, allowing better governance, discovery, observability, and stability for developers and expose the policy enforcement point and security controls to operators. 
- They are a more granular solution than a single API gateway due to the control of exposure. They offer low latency and a small footprint, as requests don’t need to wait their turn. This does imply code duplication across multiple microservice instances, which can be inefficient if code is not intelligently structured.
- A service mesh is a layer between microservices for all service-to-service communication that replaces direct communication between services. It will often have in-built support for resiliency, error checking, and service discovery. It is similar to a microgateway but with network communications entirely abstracted from business logic, allowing developers to focus entirely on the latter. 

*[Full post here](http://bit.ly/2uTVX1W), 8 mins read*

---
Daily Developer Jokes - Friday, Feb 21, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-02-21 13:00:18

---
title: "Daily Developer Jokes - Friday, Feb 21, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Friday%2C%20Feb%2021%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258ef9deee.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ What did the proud React component say to its child?

___A:___ I've got to give you props
 -->
What were some quirks and gotchas about working with Python 1?
Tags: watercooler, python
Published: 2020-02-21 12:45:39

Python 2 was released in October 2000, but Python 1 was released to the world six years earlier, in 1994 - much like my younger brother.  I have an inkling that, also much like my younger brother, it would have been wrought with idiosyncrasies and quirks that would take at least solid decade to iron out (sorry Jonah, you're a cool guy).

I am not planning to use any ancient Python myself, this is a historical curiosity post.  What are your war stories?  Put your nineties hats on!
What would be your choice of framework in 2020?
Tags: angular, webdev, ember, javascript
Published: 2020-02-21 12:44:40

Ever come across a situation when you are using a framework for a long time but find yourself wanting to explore another one to add in the box?

 

That's what happened to Mr. Smith, a client of mine. 

 

Mr. Smith has been an Ember user for a long time. To explore further, he'd been reading about Angular, various versions, watched some tutorials and case studies. 

 

However, the tricky part surfaced when he wanted to build an app that has a fast and responsive design, linear user experience, and high caching capabilities—a most feasible solution: Single Page Application. 

 

But then came the point where he realized that both these frameworks are equally suitable for SPA. So which one to choose?

 

We did a technical study and converted into a blog post, [Ember vs. Angular: Comparing Two Popular SPA Frameworks](https://www.simform.com/ember-vs-angular/)

 

![EmbvsAngComparison](https://www.simform.com/wp-content/uploads/2020/02/AngVsEmbComparison.jpeg)
 

TL;DR

 

Here is my opinion: 

 
##Ember & SPA:

It is based on an open-source javascript library. It is an easy to use web application framework for writing client-side web applications and is also an excellent competitor to write code for native apps. Since the technology is based on the Model-View-View-Model, it uses routes, templates, models, controllers, views, and components as the core concepts.
 
##Angular & SPA:

Angular is a confident winner when it comes to building single-page applications. It contains no dependencies such as jQuery or other types of javascript. It is what makes it a robust framework, among others. The navigation between the web pages becomes simple here because of the streamlined routing provided by the framework. 

The lightweight directives make it a high-performance javascript platform for building single-page applications such as Gmail. But its perks don't end here; it also provides easy access to conduct automated testing on the apps.   

We've published a detailed post here. We've compared both these frameworks on the common grounds of accessibility, testing, learning curve, and use cases. 
 
I would love to know which framework you would choose to build a Single Page Application in 2020 and why? Kindly comment, or let's get in touch @HirenDhaduk_ for further conversation.
📸 How to take screenshots from Chrome
Tags: productivity, chrome, webdev
Published: 2020-02-21 12:26:38

There are lots of Chrome extensions are available to take screenshots of websites.

But you know you can use Chrome's device toolbar to take screenshots of a website in any device sizes?

### 1. Go to Website

### 2. Open Developer Tools
![Open Developer Tools](https://dev-to-uploads.s3.amazonaws.com/i/l1uw9szar62e6o9nz27q.png)

### 3. Click Toggle Device Toolbar Option
![Device Toolbar Option](https://dev-to-uploads.s3.amazonaws.com/i/14fe9seqxv4otp9eazcy.png)

### 4. Choose Screen Size
![Screen Size](https://dev-to-uploads.s3.amazonaws.com/i/jhn8jf09g177k2xm7zs1.png)

Or you can choose the Responsive option and adjust the size.

### 5. Click Menu Icon
![Menu Icon](https://dev-to-uploads.s3.amazonaws.com/i/j65f3ze32o8jol3hqpll.png)

### 6. Choose Capture Screenshot Option
![Capture Screenshot](https://dev-to-uploads.s3.amazonaws.com/i/zt889y96yrnu1yeaz9lh.png)

# ✌️
What are you learning this week? And why???
Tags: discuss
Published: 2020-02-21 12:17:05

Heya you people.

I go first:
I am learning Bootstrap and AngularJS because a job opportunity needs me to know those, but prior to that I didn't know much about angularJS and would never think about learning it.

Your turn.

P.s. picture of my new laptop and my new stickers collection, because... Why not?
Antara proses dan hasil
Tags: life, work, productivity
Published: 2020-02-21 12:17:02

---
title: Antara proses dan hasil
published: true
description: Perlu suatu perjuangan untuk menempuh suatu hasil. Dan itu terkadang melelahkan
tags: life, work, productivity
series: Life
---

Terkadang kita merasa sudah melakukan yang semaksimal mungkin tapi hasil yang kita peroleh nggak sesuai dengan harapan kita.

Eh, tunggu dulu. Apakah sebelumnya kita nggak sadar bahwa yang akan kita dapatkan nanti hasilnya nggak seberapa?

Kalau kita cerdas, tentu saja kita sudah bisa mengestimasikan **apa hasil yang akan didapatkan jika aku mengerjakan ini**. Jadi, nggak ada lagi kisahnya kita menyesal karena yang kita dapatkan nggak seberapa atau kita nggak mendapat apa-apa.

Atau memang karena budaya Timur ya, serasa tabu gitu menanyakan hasil yang akan didapatkan:

> _Rame ing gawe. Sepi ing pamrih_

> Bersemangat dalam bekerja. Nggak menuntut imbalan

Itu sih kalau filosofi Jawa. Bahwa, kita nggak usah sih menuntut yang tinggi. Yang penting bekerja aja yang semangat dan pantang menyerah.

Ya bagus sih. Cuma..

..berorientasi pada hasil itu _bukan_ sesuatu yang tabu. Bukan sesuatu yang nggak patut ditanyakan. Kita tentunya memerlukan kejelasan. Kalau sudah jelas tentang apa yang akan kita peroleh, dan kita puas dengan apa yang akan kita peroleh, tentunya kan kerja akan jadi fokus; nggak kepikiran masalah hasil yang nggak jelas.

# **Proses** dan **hasil** dalam kegiatan sehari-hari

Oke, sekarang kita lepas dari konteks pekerjaan yang orientasinya adalah upah. Sekarang kita akan meluncur pada kehidupan sehari-hari. Masih berkaitan dengan tadi, maka ada perbedaan mendasar antara proses dan hasil:

> Proses: dinamis

> Hasil: statis

Oke, sini aku tunjukkan secara lebih detail perbedaan hasil dan proses:

| Hasil | Proses |
|-|-|
| Nikah | Menjalin relasi, meningkatkan pengetahuan tentang mengurus keluarga, taaruf |
| Lulus | Kuliah 4 tahun, bimbingan, skripsi |
| Dapat duit | Kerja |

Dari situ terlihat bahwa perlu _perjuangan panjang_ untuk memperoleh suatu **hasil**. Dan perjuangan itu disebut _proses_.

> _Bedakan yang namanya proses dan hasil. Proses itu fleksibel_

> Ustadz Syihabuddin Abdul Muiz Al-Hafidz, mudir [Mahad Isy Karima](https://isykarima.com)

Oh iya, di postinganku sebelumnya, aku udah cerita bahwa kita itu harus sabar dalam menempuh suatu proses:

{% post https://dev.to/mzaini30/menghadapi-ketidaknyamanan-262i %}

Karena yang namanya akhir dari segala sesuatunya itu adalah **hasil**, maka kayaknya nggak pantes deh baru di tahap _proses_ aja kita udah pamer.

> _Duduk seperti kucing. Menerkam seperti singa_

> Ustadz Gi, guru bahasa Indonesia di [SMA](https://isykarima.com)
Bendita competencia, por Xavier Mitjavila
Tags: xaviermitjavila, xaviermitjavilamoix, rebajas, enero
Published: 2020-02-21 12:09:14

---
title: Bendita competencia, por Xavier Mitjavila
published: true
description: Xavier Mitjavila Moix: Todavía no hemos llegado a fin de año y gran parte de los comercios ya están en el 7 de Enero. Ya empezaron las rebajas que, tradicionalmente, empezaban siempre después de las fiestas navideñas. ¡Los Reyes Magos estarán contentos con tantos descuentos antes de la noche del día 5!
tags: xavier mitjavila, xavier mitjavila moix, rebajas, enero
cover_image: https://secureservercdn.net/160.153.138.53/24n.cd0.myftpupload.com/wp-content/uploads/2020/02/Xavier_Mitjavila_Moix_articulo_bendita_competencia-1024x433.jpg
---

Todavía no hemos llegado a fin de año y gran parte de los comercios ya están en el 7 de Enero. Ya empezaron las rebajas que, tradicionalmente, empezaban siempre después de las fiestas navideñas. ¡Los Reyes Magos estarán contentos con tantos descuentos antes de la noche del día 5!

El origen de esta nueva práctica, radicalmente diferente respecto al calendario al que todos estábamos habituados, es el aumento de la competencia.

Esta nueva competencia llega sobretodo del mundo digital. El Black Friday, el Cyber Monday y Amazon, como actor principal, anticipan muchísimo la temporada de Navidad y se comen una parte importante del pastel antes de que los otros hayan empezado la carrera.

El comercio tradicional con puntos de venta físicos se adapta, lentamente y con dificultades, a esta nueva realidad basculando hacia el mundo digital y replicando en los puntos de venta el Black Friday. Mientras tanto, la única reacción posible para recuperar ventas antes de que acabe la temporada, es jugar con la misma arma: el calendario.

Por eso ya tenemos rebajas en todas partes. ¡Bendita sea la competencia!

Artículo originalmente publicado en [xaviermitjavila.com] (http://xaviermitjavila.com/2019/12/bendita-competencia-articulo-de-xavier-mitjavila-moix/)
¿Libertad?, por Xavier Mitjavila
Tags: xaviermitjavilamoix, danone, saimaza, marcilla
Published: 2020-02-21 12:06:14

---
title: ¿Libertad?, por Xavier Mitjavila
published: true
description: Xavier Mitjavila Moix: Los Estados Unidos siempre nos han vendido la libertad. Sus dirigentes han defendido la libertad de expresión, la de prensa, de empresa y todas las libertades habidas y por haber. 
tags: xavier mitjavila moix, danone, saimaza, marcilla,
cover_image: https://secureservercdn.net/160.153.138.53/24n.cd0.myftpupload.com/wp-content/uploads/2020/02/Opinion_Xavier_Mitjavila_Moix_libertad_proteccionismo_aranceles_obama_trump-1024x433.jpg
---

Los Estados Unidos siempre nos han vendido la libertad. Sus dirigentes han defendido la libertad de expresión, la de prensa, de empresa y todas las libertades habidas y por haber.

En economía, se han guiado también por la libertad de mercado y la famosa “mano invisible” de Adam Smith, que cruza oferta y demanda mientras buscamos maximizar el beneficio. Así han sido y así son los americanos, o al menos, eso parecía hasta ahora.

Hoy, el país de la libertad está implantando aranceles para dar y para tomar. Aranceles para China, para Brasil, Argentina y también para los países europeos donde, el queso fresco, el aceite de oliva y los productos porcinos -entre otros- ya sufren un incremento de sus precios del 25%.

Cuando Barack Obama finalizó su mandato, pensé que lo íbamos a echar en falta. Y muy a menudo así es. Pero en lo relativo a los aranceles, el mismo Obama impuso, solo a España, 546 medidas hasta 2017.

La llamaban “mano invisible”… Hoy, la mano es bien visible. La de Trump ahora y la de Obama antes. 

¿Entonces la libertad? Ahora lo llaman proteccionismo. 

Artículo originalmente publicado en [xaviermitjavila.com] (http://xaviermitjavila.com/2020/01/libertad-opinion-de-xavier-mitjavila-sobre-la-libertad-de-mercado/)
Building my personal website - Part 1 - The content
Tags: portfolio, webdev, design
Published: 2020-02-21 11:47:20

After I gave my first public tech talk, I finally felt confident enough to expose myself to the international dev community. And as I've just shut down two personal projects that were taking up my free time, I decided that time has come: I would build my personal website.

The first thing I did was look for articles about what a personal website should be like, specifically what content should it include. It was a good first step to the wrong direction.

# A good first step to the wrong direction.

I avoided looking for design inspiration and focused on the content instead. After a bit of research I came up with a list.

A personal website must have:

- Easy to find contact info
- Downloadable Curriculum Vitae
- A list of my strongest skills
- My best personal projects
- My personality

I started to prototype it, completely ignoring the list I've just made. With the first proposal finished I realized it had nothing to do with these items.

The fact is: that was somebody else's list. It includes what's important to other people who have already built their websites and written articles about it.

Realizing this I started to think about what **my** site should be. It must be a professional dev website, describing me and what I do, featuring some personal projects and my dev contact info.

I dropped the Curriculum Vitae: it should be personalized to a specific job position, featuring only relevant information.

The skills list? It just doesn't feel right to choose somethings and leaving others off of the plate. Should I put how much % of PHP I know? Should I separate Typescript from JS and SASS from CSS? Why bother? I decided that giving only the general context that I'm (mostly) a web developer would be the right thing to do.

Having the content in mind, I defined what's important to me on a good website in general. It should be fast, accessible, respecting the user preferences (dark mode, low motion, zoom) and should be simple. It must be totally static to be served by GitHub Pages.

It should have no JS. Ok, this last one is just a whim of mine.

Ancient browser support is not something that I'll be worried about. My public target (people interested in web development) is known for hating those entities.

Now that I knew what my site should be, it was time to start the design.

Spoiler: I'm not a designer.
How to resize images from the media library with code
Tags: sitecore, dotnet, csharp
Published: 2020-02-21 11:30:51

One of the missions of a web developer is to make your sites fast & user friendly, something that can be measured by google's speed insights score. One way to do increase your score and speed is to download images in the right size instead of the ( -most of the time- way) bigger size just to then resize it using css. This obviously gives a better speed since you need to download alot less data (which is critical on mobile and low internet devices). In order to download the right size, content editors could upload the correct one to the media library. However this is, due to many reasons (e.g. reusing old images,...), not always possible.

Luckely for us, Sitecore does have this feature built in. You can resize image from the media library to any size by adding query parameters to the image's url and then adding a protective hash.

You can do this as follows in vanilla Sitecore:

```c#
string url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
string resizedImageSrc = HashingUtils.ProtectAssetUrl(url + $"?w={width}&h={height}")
```

For those of you that do use Glassmapper you can do it as follows:
```c#
string url = image.Src
string resizedImageSrc = HashingUtils.ProtectAssetUrl(url + $"?w={width}&h={height}")
```

#Parameters
Besides from setting the width & height you can also set other query parameters:

° w: Width in pixels
° h: Height in pixels
° mw: Maximum width in pixels
° mh: Maximum height in pixels
° la: Language (defaults to context language)
° vs: Version (defaults to latest version)
° db: Database name (defaults to context database)
° bc: Background color (defaults to black, for white bc=ffffff)
° as: Allow stretch (as=1)
° sc: Scale by floating point number (sc=.25 = 25%)
° thn: Thumbnail (thn=1)
° dmc: Disable media caching, both retrieval and storage (dmc=1)

which you can just add to the query parameters.

#Sources
https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/media-options-and-query-string-parameters-in-the-sitecore-asp-net-cms