teleren/devto huggingface dataset:
Reverse an Integer - Code Challenge
Tags: ruby, javascript, challenge, beginners
Published: 2019-06-30 23:07:48


Leetcode Problem 7

### Given a 32-bit signed integer, reverse digits of an integer.

Examples:
Input: -123
Output: -321

Input: 120
Output: 21

Input: 123
Output: 321



At first glance this problem is easy. In Ruby just convert to string, reverse, and convert back to integer and Ruby has all those nice built in functions to do just that and make it easy.

```
def reverse(x)
    
    x.to_s.reverse.to_i

end
```


However, this will not accomodate a negative number as the reverse function does not accomodate then negative. So this is what happens.

```
irb(main):016:0> x = -123
=> -123
irb(main):017:0> x.to_s.reverse.to_i
=> 321

```

What we really want is -321 and one way to accomodate this is to create a variable that indicates whether or not it should be negative and add it if necessary on the return statement.

```
def reverse(x)
    
    neg = x < 0	
    x.to_s.reverse.to_i
    return neg ? -x : x

end

```

Almost there. We have not considered a key part of the problem. It is a 32-bit integer.


Integers can be huge, however, when programming there are limitations. Technically you could have a number that is infinite places long and have it be an integer but that would also break whatever you are working on (hello stackoverflow). So when the question says 32-bit integer what it is saying is the largest binary number with 32 places so...



11111111111111111111111111111111   in base 2 math is equal to

4294967295 in base 10 math.



However, the problem also specifies signed so the first bit is a + or - resulting in 31 1's not 32 so we end up with the magic number as 


2147483648


So the range is -2147483648 to 2147483648 right? But what about 0? Well the positive integer gets it so the range results in


-2147483648 to 2147483647 non-inclusive of those numbers.


To accommodate this we have to check if the integer input is greater or less than those ranges before returning a result.

```
def reverse(x)
    
    neg = x < 0
    x = x.to_s.reverse.to_i
        
    return  0 if (x > 2147483646 || x < -2147483647)
    
    return neg ? -x : x
end
```

If you wanted to not use as many built in functions building out the reverse is always good practice.

```
def reverse(x)
    i = 0
    
    neg = x < 0
    x = x.to_s
    
    x.length % 2 == 0? (half = x.length/2) : (half = x.length/2 + 1)
    len = x.length - 1
    
    while i < half
      temp = x[i]        
      x[i] = x[len - i]
      x[len - i] = temp
      i += 1
    end
    
    x = x.to_i
    
    return  0 if (x > 2147483646 || x < -2147483647)
    
    return neg ? -x : x
end
```


In Javascript we end up with


```
var reverse = function(x) {
    const neg = x < 0
    
    x = Math.abs(x).toString().split("").reverse().join("")
    x = parseInt(x)
  
    if (neg) {
        x = - + x
    }
    
    if (x < -2147483647 || x > 2147483646){
        return 0
    } else {
        return x
    }
}
```

Of course the parseInt can be combined with the line above it but it's a little easier to read on a different line.

Until my next code challenge.
Git Branches
Tags: git, github, discuss, question
Published: 2019-06-30 22:19:20

---
title: Git Branches
published: true
description: In what scenarios should one use branches
tags: git, github,discuss, question
cover_image : https://images.unsplash.com/photo-1556075798-4825dfaaf498?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&ixid=eyJhcHBfaWQiOjEyMDd9
---

This is something that has been bugging me for the better part of my Sunday afternoon. In what scenarios should I use a branch or branches when working on my on git through Github or other existing DVCS? Can I use it when working on personal projects or it is only suitable for collaborative projects?
Reddit or StackOverflow?
Tags: programming
Published: 2019-06-30 22:16:29

---
title: Reddit or StackOverflow?
published: true
description: 
tags: Programming
---

I wanna use Python on VS Code. I love Jupyter Notes but I'd like to try new experiences. I discovered after all questions on Reddit and StackOverflow communities that if we want to use Python on VS Code, we must install Python for Windows (Python 3.7.3) first. Add it to path, open VS Code and install Python Extension. No other Python version will be permitted so that you can't run well codes without 3.7.3 version today. Sadly, nobody answered me that little trick. VS Code did it after a long fight. On Reddit VS Code community, I found much more attention than sleepy StackOverflow high reputation partners. What's happening to StackOverflow? Too big to fail?
Flask REST API: Introduction
Tags: python, webdev, flask, tutorial
Published: 2019-06-30 21:57:39

