teleren/devto huggingface dataset:
Is OOP less descriptive than FP?
Tags: oop
Published: 2021-02-20 23:05:30

---
title: Is OOP less descriptive than FP?
published: true
description: 
tags: #oop
//cover_image: https://direct_url_to_image.jpg
---

Almost two years ago, there was a recent discussion topic introduced by the post [Is OOP dangerous?](https://dev.to/rachelsoderberg/is-object-oriented-programming-dangerous-2f32) that kept my attention. I am always interested in apparent contradictions because they are very often the source of new knowledge and development.

At that time I wrote [this article](https://dev.to/yucer/oop-vs-fp-and-the-quest-for-reality-gko) as a draft and left it unpublished until today. It was intended to compare the descriptive power of *OOP* vs *FP* (and *imperative* vs *declarative*) paradigms.

To be honest, I don't feel I can invest enough time or have enough resources to make a formal comparison, but I like to look for new arguments every time so I have decided to publish it without changes, and tag it as a discussion.

So what do you think?

Do both programing paradigms have the same descriptive power?
ABC of Polling in JS
Tags: javascript, polling, pollinator, node
Published: 2021-02-20 22:58:47

No, not that kind of polling you silly! The JavaScript type, meaning repeatedly calling a given function in some interval of time. Sounds easy? Well, I hate to spoil a good day for you.

## You don't want Tennet to happen in your code
One might think "What's the big deal here? Just use setInterval!". Not so fast bucko!

```javascript
function callMe() {
  // sync stuff
  console.log('Aye there!')
}

setInterval(callMe, 1000)

// logs
// [0:01] Aye there! 
// [0:02] Aye there! 
// [0:03] Aye there! 
```

That may look fine for polling a synchronous function. Add a side effect making it asynchronous and we have a completely different story here. An async function may yield its results in a time that is longer than the polling interval.

```javascript
let calls = 0
async function callMe() {
  calls++
  const callNo = calls
  // async stuff
  console.log(`Call #${callNo}`)
}

setInterval(callMe, 1000)

// logs
// [0:01] Call #1
// [0:03] Call #3
// [0:05] Call #2
// [0:08] Call #4
```

This is a mess that may lead to some serious errors in your code. We don't have constant time interval between the results. What's more important, the chronology is all screwed up! Chris Nolan would be happy, but we are not!

To get the calls in the right order we need to:
- make a call
- wait for the function to return something
- wait the defined delay time
- go back to the start

## Getting the stuff
Getting the data back can be a bit tricky. In most cases, that polled function returns something interesting. To retrieve this data we need a callback function. We can also attach an event, to allow many callbacks. That is useful, as we may like to stop polling when certain response arrives and conditions are met. Or to feed some other logic with those responses.  

## Err... what?
Polling can be prone to errors. Especially when we call a function that calls some API on a remote server. Network errors or glitches on the server side may lead to rejecting some of that calls. Yet sometimes we would like to continue polling regardless of errors. Maybe that consequent call will return real and valid data. We should be able to stop polling only when a certain number of failures in a row takes place.

## Pollinator to the rescue 🐝
I wrote a small, but busy little module you can use to address all those issues and more. Yes, we can be lazy again! Biggest advantages:

- very tiny, only 907B (that's right, bytes) minified and gzipped
- you can start, stop and pause anytime you want
- can stop polling when meting a condition based on current and previous returned data
- event based
- handles errors like a champ with configurable number of safe retries
- written in TS!
- Node and browser compatible

If you see a place for it, give it a try! Hope it saves some effort for you. 

{% github inspmoore/pollinator no-readme %}

BTW Feedback is more than welcome!
Deep or superficial learning is the problem
Tags: programming, backend, laravel, php
Published: 2021-02-20 22:47:16

There are many languages for programming and the number of available frameworks and libraries is increasing day by day. 


It's very interesting to me to know what programmers are most often employed in large technology companies like google, apple and some more.

A programmer who is fluent in a language and is well acquainted with its frameworks and libraries. Or a programmer who has worked with multiple frameworks but has not had the opportunity to learn deeply.

I will explain what I mean with an example. One of the best PHP frameworks is Laravel. Laravel learning can only end with basic topics such as:

-Routing
-Middleware
-Controllers
-Requests
-Views
-Validation

Or involve in-depth learning and work with many parts of this framework.
Have you written two or three useful packages and are familiar with some pupular packages?

Of Course it's just a simple example! But who person is win at this fight?
LeetCode 703: Kth Largest Element in a Stream (Python)
Tags: leetcode, algorithms, python, codenewbie
Published: 2021-02-20 22:43:54

Description: [https://leetcode.com/problems/kth-largest-element-in-a-stream/](https://leetcode.com/problems/kth-largest-element-in-a-stream/)

Solution:

```python
from heapq import heapify, heappush, heappop, heappushpop

class KthLargest:

    def __init__(self, k, nums):
        """
        :type k: int
        :type nums: List[int]
        """
        self.k = k
        self.k_heap = nums
        heapify(self.k_heap)
        while len(self.k_heap) > k:
            heappop(self.k_heap)

    def add(self, val):
        """
        :type val: int
        :rtype: int
        """
        if len(self.k_heap) < self.k:
            heappush(self.k_heap, val)
        else:
            heappushpop(self.k_heap, val)
        return self.k_heap[0]
```

Explanation:

On the initializer:

1- Create a min-heap with the stream of numbers we are given.

2- Pop from the min-heap until it has the same amount of elements as `k` . This means that the `Kth` largest element is on the top of the min-heap.

On add method:

1- If the amount of elements inside the heap is less than `K` , push the element to the heap. Else, push the element and then pop the top element.

2- Return the top element of the min-heap. It will be the `Kth` largest element.
Kids With the Greatest Number of Candies (ruby LeetCode)
Tags: leetcode, ruby, algorithms, codenewbie
Published: 2021-02-20 21:55:50

Description: [https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/](https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/)

Solution:

```ruby
def kids_with_candies(candies, extra_candies)
    greatest = candies.max
    
    candies.map do |candy|
        (candy + extra_candies) >= greatest
    end
end
```

Explanation: A kid will have the greatest number of candies if they have the same amount or greater, than the kid that already have the most amount of candies. So the first step is to find the greatest amount of candy, among the kids and save that number. The second step is to map through the candies array and see if the selected amount, plus the extra_candies, is equal or greater than the number we saved on the first step. In the end, the function will return an array with `true` and/or `false` values.
My first basic powershell module
Tags: powershell, cli
Published: 2021-02-20 21:49:11

Hello everyone, I'm back after a nearly two week pause. Had some back pain problems and wanted to avoid sitting in front of the computer so much. But now I'm better and eager to code and write again. So let's go.

During the last year I started to use powershell to automate some application deployments on multiple projects. Found some parts where the code is really similar, so i want to extract those parts into a module.

The build scripts are going to be used on various machines from various colleagues. So I wanted a solution with as little setup as possible.

My example module consists of two files:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z8i1ldsf3d2tp5n1ifdw.PNG)

**m1.psm1**: Contains the code for the module

```powershell
function testName($toTest) {
    "Validating: $toTest"
    if($toTest -eq "test") {
        throw "The value of the parameter to test is incorrect!"
    }
}

function helloWorld() {
    "This is a hello world from a module!"
}

Export-ModuleMember -Function "helloWorld"
Export-ModuleMember -Function "testName"

```
Notice the two Export Statements at the bottom. Exporting your module functions makes them usable outside of the module.

**m1.psd1**: This file is the module manifest and contains metadata about the module. It is created via the New-ModuleManifest Commandlet. I don't know much about it but pointing the property RootModule to my script file in the module helped to get rid of some errors where functions where not recognized.

```powershell
RootModule = './m1.psm1'
```

also see: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/new-modulemanifest?view=powershell-7.1

Finally the code to test it all:

```powershell
Import-Module .\m1\m1.psm1
helloWorld
testName -toTest "test"
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hmdf1uhxc9x6sc26rre6.PNG)

