teleren/devto huggingface dataset:
Cloning an item on drag using interact.js
Tags: interactjs, javascript
Published: 2020-03-16 18:29:43

---
title: Cloning an item on drag using interact.js
published: true
date: 2020-03-16 18:29:00 UTC
tags: interactjs, javascript
canonical_url: https://www.emgoto.com/interactjs-clone-on-drag/
cover_image: https://www.emgoto.com/interactjs-clone-on-drag-dev.png
---

If you're looking for a JavaScript drag and drop library that provides snapping to grids, or need to make sure items can only be dropped in a specific zone, [interact.js](https://interactjs.io/) provides these capabilities out of the box!

You may come across a scenario where you need an item to be cloned when you start dragging it - e.g. if you are building a map creator that lets you drop multiple of the same icon onto it.

Check out the code below, or you can also [view a working Codepen](https://codepen.io/emgoto/pen/wvamoRG).

```js
// This stores the position of the current item being dragged
const position = { x: 0, y: 0 };

interact(".item")
  .draggable({
    // By setting manualStart to true - we control the manualStart.
    // We need to do this so that we can clone the object before we begin dragging it.
    manualStart: true,
    listeners: {
      move(event) {
        position.x += event.dx;
        position.y += event.dy;
        event.target.style.transform = `translate(${position.x}px, ${position.y}px)`;
      }
    }
  })
  // This only gets called when we trigger it below using interact.start(...)
  .on("move", function(event) {
    const { currentTarget, interaction } = event;
    let element = currentTarget;

    // If we are dragging an item from the sidebar, its transform value will be ''
    // We need to clone it, and then start moving the clone
    if (
      interaction.pointerIsDown &&
      !interaction.interacting() &&
      currentTarget.style.transform === ""
    ) {
      element = currentTarget.cloneNode(true);

      // Add absolute positioning so that cloned object lives
      // right on top of the original object
      element.style.position = "absolute";
      element.style.left = 0;
      element.style.top = 0;

      // Add the cloned object to the document
      const container = document.querySelector(".container");
      container && container.appendChild(element);

      const { offsetTop, offsetLeft } = currentTarget;
      position.x = offsetLeft;
      position.y = offsetTop;

      // If we are moving an already existing item, we need to make sure
      // the position object has the correct values before we start dragging it
    } else if (interaction.pointerIsDown && !interaction.interacting()) {
      const regex = /translate\(([\d]+)px, ([\d]+)px\)/i;
      const transform = regex.exec(currentTarget.style.transform);

      if (transform && transform.length > 1) {
        position.x = Number(transform[1]);
        position.y = Number(transform[2]);
      }
    }

    // Start the drag event
    interaction.start({ name: "drag" }, event.interactable, element);
  });
```
Validate if multiple IDs exist and store as JSON with Laravel
Tags: laravel, validation
Published: 2020-03-16 18:14:47

I had a table called contact_times with these values:

"id", "name"
"1",	"Mornings"
"2",	"Lunchtime"
"3",	"Afternoons"
"4",	"Evenings"

A user can check several times when he would like to be contacted. Frontend sends the selected IDs as array to backend:
```
'contact_time_id' => [1, 3]
```
And they get saved as a JSON string in the contact_time_id column of the contact table.

How do we verify that (although unlikely to happen in this scenario), frontend doesn't send back IDs of options that don't exist in the contact_times table?

We can create a request class in Laravel and add a validation rule. 

```
class ContactStoreRequest extends FormRequest
{  
    public function rules()
    {
        return [
            'contact_time_id.*' => 'exists:contact_times,id'
        ];
    }
}
```
Note the asterisk that can be used to check for multiple values, e.g. an array.

To save the array as JSON in the contacts table, we add $casts in the contact model:
```
class Contact extends Model
{
    protected $casts = [
        'contact_time_id' => 'json',
    ];
}
```

As is often the case with Laravel, if you know how, you can make the code elegant and concise.
GitHub has acquired npm
Tags: news, javascript, npm, github
Published: 2020-03-16 18:01:34

{% tweet 1239597483493175296 %}

> Invest in the registry infrastructure and platform. The JavaScript ecosystem is massive and growing quickly. It needs a rock-solid registry. We will make the investments necessary to ensure that npm is fast, reliable, and scalable.
> Improve the core experience. We will work to improve the everyday experience of developers and maintainers, and support the great work already started on the npm v7 CLI, which will remain free and open source. Some bigger features that we’re excited about are Workspaces and improvements to the publishing and multi-factor authentication experience. 
> Engage with the community. We will actively engage with the JavaScript community to get your ideas and help us define the future of npm.

Nothing overly substantive in the announcement. npm has had a lot of issues in the past few years in direction and management. I am sure the price of npm was well below their peak.
Check if a JavaScript Object is Empty
Tags: javascript, react, node, codenewbie
Published: 2020-03-16 18:00:20

---
canonical_url: https://bonsaiilabs.com/check-empty-object
---

This video covers a common question JavaScript developers come across.
How do I test for an empty JavaScript object?

Code is available at https://bonsaiilabs.com/check-empty-object

{% youtube pQ6KQcgU-4M %}

Subscribe for more videos on JavaScript with Visualization: https://www.youtube.com/channel/UC0yZBnRsD9JRqLXBkfGym0Q?sub_confirmation=1
Crowd brainstorm covid-19
Tags: osscovid19, discuss, opensource
Published: 2020-03-16 17:56:43

---
title: Crowd brainstorm covid-19
published: true
description: How could we be any use? 
tags: OSS COVID-19
---

So guys, let's face it. Covid-19 is a pandemic. We can't change that fact. But how can we as a bunch of smart people be of any help? Can we contribute to a specific project, can we start a new one?

Ideas which are vaguely flying around in my head: 

- tool to help organize help for those in risk groups (like elderly people, people with lung deseases, etc.) 
- Create a info portal which uses AI to extract info from trustworthy news outlets or in a more pragmatic way a cms where these information get aggregated by humans

Does anybody else have the urge to do something or an idea to come up with to help the world overcome this crisis? This is *not* the cry for a business pitch so i am looking for some open source work
A simple COVID-19 dashboard I made on the weekend
Tags: webdev, javascript, showdev
Published: 2020-03-16 17:55:18

I made a simple dashboard over the weekend to monitor the Coronavirus situation.

It all started last friday and I learned a lot on this journey. First I started to mess with `jq` to convert the CSV files in a more friendly format (JSON). Then I figured that `D3.js` and `Lodash` can parse CSV files and transform the data on the fly. 🤯

Soon I had a beautiful and less stressful chart. 🥳

https://covid.ninja/

Let me know what you think. I will try to add a few features on the next hours/days.

Thank you!
#COVID2019 is setting up work from home quickly and effectively
Tags: discuss
Published: 2020-03-16 17:20:19

---
title: #COVID2019 is setting up work from home quickly and effectively
published: true
tags: discuss
---
Many organisations in India first time setting up an environment to facilitate work from home for there employees in mass. Other side employees are also preparing themselves to work remotely.
I think this will promote remote work in future.
Managing Rust binary files and Git when using rustc
Tags: rust, git
Published: 2020-03-16 16:54:08

## What is rustc?

`rustc` is the compiler for Rust. When we use `cargo` to compile our source files it is actually calling `rustc` to do all the hard work.

Don't believe me? :D Use this command to see the full output from a call to `cargo`.

`cargo build --verbose`

`rustc` outputs the compiled binary file to the same directory as it is called in.

`rustc hello.rs` will create the binary file `hello` in the same directory as our source file `hello.rs`.

## Where does Git come in to this?

All good. But if we are using Git we don't want to commit these binary files to our repository. "Let's just use a .gitignore file" I hear you cry. Perfect but we can only git ignore files and directories by name not by type or anything else.

A little trick we can use is to create a folder called `bin` and git ignore that. Then use the following when compiling with `rustc` - 

`rustc --out-dir bin hello`

Now our source files and binary files are kept apart and our binaries never make it into the Git repository.
The 7 Most Popular DEV Posts from the Past Week
Tags: top7
Published: 2020-03-16 16:47:20

---
title: The 7 Most Popular DEV Posts from the Past Week
published: true
description: A round up of the most-read and most-loved contributions from the community this past week.
tags: icymi
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png
---
Every Monday we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week. ❤️

#1. A Different Approach

Remote work is new to a lot of people. In this post, Laurie shares tips on how to communicate and collaborate with your team effectively.

{% link https://dev.to/laurieontech/remote-work-tips-for-teams-51ap %}

#2. So They Said

Gaveen shares their journey to becoming a vim user - the how and why. They also teach us a few vim concepts and share their configuration.

{% link https://dev.to/gaveen/my-vim-story-594d %}

#3. Client-Focused

As a designer, Iqra shares their process to coding. In this post, they explain five design concepts: wireframes, composition, repetition, color, and typography.

{% link https://dev.to/iqramqra/5-basic-design-concepts-for-front-end-devs-19am %}

#4. Quantified Self

Craig shares an impressive side project - a dashboard that quantifies their life activities. Through the process, they became comfortable with React and found a way to achieve more personal balance.

{% link https://dev.to/craigcarlyle/show-dev-i-built-a-dashboard-to-track-my-life-55pl %}

#5. Young, but interesting.

Vic introduces us to Mint, a programming languages focused on building SPAs. In this post, they walk us through how quick it is to create a production-ready Preact single page application with Mint.

{% link https://dev.to/koddr/mint-the-programming-language-for-writing-single-page-applications-spa-3en4 %}

#6. Dark Mode Expectations

Nathan shows us the power of CSS properties and how to implement sweeping changes to websites without much work. 

{% link https://dev.to/nathanminchow/easy-website-themes-with-css-custom-properties-1pb7 %}

#7. Guidance for Allies

Veni offers up advice on 3 actions that you can take today to help create a better environment for women in tech. 

{% link https://dev.to/venikunche/3-actions-you-can-take-to-support-women-in-tech-58ab %}

_That's it for our weekly wrap up! Keep an eye on dev.to this week for daily content and discussions...and if you miss anything, we'll be sure to recap it next Monday!_
Visitor Pattern
Published: 2020-03-16 16:37:46

# Visitor Pattern 
## Behavioral Design Pattern

___

Github: https://github.com/FrancescoXX/Design-Patterns-Visitor-Javascript

## 📌Introduction
Visitor is a simple behavioral design pattern. 

It gives a way to easily separate an algorithm from an object structure.

It is also useful to visit complex objects structures.

___

## ⚡️In short
Allows adding new functions, without modifying existing classes. 

We create a visitor class/function, that implements the specializations of the virtual function. 

The visitor takes the instance reference as input, and implements the goal through double dispatch.

___


## 💡Intent
Separate algorithms from the objects on which they operate.

___


## 🔧 Apply (when we want to)
- Visit complex objects structure (inheritance)
- Perform operations based upon concrete classes
- Avoid pollution of concrete classes with many different operations
- Have the ability to easily define new operations, without changing concrete classes

___


## ✅Pro
- Open/Closed Principle (software entities should be open for extension, but closed for modification).
- Separates operations that don't belong together.
- Accumulate state: Visitors can mantain state across the hierarchy

___

## ⚠️Cons
- Breaks encapsulation
- Adding new concrete elements is hard
- Requires a new method for all concrete visistors
- Rely on the interface of the concrete element (might lack the access to the object's private fields)

___

## 🏆 Great for
- Visit complex object structure
- Change existing object without breaking the current structure
- Centralize logic

___

```javascript
/** Visitor Pattern
 *
 */
class Sayan {
  constructor(name, power) {
    this.name = name
    this.power = power

    this.getPowerLevel = () => this.power;
    this.setPowerLevel = (power) => this.power = power;
    this.acceptVisitor = (functionVisitor) =>  functionVisitor(this);
  }
}

const goku = new Sayan("Goku", 100);
console.log(goku.getPowerLevel()); //100

//Define a Visitor Function
const Empower = (sayan) => sayan.setPowerLevel(sayan.getPowerLevel() * 100);

//Substitute the new function to the Mage object
goku.acceptVisitor(Empower);

//Now check the new power!
console.log(goku.getPowerLevel()); //10000 It's Over 9000!
```

Github: https://github.com/FrancescoXX/Design-Patterns-Visitor-Javascript
Working from home
Tags: remote, wfh, remotework
Published: 2020-03-16 16:32:34

For the next two weeks, I'll be working from home.

I once worked for one year and a half remotely and learned a lot about maintaining focus.

Here are some tips for those of you who are going through this experience for the first time:

1. Resist the temptation of waking up and starting to work right away. Take your time. Have breakfast. Read a little bit. Then start.

2. Go exercise and have a shower before the day starts. This will completely change your productivity. It's an investment of time.

4. Routine is not your enemy. Routine is your best ally.

5. Be patient and educate others who live with you. They are probably not used to having you at the house.

6. Don't eat at your desk. Have lunch away from your computer (and phone).

7. Overcommunicate and be transparent. If you have to step away for some reason, just change your Slack status and let your team know.

8. Know when to stop.

What are your personal tips?
Teen Patti Gold – Rules explained
Tags: tutorial, gaming, cardgames, teenpatti
Published: 2020-03-16 16:31:48

Teen Patti Gold Rules from Developers MoonFrog:
Ante (Boot): Ante or the boot amount that must be paid by all the players that are playing before they are dealt with the cards. This amount is equal to the minimum bet that the game allows.
Blind: In Teen Patti Poker, a player can either look at his card or play blind without looking. The person betting blind will pay only half the amount of what a person bet who has seen his cards. There is a limit on how many turns you can bet while staying blind. It all depends on the stack size of the table. After that limit, the person is forced to see his cards.
Chaal (Call): The amount that is paid by the players who have seen their cards.
Fold (Pack): A player can fold his cards if he thinks he doesn’t have a good hand. The fold is basically quitting the game for that round.
Side Pot: A side pot is basically a show between the two players. A player can request the previous player (player who played last) to do a side pot if both the players have seen their cards. Side pot will only happen if the previous player accepts the request. If he rejects, then the player playing will be asked to pay the amount that the previous player bet. If the player requesting the side pot has a better hand, then the other player will be forced to fold his hands and vice-versa. But, if the hands of both the players are the same, then the player requesting will be asked to fold.
Show: When there are only two players left in the game, then both the player has the option to show their cards. If a player show’s his cards then the opponent is forced to show his and the winner will be decided. The opponent has to pay the amount equal to the previous betting before showing his hands. If the opponent refuses, then he has to fold his hands.
Do NOT:
Use third party software, scripts, or bots, to access or play Teen Patti Gold in any way. (See below)
Attempt to get free chips by clicking links from unknown sources or people promising free chips – this will get your account phished or hacked.
Use profanity or language that discriminates or maliciously targets another individual in any way. This includes your profile picture.
Create more than one account to play Teen Patti Gold from or store chips – all accounts will be banned! (See below)
Lose on purpose as a means of transferring chips – we can easily track this and you will have your chips taken, and banned! (See below)
Sell Chips! Under NO circumstances is anyone permitted to sell chips.
Attempt to buy chips from ANYONE other than Teen Patti Gold.
Click on links that claim to give an extra bonus.
Share your Facebook password with anyone. Teen Patti Gold does not request for your Facebook password under any circumstance.
https://download.zone/teen-patti-gold-free/
Taking Input as Command Line Arguments in JAVA
Published: 2020-03-16 16:09:48

You must have now by realised what String[] args within the declaration of the main method means. It represents a String array named args. Since args is nothing more than an identifier, we can replace it with any other identifier and the program will still work. What we need to know now is how a String array can be passed as an argument when we execute the program. We pass it through the command line itself. Consider that we have a class named Add. The following statement normally used to execute the program.

java Add

When we wish to pass the String array, we simply include the elements of the array as simple Strings beside the class name. Enclosing the Strings in quotes is optional. Consecutive Strings are separated with a space. For example, if we wish to pass a three element String array containing the values "1", "2", and "3" any of the following lines is entered on the command prompt.

java Add 1 2 3 
java Add "1" "2" "3"

Since these arguments are passed through the command line, they are known as command line arguments. The String arguments passed are stored in the array specified in the main() declaration. args[] is now a three element String array. These elements are accessed in the same way as the elements of a normal array. The following is the complete Add program which is capable of adding any number of integers passed as command line arguments.

public class Add {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 0; i < args.length; i++) {
            sum = sum + Integer.parseInt(args[i]);
        }
        System.out.println("The sum of the arguments passed is " + sum);
    }
}
Job Search Week 4
Tags: makers
Published: 2020-03-16 15:57:36

I didn't' get as much as I would have liked to get done this week because I was in Paris and there was no wifi where we were staying but hopefully I can make up for it next week.

Day 1 & 2
At the start of this week, I was in Paris so I didn't get a chance to do any coding over the weekend or Monday and Tuesday. But on the bright side, I got some nice photos.

Day 3
So on Wednesday, I finished the advanced JavaScript and after revising it I feel a lot more confident on starting a MERN project. I when through objects, events and some useful methods as well as doing a fun small project.

Day 4
I thought that since I was doing I also decided to do a JQuery course. I went over the basic methods as well as some of the more basic methods. I was a good idea because adding JQuery to a project tends to make it more interactive.

Day 5

On Friday I got to do the project which was part of the JQuery course. Which was an interactive single-page application for you could play tic-tac-toe. I was quite proud of how that turned out when it was done.

Summary

I managed to do some JavaScript and JQuery which will help me when I do my project.  I'm feeling confident about the next careers fair so that reassuring.
How to create multiple AWS s3 buckets with a single resource config on Terraforrm
Tags: aws, saas, terraform, s3
Published: 2020-03-16 15:39:34

When building and managing applications, having repeatable and automated processes can enable you to focus on productive and exiting workflows thereby making the entire experience a pleasure to go through.

I run about 10 SaaS apps and 2 Serverless sites that require an S3 bucket for storage. These 12 s3 buckets have the same lifecycle rules and bucket configs that I managed manually for a couple of years.

Creating multiple S3 buckets with Terraform should be a really simple thing if you don’t mind unstructured and unmanageable code. Just set your “provider” configs and create a “resource” tag for each of your buckets. So if you have 12 s3 buckets, you’d need 12 resource tags that do the exact same thing. This method is a dirty way to write your HCL code and would actually result in more work than actually managing these directly.

So as part of the Cloud automation plan that I've been developing for Rugged I/O, I’ve begun with my s3 bucket automation.

1. Setting up your Provider and variable
Set your AWS Access Key and Secret Key in the Provider Reference.
Note: Version 0.12+ of Terraform has a simpler Interpolation syntax for variable references

![image-1](https://miro.medium.com/max/700/1*pjSiAtbe-5_y1l2E5frZEg.png)

2. Create a single variable for the "s3_bucket_name"
Your "s3_bucket_name" variable will contain an array of all the bucket names you want. This array is passed in the default key.

![image-2](https://miro.medium.com/max/700/1*ke_UFiGPrILT0Sexv0O4uQ.png)

3. Create a single resource for "aws_s3_bucket"
We only need 1 resource tag that will iterate through the bucket names in the variable.

The "count" attribute calculates the buckets required from the "s3_bucket_names" variable you created.
The "bucket" attribute will contain the name of the bucket from the array in the "s3_bucket_names" variable.

![image-2](https://cdn-images-1.medium.com/max/800/1*5sc0TT9kHRg0og_3P8x3jg.png)

The Complete Code

This technique can be used for any reusable resources, not just s3 buckets, through a thoughtful combination of a simple variable assignment, resource count and naming prefixes.

Consequently, this abstracted method of resource building has reduced hundreds of lines of code and made the entire HCL readable and understandable.