teleren/devto huggingface dataset:
python pathlib
Tags: python, beginners
Published: 2020-02-12 12:30:21

With the <a href="https://python.org">Python</a> programming language, you can deal with files. Some things you can do with Python are <a href="https://pythonbasics.org/read-file/">read files</a>, <a href="https://pythonbasics.org/write-file/">write files</a>, create files and much more. 

If you worked with files in Python, you know that dealing with Paths can be quite cumbersome. On top of that paths are written differently on systems like Windows (\) or Mac (/)

You may be familiar with having to deal with double slashes and the like:

```python
b = "c:\\stuff\\morestuff\\furtherdown\\THEFILE.txt"
```

Meet the <a href="https://docs.python.org/3/library/pathlib.html">pathlib</a> module, which prevents you from writing code like this.

## Pathlib

Pathlib makes working with paths and files in general easier. Instead of those ugly double slashes you can write elegant and readable Python code. 
To get your home directory:

```python
>>> import pathlib
>>> pathlib.Path.home()
```

The current working directory:

```python
>>> import pathlib
>>> pathlib.Path.cwd()
```

You can simply add slashes for subdirectories

```python
>>> pathlib.Path.home() / 'Desktop' / 'pama'
```

To define a filepath you can do this:

```python
>>> filename = pathlib.Path.home() / 'Desktop' / 'files' / 'test.txt'
>>> filename
```

So you can use that path (filename) to read files as you would normally do:

```python
>>> filename = pathlib.Path.home() / 'rdp.txt'
>>> with open(filename, mode='r') as f:
...     data = f.readlines()
... 
>>> data
```

You can even read files with one liner:

```python
data = pathlib.Path(pathlib.Path.home() / 'rdp.txt').read_text()
```

To get the extension, name or parent of a path is also super easy:

```python
>>> path = pathlib.Path.home() / 'Desktop' / 'files' / 'test.txt'
>>> path.name
'test.txt'
>>> path
PosixPath('/home/tux/Desktop/files/test.txt')
>>> path.parent
PosixPath('/home/tux/Desktop/files')
>>> path.suffix
'.txt'
>>> path.stem
'test'
>>>
```

**Related links:**
* <a href="https://docs.python.org/3/library/pathlib.html">Python Pathlib module</a>
* <a href="https://pythonbasics.org/">Learn Python</a>
Any tips or example for using Firestore with MobX
Tags: help
Published: 2020-02-12 12:24:41


I am doing a NextJs app and I just need state management and Firestore intergration. Redux is too complicated for this job within time limit at the end of February.


The last tutorial I found is using Firebase Realtime Database. The data is aleady on Firestore so I can't change that. I appreciate your support and thank you in advance.


Also, it would be nice if you can help me to persist MobX state in localStorage.
MineSweeper Game In Vanilla JavaScript
Tags: javascript, css, showdev
Published: 2020-02-12 12:04:44

I wanted to code a little game and I thought "why not MineSweeper", you remember, the old classic from Windows where as a kid we all didn't know how it worked? Yes, that one!

Here is what it looks like:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ut8p3wisgmwkyo1vh2uq.gif)