Notice here that I use the relative path to import the Module. Please remember that i'm using this for deployment scripts which might be run by my colleagues on their machines. I want to avoid them having to install and update the module when something changes. I will just commit the deployment script and module with the project in git and expect that it should work with having to install anything.
Error: ‘Cannot read property ‘options’ of undefined’ al intentar crear Multi-app con Ionic + Angular
Published: 2021-02-20 21:35:53

Intentando crear un proyecto multi-app con Ionic + Angular siguiendo evangélicamente esta guía por el equipo de Ionic:
https://github.com/ionic-team/ionic-cli/wiki/Angular-Monorepo
 —

![](https://cdn-images-1.medium.com/max/2044/1*i421tJu58s1NLrrGbn93lA.png)

Me he tropezado con el siguiente error en el paso 4.2:

*…Generate an app and add Ionic to it:*

    **ng add @ionic/angular --project=app**

## **¡SOLUCIÓN RÁPIDA!**

1-) *En vez de ejecutar esto (paso 4.1):*

    ng generate application --minimal --prefix=app --routing — style=css app

*Ejecuta esto:*

    **ng generate application --prefix=app --routing --style=css app**

## ¡RAZONES! (texto largo)

En lo poco que indagué, no hallé explicaciones específicas del mismo y como gustaba completar las fases si o si de esta forma para inicializar un nuevo proyecto, me puse a “debuggear” a punto de nuestro archi-conocido *“console.xyz”…* y viejo amigo, claro! (no, no! El malvado *--verbose* no me trajo nada esta vez :@)

