teleren/devto huggingface dataset:
Processing File Uploads with IBM Cloud Functions
Tags: openwhisk, serverless, ibmcloud, python
Published: 2020-07-18 18:33:00

I've been doing a lot with IBM Cloud Functions recently. So far I've always been passing up simple query string values or json-encoded data. But what if you want to upload an actual binary file? The usual way, in the web world, is to use the `multipart/form-data` content type. 

But how does Apache Openwhisk (that IBM Cloud Functions are based on) handle this?

If you set the function to `raw` type, rather than getting the JSON-decoded values passed to your function as a dictionary, you get a dictionary that gives you the raw data. The data itself if base64 encoded in `__ow_body` and the headers in `__ow_headers`.

There are several ways to process this in Python. The `requests_toolbelt` package has a `MultipartDecoder` class. But I'm going to use one from the `cgi` library that is included in Python itself:


```python
from cgi import parse_multipart, parse_header
from io import BytesIO
from base64 import b64decode

def main(args):
    c_type, p_dict = parse_header(args['__ow_headers']['content-type'])
    decoded_string = b64decode(args['__ow_body'])
    p_dict['boundary'] = bytes(p_dict['boundary'], "utf-8")
    p_dict['CONTENT-LENGTH'] = len(decoded_string)
    form_data = parse_multipart(BytesIO(decoded_string), p_dict)

    # Do something with the data. In this simple example
    # we will just return a dict with the part name and 
    # length of the content of that part
    ret = {}
    for key, value in form_data.items():
        ret[key] = len(value[0])

    return ret
```

The `parse_multipart` method expects to find a header called `CONTENT-LENGTH` so we need to add that in to our headers before passing it to the parser.

To create this cloud function, we need to set `--web raw` flag to tell Openwhisk not to try and parse the payload as JSON for us:

```sh
% ibmcloud fn action create upload upload.py --web raw
```

We can then get the URL for it:

```sh
% ic fn action get upload --url
ok: got action upload
https://eu-gb.functions.appdomain.cloud/api/v1/web/1d0ffa5a-835d-4c40-ac80-77ca4a35f028/upload
```

And we can then call it using cURL and upload some data to it. In this case we are passing both a simple string value (`foo`) and the contents of a binary WAV audio file:

```sh
% curl -F id=foo -F audio=@test.wav  https://eu-gb.functions.appdomain.cloud/api/v1/web/1d0ffa5a-835d-4c40-ac80-77ca4a35f028/upload.json   
{
  "audio": 3840102,
  "id": 3
}                    
```

It seems that IBM Cloud functions has a limit of 5MB for the payload. I guess anything larger than this and you'd be better to upload it to IBM Cloud Object Storage (COS) then pass the URL of that uploaded item to the cloud function.
A terminal-based client for Clockify time tracker
Tags: go, clockify, cli
Published: 2020-07-18 18:28:43

---
title: A terminal-based client for Clockify time tracker
published: true
description: 
tags: golang, clockify, cli
cover_image: https://raw.githubusercontent.com/ABGEO/goclockify/1.x/assets/demo.gif
---

Here's my first work on Golang.
goclockify - a terminal-based client for Clockify time tracker.

https://github.com/ABGEO/goclockify
My experience of learning with Udacity
Published: 2020-07-18 18:07:02

Recently I took a Python free course and a UX nanodegree on Udacity. Here what I liked and disliked about the platform.

<a href="https://www.udacity.com/">Udacity</a> is one of the leading online education institute founded by Sebastian Thrun an ex-Stanford professor and also the founder of GoogleX. 

Nanodegrees are certifications which are cost and time-effective alternative to traditional degrees as they offer focussed content on high-tech topics.
Apart from high-quality content and a good UI, there are certain features where Udacity impressed me. 

The first one was mentorship. You are assigned a mentor after you enroll in it. The work of the mentor is to guide you throughout the program. Personally I didn’t make use of my mentor much, but I can say having a mentor is life-saving. Feedback from your mentor helps in building your professional network and also your competency. 

The second feature I liked was their community forums. 
It helped me to a question, seek some advice, get support, and I could even answer questions from other students. 

Lastly, I was impressed by their career services. While learning I found that Udacity cares about their students by providing some extra perks. Those extra perks can help you land a job. 

All students receive their extensive career support, and they make sure you are ready to launch your job search with career coaching, interview prep, and a network of tech companies. 