You can play the demo here 👉 [MineSweeper Game Demo](https://minesweeper.marc.dev)

And if you're interested how I coded this, I uploaded the code to [Github](https://github.com/themarcba/minesweeper).
python relative import
Tags: python, beginners
Published: 2020-02-12 11:49:29

Like any other modern programming language, in <a href="https://python.org">Python</a> you can import code from other files or <a href="https://pythonbasics.org/modules/">modules</a>.  If you used Python before, you know that you can use modules. 

With modules (packages) you can use already existing code bases in your own code, saving you a lot of development time. 

You can import any module with the **import** keyword.

```python
import math
import sys
import os
...
```

Before playing with modules, you should know the <a href="https://pythonbasics.org">basics of Python</a>.

So what is an absolute and a relative import?

## Absolute import

Absolute import defines the resource to be imported by its full path (projects root).  You likely already have used absolute imports, as its the default way of importing modules in Python.

These are examples of absolute imports:

```python
import package
```

And this:

```python
from package.firstmodule import firstmodule
```

## Relative import

A relative import imports the resource relative to the current location. 

In other words, with relative imports you specify *where* your resources are *relative to the current python script*.

```python
# Import names from pkg.string
from .string import name1, name2

# Import pkg.string
from . import string
```

You can see the dot in front of the module, relative imports use dot notation. 

A single dot means the current directory, you may be familiar with this from <a href="https://en.wikipedia.org/wiki/Linux">Linux</a> or command prompt where: 

* dot (.) means current directory
* dot dot (..) means parent directory
* dot dot dot (...) means grandparent directory

## Which to use

You should use absolute imports, unless you have a reason not to. Absolute imports are clear and easy. It specifies where the imported resource is, just by looking at it.

New modules can be <a href="https://pythonbasics.org/how-to-use-pip-and-pypi/">installed with pip</a>, which saves you from having to commit many packages inside your code base.


## Related links
* <a href="https://docs.python.org/2.5/whatsnew/pep-328.html">Python PEP on relative imports</a>
* <a href="https://pythonbasics.org">Learn Python</a>
How to host a static website for free using Google Cloud Platform
Tags: php, productivity
Published: 2020-02-12 11:26:30

<h2>What is Google Cloud Platform ?</h2>
Google Cloud Platform is a data center infrastructure that Google uses for their products like Youtube, Search, etc. GCP is one of the popular cloud  services especially for startups and websites since its price is cheaper and affordable than other cloud computing providers. Other popular cloud service providers are Amazon Web Services, Microsoft Azure, Oracle and IBM Cloud.


Google provides 300$ credit for free to new users. We can use this to host a new html site for free.

Steps for hosting a website in Google Cloud Platform :

1. Signup for free quota from Google cloud website https://cloud.google.com/ using your google account and validate credit card details.

![Signup](https://dev-to-uploads.s3.amazonaws.com/i/187zf4od0pen9bofbgou.png)

2. Then Create a project by giving your needed website name. 

3. Create an app in App Engine https://console.cloud.google.com/appengine to your project
![Create an App](https://dev-to-uploads.s3.amazonaws.com/i/fa7tka2msub8wopltf2e.png)


4. To Deploy your website to the created app, download Google Cloud SDK from the link https://cloud.google.com/sdk/docs/quickstarts .

5. Run Google Cloud SDK

6. Initialize the Google cloud SDK with <code>gcloud init</code> command.
![Gcloud Init](https://dev-to-uploads.s3.amazonaws.com/i/foqafkbfdohh3xydd5yq.png)
![Next Step](https://dev-to-uploads.s3.amazonaws.com/i/6cnwj11h55dy2rsbmcmy.png)

7. Create a <a href="https://atooz.in/web-design-company-coimbatore.html">website design for your startup</a> in <code>path_to_website_root_folder</code>

8. Point command prompt to the folder the website files exists
          <code>cd ../../path_to_website_root_folder/</code>

9. Create <code>app.yaml</code> file and map website files in the website root folder. Follow the standards and code snippets in the link https://cloud.google.com/appengine/docs/standard/php/config/appref

10. Deploy the app using command <code>gcloud app deploy</code>
    https://cloud.google.com/appengine/docs/standard/php/tools/uploadinganapp

11. The files will be uploaded successfully and a subdomain will be generated on appspot domain. You can use that subdomain or connect your own domain to the project. https://console.cloud.google.com/appengine/settings/domains.
We are giving away a Dracula Pro license 🔥
Tags: giveaway, contest, developers, ide
Published: 2020-02-12 11:22:08

We are giving away a [Dracula Pro](https://draculatheme.com/pro) license on our Twitter, retweeting and liking is required to enter the contest. 

{% twitter 1227548548683747328 %}

Credits for Dracula PRO go to @zenorocha, more information about his story:

{% link https://dev.to/zenorocha/i-made-a-color-scheme-for-programming-using-math-2ne6 %}
string substitution python
Tags: python, beginners
Published: 2020-02-12 11:09:45

In <a href="https://python.org">Python</a> you can easily substitute a <a href="https://pythonbasics.org/strings/">string</a> without having to do character by character replacement (looking at you <a href="https://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c">C programming</a>).

In fact, Python has a method named **.replace()** which is part of the <a href="https://pythonbasics.org/strings/">string</a>.

The syntax for the replace method is:

```python
str.replace(old, new[, max])
```

Where the parameters are:

* **old** the string to be replaced
* **new** the new string
* **max** optional, maximum number of replacements

## Replace example

Take a look at this example in the Python shell.

```python
>>> s = "All work and no play makes jack a dull boy"
>>> s = s.replace("jack","Josephine")
>>> s = s.replace("boy","girl")
>>> s
'All work and no play makes Josephine a dull girl'
>>>
```

So strings get replaced and the method can be called multiple times on the same string.

By default it replaces each string it finds, with no limitation.
The following example shows the usage of replace() method.

```python
>>> x = "for philip python programming is pragmatic and powerful"
>>> x = x.replace("p","P")
>>> x
'for PhiliP Python Programming is Pragmatic and Powerful'
>>> 
```

But if you add the optional max parameter, you can limit the number of occurrences:

```python
>>> x = "for philip python programming is pragmatic and powerful"
>>> x = x.replace("p","P",1)
>>> x
'for Philip python programming is pragmatic and powerful'
>>> 
```

This also works on <a href="https://www.python.org/dev/peps/pep-0498/">f-Strings</a> (formatted-strings).

```python
>>> a = 1
>>> b = 2
>>> x = f"a is {a} and b is {b}"
>>> x = x.replace("a ","A ")
>>> x
'A is 1 and b is 2'
>>> x = x.replace("b ","B ")
>>> b
2
>>> x
'A is 1 and B is 2'
>>>
```


**Related links:**
* <a href="https://pythonbasics.org/replace/">Replace function</a>
* <a href="https://docs.python.org/3.8/library/string.html">Documentation on strings</a>
* <a href="https://pythonbasics.org/">Learn Python</a>
Waves Blockchain - Explorateur de blocks et IDE en ligne
Tags: blockchain, waves, node, ride
Published: 2020-02-12 11:00:46

Lorsque l'on développe des applications sur la Blockchain, il y a un outil indispensable et commun à toutes les Blockchains, c'est l'explorateur de blocks (Waves Explorer) qui permet de consulter l'ensemble des actions liées à un compte Waves ou un block. Pour cela nous allons voir en détail ici les fonctionnalités de l'explorateur waves.

Autre outil indispensable, notamment lorsque l'on souhaite tester un nouveau langage, c'est l'IDE en ligne, il permet de tester la programmation de Smart Contract sans avoir à se soucier d'installer tout l'environnement et les librairies nécessaires et ainsi d'aller à l'essentiel. Nous avons souvent utilisé l'IDE en ligne dans les précédentes vidéos mais voici ici le détail des options de celui ci.

https://youtube.com/watch?v=mbgnDtddm6w

PROCHAINES VIDEOS

15 février
Waves Keeper, cette extension navigateur, similaire à Matamask, permet aux utilisateur de votre application Blockchain de gérer l'ensemble de leurs comptes directement depuis le navigateur et de manière entièrement sécurisée.

19 février
Préparer son environnement de développement local est la suite logique après s'être familiarisé avec l'IDE en ligner. Nous verrons comment installer l'ensemble des éléments, à savoir l'extension Waves pour VS CODE, une node privée via Docker, le plugin Surfboard etc.

22 février
Utiliser son environnement précédemment installer et comprendre l'ensemble des fonctionnalités de Surfboard pour la création, la compilation et un déploiement rapide de vos smart contract

25 février
RIDE V4 et Waves node 2.0 arrivant sous peu, nous passerons en revue l'ensemble des changements liés à ces nouvelles version, pour RIDE mais aussi pour le protocole Waves.

Suivez nous et posez toutes vos questions sur :

Telegram : https://t.me/wavesdappsFR
Twitter : https://twitter.com/WavesDevFr

https://www.wavesplatform.com
How to customize your Vagrant and VirtualBox machines' folder on Windows ?
Tags: howto, tipsandtricks, automation, programming
Published: 2020-02-12 11:06:40

---
title: How to customize your Vagrant and VirtualBox machines' folder on Windows ?
published: true
date: 2020-02-12 11:00:00 UTC
tags: How to,TipsAndTricks,Automation,Programming
canonical_url: 
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/pq99p54u5uxlfq1eogrh.png
---

Last week, for one of my side projects, I had to use vagrant in order to be able to run some tests on a Chocolatey packages I am currently trying to update.But having a computer almost full, any call to `vagrant up` ended up failing because of my lack of memory space on my main hard drive. 😝

## VirtualBox and Vagrant

A small digression for those who don’t know what VirtualBox or Vagrant are. 😉

[VirtualBox](https://www.virtualbox.org/) is a software made by [Oracle](https://www.oracle.com/index.html), that allows us to virtualize system and to run virtualize system on a machine. This means that you can potentially have run any version of Windows, Linux or Mac on your own machine with this software.

[Vagrant](https://www.vagrantup.com/) is a software made by [Hashicorp](https://www.hashicorp.com/), which simplifies the use of virtualization tools and offer a way to easily run and automate interactions with virtualized environments.

On a windows system, you can install both of them using [Chocolatey](https://chocolatey.org/) with powershell like that:

```
choco install virtualBox
choco install vagrant
```

## Back to our problem

Having virtual machines is nice, but can requires a lot of space.

So we need a way to have [VirtualBox](https://www.virtualbox.org/) and [Vagrant](https://www.vagrantup.com/) them in a different folder than their default one, on your main hard drive.Doing this is easy, since [VirtualBox](https://www.virtualbox.org/) and [Vagrant](https://www.vagrantup.com/) actually gives you the possibilities to change those elements (some people must have had the same problem before 😆 )

To do so, open your powershell terminal in Admin mode and run the following command with your custom folder

```
VBoxManage setproperty machinefolder <your/custom/VirtualBox/folder/>
setx VAGRANT_HOME <your/custom/Vagrant/folder>
```

Personally, here how I used them

```
VBoxManage setproperty machinefolder "D:/VirtualBoxVMs"
setx VAGRANT_HOME "D:/.vagrant_d
```

And now, all I have to do is run `vagrant up` to have my virtual machine running and stored in my other hard drive. 🙂

## Conclusion

[VirtualBox](https://www.virtualbox.org/) and [Vagrant](https://www.vagrantup.com/) are amazing tools with a lot of configuration possibilities, so you can adapt them to your needs and constraints.

I hope this article will give you the information you were looking for.Personally, I needed to write this post so that future me will be able to go back to it whenever he will need to do so 😆

Thank you all for reading this article !And until my next article, have an splendid day 😉
Interview problem: Sick Travelers
Tags: career, challenge
Published: 2020-02-12 10:58:05

**Now, with New Coronavirus situation, this problem gives interesting epidemic simulation!**

![sick travellers problem explained](https://dev-to-uploads.s3.amazonaws.com/i/lp77u9udt1giej0lfm9j.png)

_There is [Palantir Technologies](https://www.palantir.com/) and one of our fellows had been interviewed there (for internship or junior developer position, I assume). He retold me this problem, as a curiosity, proposed to him at interview and suggested to add it as another task at **CodeAbbey**. After some googling I found the problem is known to some extent, so I did as suggested._

[Here is the link to problem at CodeAbbey](https://www.codeabbey.com/index/task_view/sick-travellers)

Supposedly it may take from 30 minutes to 2 hours. But if you'll try solving it - please, share your experience!

## Problem Statement

1. There is some quantity of cities and some quantity of travelers.
2. Every traveler has schedule to visit several cities in certain order, staying 1 day in each (and travelling speedily by night). When schedule ends, traveler just starts again.
3. Each traveler can be `healthy`, `sick` or `recovering`.
4. One who is `sick` will become `recovering` next day.
5. One who is `recovering` will become `healthy` next day.
6. One who is `healthy` will become `sick` next day if today he/she is in the city with someone `sick` or `recovering` (i.e. contagious).

For example look at the picture above. There are two persons and 4 cities. The time is increasing by days from left to right. One person travels between cities `A` and `B` (and is marked by blue lines). Another travels according to `C-B-D` schedule (purple lines).

The first (blue) is sick initially (let's call it day-1) - this is marked by red color. He/she moves to `B` on the day-2 and meets second (purple) here. Blue is recovering (pink) on the day-2, but some of his viruses land on Purple. Thanks to this, Purple becomes sick on day-3 when reaching city D.

Luckily in this example people density is small and both are soon healthy (green) for good. Epidemic doesn't happen.

The task is to simulate this for hundred days or while all become healthy. But we can invent more interesting questions. E.g. to figure out what people density leads to epidemic on average. Or even detect loop in situation change sequence over many days.

_Problem seems to be pretty straightforward, not about some whimsical algorithm, but rather good coding exercise - to write it neatly, choose suitable data structures etc._
Visualizing React-Redux 
Tags: react, redux, reactredux
Published: 2020-02-12 10:48:47

---
title: Visualizing React-Redux 
published: true
description: A pictorial representation of React-Redux
tags: #react #redux #react-redux
---

Hello All,
Based on the article of Valentino Gagliardi (https://dev.to/valentinogagliardi/react-redux-tutorial-for-beginners-learning-redux-in-2018-13hj), I created a visual representation of Redux and React-Redux flow. For me I was always going back and forth to code snippets when learning react-redux. I thought this might help a bit. Feel free to comment and correct me. Thanks.

REDUX SOLO:

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


And...
REACT-REDUX:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ycokkjd3dcskumq2unks.png)
Geofencing Marketing: Targeting Customers through GPS
Tags: challenge
Published: 2020-02-12 10:48:01

[Geofencing marketing](https://www.lemnisk.co/blog/geofencing-marketing/) enables companies to send display ads/offers and other push notifications to customer mobiles whenever they enter/exit a particular location. This is done by creating a virtual geographical boundary by using GPS (Global Positioning System) or RFID (Radio Frequency Identification). 

 Once the virtual boundary is set, marketers can set up triggers that send an app push notification or an SMS or an email alert whenever a mobile device is within the boundary.

Here is an example of how geofence can increase brand reputation and conversions,

Consider a consumer named Ron who visits an Apple store in his city. As he starts looking at products in the store, he receives a mobile notification.

 
“Dear Ron, Welcome to Apple. Now avail a flat discount of 15% on any Apple product via XYZ Bank credit card. Hurry! Limited Period Offer.”

 Ron is excited to see this message and in the next few minutes, his buying intent changes from “Maybe” to “Yes”. 

Ron visited the store with the intention of buying a Macbook. He, however, hadn’t decided if he would make the purchase right away. The personalized offer that he receives on his mobile comes exactly when he contemplates buying the product. He is delighted to get this message and immediately proceeds to buy the product with the bank’s credit card.

Some of the benefits of Geofencing Marketing:

1. Delivers Hyper-personalization to every single user
2. Increase in sales and customer engagement
3. Improves customer behavioral data
Advanced TypeScript Exercises - Answer 2
Tags: typescript, javascript
Published: 2020-02-12 10:24:34

--- series: Advanced TypeScript Exercises ---

In the question I have asked why below snippet doesn't compile
```ts
type User = {
  id: number;
  kind: string;
};

function makeCustomer<T extends User>(u: T): T {
  // Below error, why?
  return {
    id: u.id,
    kind: 'customer'
  }
}
```
At the first look object which is returned by `makeCustomer` is valid `User` type as it has both needed fields defined in the `User`. The crucial thing to understand is that we work here with type variable `T` which extends from `User` but it doesn't mean it is `User`. `T` is assignable to `User`, so it needs to have all fields which `User` has, but, it can have more fields!

Yes and this is exactly the issue, returned object is a `User` and pass all constraints of it, but doesn't pass all constraints of `T` which can have additional fields. We don't know what are those fields though, so in order to fix the typing we should make an object which has all fields of `T`, and we know all fields of `T` are in argument `u`. We can then use spread operator in order to spread all unknown fields to the newly created object. 

```ts
function makeCustomer<T extends User>(u: T): T {
  // no error
    return {
    ...u, // spread all properties of u being T
    id: u.id, // yes redundant line, leaving it for consistency
    kind: 'customer'
  }
}
```
Now we are sure that all fields from `T` will be included in our returned object. But there is also a case where TypeScript has an issue, design issue probably. We can create here situation which will be just a bug, when value will not match the type. Consider that we can make another type which will extend `User`, lets say `Admin`

```ts
type Admin = User & {
  kind: 'admin';
}
```
We can ask if `Admin` extends truly the `User`:
```ts
type IsAdminAUser = Admin extends User ? true : false // evaluates to true
``` 

Ok so `Admin` is a `User`, then we can use `makeCustomer` with `Admin`? Looks that we should as `T extends User` and `Admin extends User`. Lets check:

```ts
const admin = makeCustomer({ id: 1, kind: 'admin' } as Admin)
```
And there is a bug, TS is saying `admin` has a type `Admin` but when we console.log it, the structure is `{id: 1, kind: 'customer'}`, so unfortunately we  got to the situation where TS has wrong assumptions 😩. 

The whole code can be found in [the playground](http://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAqgzhATlAvFA3gKClAlgEwC4oA7AVwFsAjJAbmygGtcSio5hEWBzegX3qYAZmRIBjYLgD2JKBQCGjCAGEyHKRSQAeACpQIAD2ARWcWAkQA+ABRliOgJT2MDAPSvSU-YkRTEDHEQIYDJEWSwcHAA6GLIAGgC8NjIoggTIphY2AHIxNWANJGyGPkxS0EgoAEF8ChZUcyQoADIXHGZWYmz5WpZs-kxMCugASTgaupIq+Ca0CfrDY1NG5AB+KE4yaGIheQAbBCh3fQA3fbJ5YzMCjcQtwbEZDigeyYaFJVV1TURrdCTiABGOKZTpQbq9EjZKB8F5meYkByYR4kOBSPYQKJ7KTcayvFgOWhHDzoAhAkEdNgAIjy3yQVNKQA)

**This series is just starting**. If you want to know about new exciting questions from advanced TypeScript please follow me on [dev.to](https://dev.to/macsikora) and [twitter](https://twitter.com/macsikora).