Most of what I do as a professional developer involves back end services using Python and Flask.  I've tried a bunch of different combinations of methodologies and technologies and come up with a pattern that seems to work well in most cases.  Over the course of this series, I'll do my best to walk you through the different considerations when building web services and explain why I've made the choices that I've made.  By the end, I hope to have both a guide to success for Flask developers and a template that can be used to kickstart new web dev projects.

# Outline
Here are all the topics related to web services that I plan to cover.  I'll give specific detail on how I solve each problem, but I'll try to also give general advice to be applied regardless of the language/framework you're using.  Some of this may change as I write.  I might add things on or leave things off based on interest in comments.  Please let me know if you think I've missed anything here so I can make sure I add it as I start writing!  I also plan to make all the code available on GitHub as I go.

1. Foundation: Building an app that's ready to grow.
    1. Basic, sustainable package structure
    1. Dependency management
    1. Running services locally
    1. Integration with IDEs
    1. Basic unit tests
1. Continuous Integration: Catching mistakes early
    1. Automated tests
    1. Static analysis
    1. Dependency Vulnerabilities
    1. Style checking
1. Authentication: Knowing who is using your app
    1. Safely storing and checking credentials
    1. Using tokens to identify users
    1. Enforcing authentication on all resources
    1. Testing around authentication (mocking/faking)
1. Databases: Storing and accessing data
    1. ORMs
    1. Disposable databases for testing
    1. Migrations (tracking schema changes)
1. API Design: Making your services easy to use
    1. Defining API resources
    1. Basic operations (CRUD)
    1. API spec and dev UI
    1. Testing the API
1. Authorization: Ensuring people only access their data
    1. Framework for expandable permissions
    1. Enforcing authorization checks on endpoints
1. Asynchronous Tasks: Don't slow down your users
    1. Starting async jobs from requests
    1. Running periodic tasks
    1. Email Notifications
1. Preparing for Production: Adding more stability
    1. Production servers
    1. Database technologies
    1. Containers (Docker)
    1. Security headers
    1. Version management (changelog)
    1. Logging
1. Deploying: Getting you app out there
    1. Infrastructure as code
    1. DNS
    1. Load balancing
    1. Managing secrets
    1. Multiple environments
    1. Alarms/notifications when problems occur
    1. Manual and continuous deployment
1. Consuming the API: Actually using the thing
    1. Using the UI
    1. Using API tools (Postman)
    1. Generating client libraries
Consider AWS Batch for Your Next Background Jobs
Tags: backgroundjob, aws, docker
Published: 2019-06-30 21:29:37

---
title: Consider AWS Batch for Your Next Background Jobs
published: true
description: Using AWS Batch to process background jobs
tags: background job, aws, docker
---
A colleague and I are currently in the process of updating an aging service in our stack. The service is pretty well isolated — it takes a bit of input, does a few units of work, then puts the results in a specific S3 bucket with a key provided as part of the input.

Normally I would reach for SQS + EC2 with a homegrown background worker or a community library like shoryuken. However, having a few dozen servers in production already, I wanted a solution that wouldn’t include additional infrastructure I would need to manage.

When I run in to an infrastructure related challenge nowadays, I do a quick search in the AWS console to see what turns up. Sure enough, AWS has a service for background jobs called Batch.

At first glance, it wasn't entirely clear how Batch worked. I Googled a few different keyword arrangements, none of which turned up anything particularly useful; a few articles here and there, but nothing like an in-depth tutorial that covered our particular use case.

After going through the Getting Started Guide, I found that Batch was very simple to set up. Most of the overhead was getting over what a traditional background worker setup looks like.

There are a few characteristics that, collectively, make Batch work well for background jobs.

## Compute Environment
Batch jobs are run in a Compute Environment. This is just an ECS cluster that Batch creates and manages for you. These are the nodes/instances that will run your job.

## Job Definition
Jobs are defined using a Job Definition, which allows you to customize the number of CPUs, memory, and retries, as well as set environment variables and other options, like what default Docker Image you want to use.

We knew we wanted to use Docker Images from the beginning. Our job has a large amount of runtime dependencies, and we thought it best to packages these into an atomic unit. Batch is a great fit, since Batch supports Docker Images.

## Job Queue
Unlike other background job libraries, Batch has its own queueing system — it doesn't rely on SQS or Redis.