El CLI con el schematic *“ng-add”* espera obtener estrictamente la opción: **“test”** desde el *angular.json* del proyecto que intentamos agregar angular.

![](https://cdn-images-1.medium.com/max/2650/1*LOCKj-fEycwZtKBVkrSF5w.png)

Como habrás notado, la actual opción está indefinida (no existe), debido que el argumento “--minimal” con el comando: *ng generate application,* no genera la configuración para testing pero el *schematic* lo necesita (por lo visto, la guía si le falta actualizar esta parte la 
cuál ya fue reportado como una nueva revisión también [aquí](https://github.com/ionic-team/ionic-cli/wiki/Angular-Monorepo/1a2abde83d1e9f22358c1d09a3a745f62f2b5a05)).

![](https://cdn-images-1.medium.com/max/2000/1*QQSJWk38vtq2iouq8c1ayQ.png)

—

**“--minimal”** es solo para fines de aprendizaje, pero cuando pensé que era una historia ideológica como “¡Pruébelo correctamente!”, no esperaba que tropezara de esta manera hehe!

Si no me di explicar o tienes alguna duda/sugerencia, por favor déjame saber en los comentarios.

Saludos estimado iónico. ;)
Discrete Probability Distributions with Python
Tags: python, machinelearning, prediction, math
Published: 2021-02-20 21:08:24

For example, if the random variable X is an experiment where a coin is tossed into the air and the coin lands, there are two possible outcomes: 0 if the tails come in, and the 1st state space (0.1) if the tails come, the probability of the event is 0.5. happens. Hence the probability mass function:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5y2hny0qrrl5lhkmffu.png)

It is expressed as. So far, we have explained the basis of probability theory through an example. Now, let's graph and visualize the event that I told through a new example with software. We Will See The Theory!

In our example this time there will be a dice. We will look at the average of the numbers on this dice and to what number this average converges to. Now, let's take a dice and roll the dice 100,000 times, let's write the numbers on a piece of paper… Joke, we can start by adding libraries.

We have created x and y lists together with our variables. We also determined the axis names of the plt chart. We created the X and Y lists to keep track of the number of dice rolled and the number of dice beats.

I would like to start the story with our 'number' variable While loop; We picked 100 times numbers from [1,6], and added it to the sum variable. Then our variable number of pulses was 0, we increased this variable by 100 so that we can show it in our graph. Then we divide the sum by the number of shots to our average variable and assign its mean. Finally, add the mean and number of pulses to the x and y lists.

We have repeated this about 1000 times. Then we printed it using the codes ply.plot and plot.show. We printed our lists to the console with the print commands in the upper lines. You can examine; really attracts attention.

Now we are where I am most excited; I think it's getting closer to the center of gravity! Another detail is that this point is the arithmetic mean of the numbers on the dice:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnvc2oecq9khbzyaehjr.png)

As a result, we saw that it converged to our experimental possibility. In terms of practicality, you can apply our first example of coin dumping yourself.

{% gist https://gist.github.com/AlicanAKCA/361e8a7607ff5bc6257e3960b0e76598 %}
So, I wrote a book
Tags: clojure, books
Published: 2021-02-20 20:24:09

I just finished writing my very first book! It is an introduction to the ClojureScript programming language that is primarily aimed at curious JavaScript developers. This has been several years in the making, and I am very proud to have finally produced a finished book!

[The entire book is free online](https://www.learn-clojurescript.com/), and if you would like to contribute your thanks to the effort I have put in, you can pre-order a physical copy at https://gumroad.com/l/learn-cljs. I would love to know what you think about the book!
React Native: Simple responsive Images for all screen sizes with flex.
Tags: reactnative
Published: 2021-02-20 20:13:17

---
title: React Native: Simple responsive Images for all screen sizes with flex.
published: true
description: 
tags: ReactNative 
//cover_image: ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcuvgu4lmihleqt4xc0d.png)
---

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcuvgu4lmihleqt4xc0d.png)

Smartphones come in different shapes and sizes, therefore it is paramount our content responds accordingly.

Images can be problematic when delivering our design across different screens. A one size fits all strategy would not work in today's diverse smartphone landscape and would likely result in a user experience nightmare.

The Flexbox module is based on the Cartesian coordinate system, which is distances over two lines running perpendicular, famously known as the
X-axis and Y-axis, with the Cartesian system in mind our container can be calculated with the main axis which runs horizontal, and the cross-axis which runs vertically as illustrated in the image above.

Consider your container as the X-Axis and Y-Axis that holds the Image.

Consider your container as the X-Axis and Y-Axis that holds the Image.

for example:

```
<View style={styles.container}> // X & Y axis.
<Image /> // value or items`
</View>
```

The container value has a height and width as per your requirements.

for example:


```
container : {width: 180, height: 200}
```


In order to ensure images inside the container adapt to change, we can use percentages to ensure the size is always on par with the height and width of the container.

Therefore, to make the images responsive we can simply set the value of height and width to 100% and resize mode to cover.

```
<View style={{
    width: 180,
    height: 200,
    aspectRatio: 1 * 1.4,

    }}>
    <Image
    source={{uri : item.image.url}}

    style={{

    resizeMode: ‘cover’,
    width: ‘100%’,
    height: ‘100%’

    }}
    />
</View>
```


By setting the Image’s height and width to 100% and resize mode to cover, the image will proportionately occupy a 100% of the container's real estate inside of the X and Y-Axis or the container. It will uniformly scale the image whilst maintaining it’s aspect ratio proportionate to the dimensions of the container.

To conclude, the application of geometry can be an effective resource in scalability. The simple notion of a box and the compatibility of its contents is a good way to think about how responsiveness works in our applications. It is important to note that the container’s style has precedence over the image’s style similar to a waterfall effect, that is how the container’s value dictates how high or wide the image can stretch in the UI.
How I can cache the built layers between builds on travis?
Tags: help, docker, travis
Published: 2021-02-20 20:01:53

As I ask in https://devops.stackexchange.com/q/13398/4396 I want to cache any built layer on my dockerfile in order to speed up my docker builds.

I have the following .travis.yml:

```
language: shell
os: linux
dist: xenial
git:
  depth: false

services:
  - docker

env:
  global:
    - LATEST=39
    - LATEST_LTS=39
  jobs:
    - "DB_TYPE=all VERSION=35 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=35 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=pgsql  VERSION=35 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=35 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=pgsql VERSION=36 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=all VERSION=36 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=36 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=pgsql  VERSION=36 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=36 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=pgsql VERSION=36 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=all VERSION=37 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=37 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=pgsql  VERSION=37 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=37 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=pgsql VERSION=37 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=all VERSION=38 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=38 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=pgsql  VERSION=38 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=38 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=pgsql VERSION=38 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=all VERSION=39 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=39 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=pgsql  VERSION=39 DOCKERFILE=dockerfiles/apache/Dockerfile"
    - "DB_TYPE=mysqli VERSION=39 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"
    - "DB_TYPE=pgsql VERSION=39 DOCKERFILE=dockerfiles/fpm_alpine/Dockerfile"

script: bash ./travis/build.sh

deploy:
  - provider: script
    on:
       branch: master
    script: bash ./travis/deploy.sh
```

And I use the following dockerfiles:

* https://github.com/ellakcy/docker-moodle/blob/master/dockerfiles/apache/Dockerfile
* https://github.com/ellakcy/docker-moodle/blob/master/dockerfiles/fpm_alpine/Dockerfile

How I can reuse docker build cache during the 16 parralel builds I perform?
Just another timer in svelte
Tags: svelte, showdev
Published: 2021-02-20 20:00:46

# Just another timer in svelte

![timer](https://raw.githubusercontent.com/slavcoder/timer/main/screenshots/mirage.png "main view")

I've just finished small project in [svelte](https://svelte.dev/) and decided to share it with you. 

This is a simple timer where you can set several counters. It might be used as a pomodoro app or to set some deadlines.

[live](https://slavcoder-timer.netlify.app/)

[repository](https://github.com/slavcoder/timer)

You can write time in specific format to create or save new counter.

Examples:

- `5d 20m 10m 30s` will be calculated as 5 days, 30 minutes and 30 seconds
- `0.2d` or simply `.2d` will be calculated as 4 hours and 48 minutes
- `1d -10h` will be calculated as 14 hours
- `-10s` will be invalid, the minimum time is 1 second and maximum is 9999 days
- `20/02/2025` will be calculated as time up to that date
- `-5h 20/02/2025 30m -4444s` will be valid (time up to that date, minus 5 hours, plus 30 minutes, minus 4444 seconds)

You can also customize features and themes by settings. 

This is my first small project using svelte and I would be grateful for feedback or star if you like it.
Universal macOS binaries with Go 1.16
Tags: go, macos, applesilicon
Published: 2021-02-20 19:50:07

[Go 1.16](https://golang.org/doc/go1.16#darwin) adds support for the newest architecture in town, Apple Silicon. With the help of `lipo`, a tool included in XCode, you can create universal binaries, which can work in both classic x64 Intel processors and the M1.

Let's get started!

Requirements:

* [Go 1.16](https://golang.org/dl/) or superior
* XCode 12.2 or superior

Let's compile one of the simplest Go programs

```go
package main

func main() {
	print("Hello,world")
}
```
Save this file in `hello.go`, and then execute the following two commands to generate binaries for both arm64 and amd64: 

```bash
$ GOOS=darwin GOARCH=amd64 go build -o hello_amd64 hello.go 
$ GOOS=darwin GOARCH=arm64 go build -o hello_arm64 hello.go
```

The `GOOS` and `GOARCH` instruct the Go compiler to generate a binary for the given architecture and operative system. You can cross-compile and create binaries for Mac from Linux and Windows, but you won't be able to create universal macOS binaries (for now). 

You can check the executable details of each generated binary with the `file` command: 

```bash
$ file hello_amd64 
hello_amd64: Mach-O 64-bit executable x86_64
$ file hello_arm64 
hello_arm64: Mach-O 64-bit executable arm64
```

Ok, the next step is the magic: `lipo` merges the two executables into a Universal one:

```bash
$ lipo -create -output hello_universal hello_amd64 hello_arm64
```

And there it is! Now you have a universal binary, that can be executed in both platforms:

```bash
$ file hello_universal 
hello_universal: Mach-O universal binary with 2 architectures: [x86_64:Mach-O 64-bit executable x86_64] [arm64]
hello_universal (for architecture x86_64):	Mach-O 64-bit executable x86_64
hello_universal (for architecture arm64):	Mach-O 64-bit executable arm64
```

If you distribute macOS binaries, this might help you to improve the UX of your consumers, so they don't have to worry about which version should they use.

Hope this little post help you!

For more information:
* [Building a universal macOS binary](https://developer.apple.com/documentation/xcode/building_a_universal_macos_binary)
* [Go 1.16 Release notes](https://golang.org/doc/go1.16)