Well, there are a certain drawbacks of learning from Udacity. Firstly, nanodegrees are expensive. When I researched,I found that partnership with organizations like Google Amazon Salesforce, providing mentorship to every student and the help that you get in the career services adds up to the cost. 

Anyways after completing their python course, I am planning to enroll in their data scientist course as I have read some interesting <a href="https://www.onlinecourseing.com/udacity-nanodegree-review/">Nanodegree reviews</a> 

Well, I hope this article gives you some perspective about the platform.
管理の悩み・その壱
Published: 2020-07-18 18:06:53

管理をしていて「この人に仕事頼むのは怖いなー」と思う要因の一つとして、「見積もりの甘さ」がある。

要因は他のもあるけど。

「見積もり」といっても、工数の見積もりではなくて、計算量やデータ量の見積もり。

エンジニアを何年もやっていると作れないものはほとんどなくなってくるんだけど、その処理にかかる時間やデータ量を意識しながら作るのは一段レベルが違うらしい。

作ったものがどれくら時間がかかりそうか、どのくらいメモリを消費しそうか、長期的にはどのくらいのデータ量に落ち着きそうか。

見積もりが難しいこともあるかもしれないが、常に意識できるようでないと長いことエンジニアとして仕事を続けるのは難しい、、、少なくとも、管理側からは仕事を頼みづらくなってしまう。

難しいものについては酌量の余地があるものの、自明のものに対して全く意識せずにリークするようなものを作るエンジニアに対して、仕事を依頼できるかと言ったら、、、そうではない。

One of the factors that make me think "I'm afraid to ask this person to do the job" when I'm managing it is the lack of a good estimate. There's a "-

There are other factors, though.

When I say "estimates," I don't mean estimates of man-hours, but estimates of the amount of calculations and data.

After years of engineering, there's almost nothing left to process that you can't make. It's a different level to make it while being aware of the amount of time and data it will take.

You have to think about how long it's going to take you, how much memory it's going to consume, and how much data it's going to consume in the long run. Are you likely to settle for about the same amount of data?

It may be difficult to estimate, but if you can't always be aware of it, you'll be an engineer for a long time. It's hard to keep a job as, or at least make it harder for the management to ask for it. .

Although there are extenuating circumstances for the difficult ones, the leak is completely unaware of the obvious ones You can't ask an engineer who makes something like that to work for you.
Checking whether a number sequence has two or four digits in Python
Tags: python, regex
Published: 2020-07-18 17:51:48

---
title: Checking whether a number sequence has two or four digits in Python
published: true
description: Using Python Regular Expressions to check whether that the year element of the date string either has two or four digit years
tags: python, regexp
---

I had an interesting problem the other day which I thought would be pretty trivial but actually turned out to be a bit of a pain.

UK dates are often written in the following formats: 

* dd/mm/yy
* dd/mm/yyyy