Job Queues are tied to a Compute Environment and can have different priorities. Jobs are submitted to Job Queues, which get run by the Compute Environment.

## Job
Jobs are submitted to a Job Queue using a Job Definition. Default arguments set in the Job Definition can be overwritten when submitting a job.

There are a few ways to submit jobs. We submit our jobs in our codebase using the the Batch gem provided by AWS.

There's still a lot more for me to learn about Batch, but I wanted to share my experience using it so far. Feel free to leave a comment if you have any questions.
What's your number one underrated VSCode extension?
Tags: discuss, vscode
Published: 2019-06-30 20:58:41

---
title: What's your number one underrated VSCode extension? 
published: true
description: Let's collect a few underrated, obscure or just awesome VSCode extensipns.
tags: discuss, vscode
---

I have recently seen quite a few articles showcasing VSCode setups. But they're mostly featuring popular plugins most of which I came across alread. 

That's why I'm interested in your favourite obscure, lesser known or just plain awesome plugins. Self promotion welcome! ✨
Game Making with Godot
Published: 2019-07-01 01:44:10

---
title: Game Making with Godot
published: true
tags: 
canonical_url: https://triptych.writeas.com/game-making-with-godot?pk_campaign=rss-feed
---

Part of my vacation time was spent working on a new game making tool called #ittybittyrpg. I'm building it in [Godot](https://godotengine.org/) and I made a lot of great progress. Here's a recent screenshot with Save and Load working, as well as a logo from [Logomakr](https://logomakr.com)

![](https://i.snap.as/gwZdNEu.png)

I have a really interesting idea for IttyBittyRPG where instead of doing things like Twine or Bitsy, as I was originally wanting to do, the idea will be more like you have a fantasy world sticker book, and you create dialog, battles, and levels like you might put stickers in a sticker book. The UI for the editor will be “playful” and then the game itself will be emergent from that.

So, since this is supposed to be about coding, I had to port over the Save / Load code from an older version of [GDScript](https://docs.godotengine.org/en/3.1/) to 3.1.

Code example is [here](https://codeshare.io/alEElB)
Using multiple SSH-keys with git
Tags: notetoself, ssh, git
Published: 2019-06-30 20:24:33

Recently I found myself having to use two SSH keys on my machine to access code repositories hosted on Bitbucket under two different accounts, personal and work. In the end it was not very complicated, but it took me a while to figure out, so I decided to write everything down. :)

The first thing I need is to have both SSH keys on my machine. I already had the personal one, so I generated the second with same `ssh-keygen` terminal command. I had to give it a different file name though, to make sure my personal SSH key isn't overwritten. Once the key is created it should be added to the account that hosts the repositories (in my case Bitbucket account). 

The next step is to create SSH configuration inside `.ssh/config` file. Each record in this file represents specific host (or hosts) and details a set of parameters to be used with it.
Every time the system is establishing SSH connection it will look through this config file and if the URI it is trying to connect to matches one of the Host records, it will use the parameters for this record. It supports many parameters, but I only needed two in this case.

The config is very simple:

  * when trying to connect to `work.bitbucket.org` connect to `bitbucket.org` instead and use credentials from `id_rsa_work` file.
  * in all other cases just use credentials from `id_rsa` file.

```
Host work.bitbucket.org
  HostName bitbucket.org
  IdentityFile ~/.ssh/id_rsa_work

Host *
  IdentityFile ~/.ssh/id_rsa

```

Now the logical question here is where this `work` subdomain of `bitbucket.org` is coming from? When I try to `git pull` from either personal or work repos it goes to bitbucket.org. And the answer is that we can just fake it. Rather than use the real URL of the remote repository we can modify it.

All the parameters of a git repository are stored inside the `.git/config` file. We can print the repo's remote URL by executing `git remote -v` in the terminal. And to modify it we can either edit the config file directly or execute `git remote set-url origin [new_url]`.

So to make the request of a particular repo to match our SSH configuration, we just need to prefix `bitbucket.org` in the repo's URL with `work.`, e.g. `git@work.bitbucket.org:valenber/myrepo.git`.

This way when updating the repo (making pull or push) the system will try to establish SSH connection with `work.bitbucket.org`, it doesn't exist, but this request will never get further than our SSH config file, where it will get redirected to `bitbucket.org` and use the correct SSH key.
Kubernetes for Java Developers - Creating a docker image
Tags: java, docker, kubernetes, containers
Published: 2019-06-30 20:16:53

---
title: Kubernetes for Java Developers - Creating a docker image
published: true
description: Kubernetes for Java Developers
tags: java, docker, kubernetes, containers
series: Java Kubernetes
cover_image: https://thepracticaldev.s3.amazonaws.com/i/efa0toi8knmzcbvbiuj2.png
---
##Welcome back

On [first](https://dev.to/sandrogiacom/kubernetes-for-java-developers-setup-41nk) tutorial of this series, we learn about set up a local kubernetes environment.
At this point, we have a Java application that uses a mysql database running on docker.
To package our application inside a docker image, we need to create a Dockerfile.

##Create a Dockerfile

Dockerfile definition:

```yaml
FROM openjdk:11.0.3-jdk-slim
RUN mkdir /usr/myapp
COPY target/java-kubernetes-0.0.1-SNAPSHOT.jar /usr/myapp/app.jar
WORKDIR /usr/myapp
EXPOSE 8080
CMD ["java", "-Xms128m", "-Xmx256m", "-jar", "app.jar"]
```

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


##Use Make to automate tasks

[Make](https://www.gnu.org/software/make/) is a tool which controls the generation of executables and other non-source files of a program from the program's source files.
We will use make to automate maven and docker commands in this project.
Check your make installation. Type `make --version` on terminal. If none happens, please install make before continue.

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

##Create a Makefile

Creating a Makefile on the same Dockerfile directory.
Check out the complete Makefile on github: https://github.com/sandrogiacom/java-kubernetes/blob/master/Makefile 

The importance parts are:

```bash
build:
	mvn clean install; \
	docker build --force-rm -t java-k8s .
	
run-db:
	make stop-db; \
	make rm-db; \
	docker run --name mysql57 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_USER=java -e MYSQL_PASSWORD=1234 -e MYSQL_DATABASE=k8s_java -d mysql/mysql-server:5.7
	
run-app:
	make stop-app; \
	make rm-app; \
	docker run --name myapp -p 8080:8080 -d -e DATABASE_SERVER_NAME=mysql57 --link mysql57:mysql57 java-k8s:latest		
```

**build:** Run maven and create a docker image with the name "java-k8s"
**run-db:** Start a new mysql database container
**run-app:** Start a new application container

In this order, type:
```bash
make build
make run-db
make run-app
```
**Obs:** Wait 30 seconds between `run:db` and `run:app` to make time to start up database.

To see logs of applicaton, type:
```bash 
docker logs -f myapp
```

And `CTRL+C` to exit log mode.

Type `docker ps` to see the containers running

**Check**
http://localhost:8080/persons

![](https://thepracticaldev.s3.amazonaws.com/i/2he81bpf770359qmwfmf.png)

To stop applicaton and database, type:
```bash 
make stop-app
make stop-db
```

Please clone the complete demo app at:

https://github.com/sandrogiacom/java-kubernetes

Have fun!

See you on the next part. Deploy your app into kubernetes cluster.

[![](https://thepracticaldev.s3.amazonaws.com/i/gmrz82bjwhej1f1iqb1e.png)](https://twitter.com/sandrogiacom)
Livestream - Dev.to Challenge Vowel Count in Rust
Tags: challengeanswer, rust, livestream
Published: 2019-06-30 19:39:48

Here is a mostly complete live stream of my doing one of the daily challenges that dev.to has been hosting! My live stream cut out just before my last refactor :facepalm: so to see the finished code to check out the GitHub at:

https://github.com/coreyja/dev-to-challenges/blob/master/3-vowel-counter/rust/src/lib.rs

This video is also availible in HD on Vimeo:
{% vimeo https://vimeo.com/345335134 %}
I need help!
Tags: php, help
Published: 2019-06-30 18:08:22

So me and my friend are making an RPG website for fun and we've run into a problem. We suck at PHP. We are so bad that we dont even know how to pull out one value from an SQL query. Please can someone help us get the 'name' value from this SQL query in PHP7. Thanks!

<?PHP
session_start();
$email = $_POST['email'];
$password = sha1($_POST['password']);

$con = mysqli_connect('CENSORED','CENSORED','CENSORED');
mysqli_select_db($con, "BATTLE");

$q = "SELECT * FROM players WHERE email == '$email'";
$result = mysqli_query($con, $q);
$num = mysqli_num_rows($result);
if($num == 0){
	$_SESSION['email'] = $email;
	// GET THE NAME!!
}
?>
Video: How to create data visualizations that tell a story
Tags: datavisualization, meetuptalk
Published: 2019-06-30 17:27:49

---
title: Video: How to create data visualizations that tell a story
published: true
description: A talk from Papers We Love Berlin meetup June 19th
tags: data visualization, meetup talk
---

It's easy to make charts nowadays. However, just throwing in some data and selecting a chart type won't fly far. William Cleveland's research from the 80s in the field of graphical perception and data visualization is a great starting point for people who want to make charts that are understandable and optimal in conveying the message to the reader.

In my talk, I'll be walking you through the important pieces of Cleveland’s paper Graphical Perception and Graphical Methods for Analyzing Scientific Data, as well as sharing some good and bad visualizations from the real life and share the best practices of data visualization.

This talk was given in [Papers We Love Berlin](https://www.meetup.com/Papers-We-Love-Berlin/events/262026955/) meetup on June 19th by [Juha-Matti Santala](https://hamatti.org)
Weekly Coding Challenge - Week #16 - Notifications
Tags: challenge, html, css, javascript
Published: 2019-06-30 17:12:16

---
title: Weekly Coding Challenge - Week #16 - Notifications
published: true
description: Week #16 of the Weekly Coding Challenge program - Notifications
tags: challenge, html, css, javascript
canonical_url: https://www.florin-pop.com/blog/2019/06/how-to-create-a-notification-box/
cover_image: https://www.florin-pop.com/static/85554c451b77d5ceae7a746fc7a0240b/ff993/how-to-create-a-notification-box.png
series: Weekly Coding Challenge
---

Theme of the week: **Notifications**

### Description

The notification component is used in a web/mobile app when you want to notify the user that something happened based on his action - "successfully completed registration", "error on an input field", "confirmation of deletion of an item", etc.

## Useful Resources

Check out my submission for this challenge: [Notifications Box](https://www.florin-pop.com/blog/2019/06/how-to-create-a-notification-box/).

See all the submissions in this [Codepen Collection](https://codepen.io/collection/AQkvwd/).

Are you interested in joining the challenge? :smiley: Read [The Complete Guide](https://www.florin-pop.com/blog/2019/03/weekly-coding-challenge/) to find out how. Don't forget to share your creation! :wink:

Happy Coding! :innocent:
My opinionated & minimalist JavaScript full-stack starter-kit
Tags: showdev, fullstack, javascript, webdev
Published: 2019-06-30 17:12:14

## Hey folks!

based on my previous experience of setting up multiple JavaScript full-stack architectures, I created my own opinionated & minimalist boilerplate:

[JavaScript Full-Stack Starter Kit](https://github.com/mi-kas/fullstack-starter-kit) 🚀

It's based on frameworks such as Node.js, Express, MongoDB, Mongoose & Swagger for the backend and React (built with create-react-app) for the frontend.

### Features

- Node.js backend with Express
- Swagger API specification & validation
- MongoDB database
- React frontend
- Next generation JavaScript agnostic setup with Babel
- Multi-container Docker setup
- Easy Docker orchestration with handy Makefile commands
- Mono-repo approach


Check it out and let me know what you think about it!

Cheers,
Michael ✌️
Which language should I choose
Tags: backend, kubernetes, cloud, infrastructure
Published: 2019-06-30 16:30:54

---
title: Which language should I choose
published: true
description: Which language should I choose
tags: Backend, Kubernetes, Cloud, Infrastructure
---

Hi guys! So I am starting up on a new application and want to discuss which programming language should I choose to build my server side infrastructure on.

The architecture will be based on containers and Kubernetes for future scalability. The idea of the application is very simple with a few CRUD endpoint. It involves video storage, voice transcriptions, video processing and natural language processing for mood and opinion mining and a lot of server side text manipulations.

Now I know if there is ML involved I should probably choose Python and call it a day but that is exactly what I want to discuss. A lot of these services are provided by cloud solutions and we want to use them initially and then build our own solutions once we have a good amount of datasets in the coming years.

So, my question is how viable is Golang for purposes like string manipulation and AI? I am leaning towards Golang because of its seamless integration in a scalable cloud infrastructure. I have heard a lot of good things about it being super fast and saving deployment costs in cloud infrastructure that charge for computation time.

For more context, I have already built backend applications with Node and Python combined in the past and achieve good results with it but it wasn't built to scale and was a concept rather than a full fledged startup with investment.

Looking forward to your valuable input.