The script I was writing needed to do a quick and dirty validation that the string input was in one of the valid forms before using a [proper library](https://github.com/dateutil/dateutil) to actually read the date.

The first regular expression I tried turned out to not be valid in Python so I started using the excellent [Pythex](https://pythex.org/) online tool to help craft something that would work.

In the examples at follow add the start and end anchors mentally, I've omitted them.

My first naive attempt didn't work at all:

```python
\d{2}/\d{2}/[\d{4}|\d{2}]
```
This matched if the year was one digit long. I thought maybe it was because I had the longer sequence at the start but swapping around the or (the pipe symbol) doesn't matter.

The first issue here is the square brackets which is actually a character sequence selection. I'd simply forgotten what it meant so I think all that was matching was a single digit character as the entire square bracket evaluates to a single character.

Okay...

```python
\d{2}/\d{2}/\d{2}|\d{4}
```

This kind of works except that it doesn't match four digit dates but anything that has at least two digits so three digits years are fine if you don't have the line boundary.

As the *or* is evaluated left to right my first formulation was actually correct.

```python
\d{2}/\d{2}/\d{4}|\d{2}
```

And for the tl;dr cut and paste version

```python
r'\A\d{2}/\d{2}/(\d{4}|\d{2})\Z'
```

I didn't expect this to be such a struggle, I was kind of the old adage of trying to fix a problem with a regular expression and ending up with two problems...
Return statement in PHP
Tags: php
Published: 2020-07-18 17:50:01

The return statement is an important language constraint to return the value to the caller. In this tutorial, we’ll see different uses of return statements in PHP with examples.

I know that there is nothing special in creating this post only for return statement. But believe me, this will create new opportunities of using return statement in different part of the codebase and we’ll understand how dynamically we can use it in our day to day coding.

In most of the scenarios, we have seen this return statement inside the function definition only.

https://programmingdive.com/different-uses-of-return-statement-in-php/
Spice up your page loads with subtle animations!
Tags: css, webdev
Published: 2020-07-18 17:48:04

In today's article I wanted to share a little twist that I like to include on some of my websites to enhance the overall user experience - adding subtle animations on **page load**.

I think this really adds to the website, and in some way, makes it feel a little snappier than it actually is.

### HTML
You'll want to pick a portion of your site (usually the main content) to apply the animation to, for example:
```html
<div class="container">
    <!-- body content here -->
</div>
```
### CSS
For the CSS, we need to apply an animation to the `.container` class, and then specify the keyframes for it. Let's identify the keyframes with `fadeIn`:
```css
.container {
    animation: fadeIn 0.5s;
}

@keyframes fadeIn {
    from {
        opacity: 0.25;
        transform: rotateY(-10deg);
    }

    to {
        opacity: 1;
        transform: rotateY(0deg);
    }
}
```
As we can see with this simple `@keyframes` rule, we only *slightly* adjust the initial rotation and opacity for the element - you can choose whichever properties you like here but make sure it's not too much. Also, a snappy duration of `0.5s` tends to work quite nicely.

That's it! Load up the page and see what it looks like 😁

### Video Tutorial
If you prefer this tutorial in the form of video, check it out below on my YouTube channel, **dcode**.
{% youtube zWB219zf1og %}
Recreate the IOS14 Translate App [ Part 1 ]
Tags: swift, ios
Published: 2020-07-18 17:46:53

Hey there, 

With the recent launch of IOS 14, one of the things that caught my eye is the new translation app. I love how minimal it is. The animations are relaxing and soothing. I recreated the app and have captured the details below. Hope you can learn something from this post. If you have any ideas, feel free to drop a comment.

# Breakdown

Let’s start with a breakdown of the official translate app. 

1. There are 2 tabs, one named translate and the other favourites. 

2. Translate tab is divided into 4 sections.

3. At the top we see two buttons which are used to select the from and to languages.

4. The centre container displays the raw & translated text along with their respective languages.

5. The bottom section contains a text field with a placeholder “Enter text”

6. A mic button is overlaid on the bottom section. When clicked, this opens a listening view which has a static text at the top and a beautiful animation at the bottom.

7. Favourites tab displays recent and starred translations

# Language Buttons

Let’s start from the top. These are simple buttons which displays a sheet when clicked.

1. We use a state variable isPresented to show / hide the sheet.
2. We wrap the two buttons with HStack in order to display them on the same row.
3. .frame(minWidth: 0, maxWidth: .infinity) allows our buttons to take up all the available space.

![Buttons](https://dev-to-uploads.s3.amazonaws.com/i/ebrfvs6n7pl26tn8di6c.png)

# Translation View

Let's start with the raw text first. These are two Text elements wrapped in a VStack. Since the text is aligned to the leading, we set the alignment property of VStack as .leading. The translated text is also created in the same way. SystemTeal is applied as a foreground colour to the translated text.

The two VStacks are wrapped in a VStack with spacing property set to 20. We also add a divider between the two inner VStacks. This creates a separation between the two sections.

![Translation](https://dev-to-uploads.s3.amazonaws.com/i/kcszg3lpj6kw5iu06z9s.png)

# Mic

We use a state variable which we will use to show / hide the listening view. This button activates the listening view on click.

![Mic](https://dev-to-uploads.s3.amazonaws.com/i/h9mtsvxzlcz1fnj7m33m.png)

That wraps up part 1. In the next post we will talk about the editor, sheet expand animation and the listening animation.

You can browse the code here - https://github.com/vijaywargiya/Translate-SwiftUI

Hope you enjoyed reading this post 😊
My Sinatra MVC Project
Published: 2020-07-18 17:45:31

For my Sinatra MVC project, I created an online closet application. This CMS application allows a use to add items into an online closet with a clothing type, brand and size. The relationship between items and users is a has many/belongs to relationship. So an item belongs to a user and a user has many items. I thought this was a great way to meet the requirements the project has.

This morning I was looking over my project and was extremely proud of the application I built. I thought about how 3 months ago I have never coded anything ever and this week I was able to build a fully functional MVC application. I feel like this is a great accomplishment and milestone of my Software Enginer journey that makes me super excited to dive into Rails after this upcoming break!
Apollo Client 3.0 - Reactive Variables in Local State
Tags: graphql, javascript, webdev, architecture
Published: 2020-07-18 17:34:32

I have just wanted to share one cool thing, which was recently announced with the premiere of **Apollo Client 3.0** - **reactive variables** in **local state**.

I think it will insanely improve developer's experience when implementing local state using Apollo.

Below great example from the docs:

# 1. Define the query
Create local state variable called **cartItems**

```javascript
export const GET_CART_ITEMS = gql`
  query GetCartItems {
    cartItems @client
  }
`;
```

# 2. Create reactive variable

```javascript
export const cartItemsVar = makeVar([]);
```

# 3. Define policy for the local state field
Use created reactive variable as the source of **cartItems** local state field

```javascript
export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        cartItems: {
          read() {
            return cartItemsVar();
          }
        }
      }
    }
  }
});
```

# 4. Create component, which will update reactive variable

```javascript
import { cartItemsVar } from './cache';
// ... other imports

export function AddToCartButton({ productId }) {
  const cartItems = cartItemsVar();
  return (
    <div class="add-to-cart-button">
      <Button onClick={() => cartItemsVar([...cartItems, productId])}>
        Add to Cart
      </Button>
    </div>
  );
}
```

# 5. Create component, which will query for local state field

```javascript
export const GET_CART_ITEMS = gql`
  query GetCartItems {
    cartItems @client
  }
`;

export function Cart() {
  const { data, loading, error } = useQuery(GET_CART_ITEMS);

  if (loading) return <Loading />;
  if (error) return <p>ERROR: {error.message}</p>;

  return (
    <div class="cart">
      <Header>My Cart</Header>
      {data && data.cartItems.length === 0 ? (
        <p>No items in your cart</p>
      ) : (
        <Fragment>
          {data && data.cartItems.map(productId => (
            <CartItem key={productId} />
          ))}
        </Fragment>
      )}
    </div>
  );
}
```

# Summary

After updating the value of reactive variable all queries, which relies on **cartItems** local state field will be automatically update. That's awesome!

[Link to the docs](https://www.apollographql.com/docs/react/local-state/managing-state-with-field-policies/#storing-local-state-in-reactive-variables)
Install Spacemacs on Windows
Tags: opensource, productivity
Published: 2020-07-18 17:32:29

# General Install

1. Download the .zip archive by following the Windows instructions on the [GNU Software Website](https://www.gnu.org/software/emacs/download.html). I decided to go with the most recent version at this time for windows (emacs 26.3).

2. Move the .zip to wherever you would like to have emacs installed and extract all (either 7zip or the native windows unzip in file explorer will work)

3. Once emacs is unzipped, navigate to the `emacs-<version>/bin` directory in file explorer, copy the path (by clicking the the top bar and copying) so we can add it the the path

4. Open up environment variables, find the system path environment variable (the ones on the bottom), click edit, then add, and finally paste the emacs path.

5. For easier access to open emacs, navigate back to the bin folder and find the `runemacs.exe` file; right click on it and select send to > desktop(create shortcut) and create a shortcut on your desktop to start emacs easily.


#### Congratulations Emacs is installed (and possibly ready to use?)
I'm am going to go a bit further and install spacemacs as the config because it gives a nice base to work off, provides easy extension points, and I personally prefer vim style navigation and editing as it is what I started on (as well as being easier on the wrist most of the time)

# Install And Configure Spacemacs

1. Visit the [Spacemacs website](https://www.spacemacs.org/#)

2. If you have opened emacs, locate your `.emacs.d` file, which should live in `%USERPROFILE%\appdata\roaming\.emacs.d`, and delete it. Back it up or add it to source control if you want it for future use.

3. Run the following command, replacing %USERPROFILE% with the path to your appdata folder; In my case `C:\Users\zach\appdata\roaming`

```
git clone https://github.com/syl20bnr/spacemacs C:\%USERPROFILE%\appdata\roaming\.emacs.d
```
This will put the spacemacs config in the .emacs.d folder.

4. Finally, open up emacs and run through configuration to get your preferences set up and installed.

5. From here, the [Spacemacs docs](https://www.spacemacs.org/doc/DOCUMENTATION.html) give lots of ideas on how to customize and extend your editor and capabilities within emacs.


### Useful links
* [Spacemacs](https://www.spacemacs.org/#)
* [Gnu Emacs](https://www.gnu.org/software/emacs)

Link To Original Post:
https://www.ballcapz.dev/blog/spacemacs-windows-install/
Idempotence in API design
Tags: rest, api, softwaredesign, node
Published: 2020-07-18 16:54:05

When you develop any kind of API, for some reason, **idempotence** it's an aspect that usually goes unnoticed, but indeed that aspect could make more robust and safe your piece of software. Let me explain it.

APIs based on REST use HTTP to communicate with the different clients. So, HTTP has a property called __**safe**__; an HTTP request it's __safe__ if doesn't mutate the application state. Consider the table below.

| **HTTP verb** | **Common use**      | **Safe** |
| ---------- | ------------------ | ---------- |
| GET        | Get resources   | Yes         |
| POST       | Add resources   | No         |
| PUT        | Modify resources | No         |
| PATCH      | Modify resources | No         |
| DELETE     | Delete resources  | No         |

Having said that, what's **idempontence**? Idempotence make that multiple identical requests has the same effect as making a single request, minimizing or preventing observable side effects, if you're a functional programming enthusiast, a good analogy could be **pure functions**. Mathematically speaking, consider the function:

```
f(x) = x^2 + 2
```

If we say `x = 2`, no matter how many times use the function, the result always will be `6`. Now, this could be seen in programming, for example in the JavaScript case, `Math.cos(x)` always return the same value of x. The REST specification indicates that methods **GET**, **PUT**, **DELETE** should be idempotent. 

So, how can implement idempotence in our projects?

There's no perfect recipe, but REST has some features that can help us:

* The header `If-None-Match: *` when it is created or updated a resource, this to avoid identifier collisions and return `412 Precondition failed` if the operation fails.
* The header `ETag: {etag-hash}` in the resposponses of **GET** methods.

But we can learn from big companies like **Stripe**, they have a simple implementation for their APIs, they make that clients generate a random and unique hash (like UUID) and attached in a header called `Idempotency-Key` for every request. This can be stored, in cache engines for example, like Redis or Memcached and handled like one unique request.

Maybe never have the need to implement this, but it's important to know that exists and when you facing a similar problem, look back and consider if idempontence could solve the problem.
Criando Sistema de Imóveis com Next.js Reactjs Typescript [4] - Prettier, styled-icons, react-sticky-box, GlobalStyle
Published: 2020-07-18 16:47:06


Adicionei algumas configurações adicionais para o editor (.editorconfig, .prettierrrc) olha lá o repositório. 

1- Instalar Icones e lib para responsividade
```javascript
yarn add styled-icons react-sticky-box
```

2-Em tsconfig.json desabilitar o "isolatedModules": false

3-No root do projeto vamos criar uma pasta src/styles com o arquivo GLobalStyles.ts, arquivo padrão com zerando css exemplo de projeto da Rocketseat: https://github.com/Rocketseat/youtube-clone-twitter/blob/master/src/styles/GlobalStyles.ts

```javascript
import { createGlobalStyle } from 'styled-components';

export default createGlobalStyle`
  * {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    color: var(--white);
  }
  html, body, #root {
    max-height: 100vh;
    max-width: 100vw;
    width: 100%;
    height: 100%;
  }
  *, button, input {
    border: 0;
    background: none;
    font-family: -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Ubuntu, Arial, sans-serif;
  }
  html {
    background: var(--primary);
  }
  :root {
    --primary: #000;
    --secondary: #15181C;
    --search: #202327;
    --white: #D9D9D9;
    --gray: #7A7A7A;
    --outline: #2F3336;
    --retweet: #00C06B;
    --like: #E8265E;
    --twitter: #33A1F2;
    --twitter-dark-hover: #011017;
    --twitter-light-hover: #2C8ED6;
  }
`;

```

Em nosso index.tsx importamos e usamos GlobalStyles
```javascript
import Head from 'next/head'
import styled from 'styled-components';

import GlobalStyles from '../src/styles/GlobalStyles';

const Title = styled.h1`
  color: red;
`;

export default function Home() {
  return (
    <div className="container">
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main>
        <Title>Criando Sistema de Imóveis com Next.js Reactjs Typescript Styled-Components [Part 3] - Configurando Styled-Components</Title>
      </main>

      <footer>

      </footer>

      <GlobalStyles />
    </div>
  )
}

```