teleren/devto huggingface dataset:
Arrow Function di Javascript
Tags: javascript, node, webdev
Published: 2021-05-12 21:14:44

Pada Javascript, arrow function adalah sebuah mekanisme pembuatan function expression tanpa harus menuliskan keyword 'function'.
Berikut contoh arrow function:
```
let greet = () => console.log('halo')
// menjalankan function greet
greet()
```

Keistimewaan lainnya dari arrow function yaitu adanya implicit return.
Implicit return adalah sebuah cara sebuah arrow function mengembalikan nilai tanpa harus menuliskan keyword 'return'.
Contoh implicit return:
```
let multiple = (number1, number2) => number1 * number2
console.log(multiple(10, 20))
```
Implicit return ini hanya berlaku jika arrow function ditulis dengan satu baris saja. Kalau muli line, maka harus secara explisit dituliskan keyword 'return'-nya
```
let multiple = (number1, number2) => {
   return number1 * number2
}
console.log(multiple(10, 20))
```
berikut penjelasan singkat tentang arrow function di Javascript, terima kasih sudah membaca artikel ini.
How to set up VSCode to  work with TakeShape's Metaschema
Published: 2021-05-12 21:10:35

---
canonical: "https://www.takeshape.io/articles/how-to-set-up-vscode-to-work-with-takeshapes-metaschema/"
---

# How to set up VSCode to  work with TakeShape's Metaschema

Nobody likes typos in JSON. Let's make VSCode catch them for us when writing a TakeShape schema.

When writing JSON it's easy to fudge the syntax a bit, usually by missing a quote or a colon. Thankfully, coding tools like VSCode are good at catching these errors. However, a far sneakier problem to identify is when the format of the keys and values in a JSON file don't abide by the internal rules of a program that relies on the JSON you are writing. This can be easily solved by using a JSON metaschema to automatically validate JSON, which will give VSCode the power to warn you when your  JSON doesn't match what TakeShape is expecting to be in a `schema.json`. 

*Term definition:* TakeShape's metaschema is a JSON schema that VSCode can use to regulate TakeShape's `schema.json` files. It's a schema for a schema; hence, a "metaschema". TakeShape's metaschema can be found at [https://schema.takeshape.io/project-schema](https://schema.takeshape.io/project-schema)

## **Setting up VSCode to use TakeShape's metaschema**

1. **In VSCode, go to your Preferences and find the settings.json file.**

    It's under the Settings button in the bottom left corner, under the Settings tab. You can also get there with the `Cmd` + `,` shortcut (`Ctrl` + `,` on Windows).

    Search for `json` and click on the link that says `Edit in settings.json`.

2. **Tell VSCode to use the TakeShape metaschema.**

    Add the following to the `json.schemas` array:

    ```json
    {
    	"fileMatch": [
    		"schema*json"
    	],
    	"url": "https://schema.takeshape.io/project-schema"
    }
    ```

    In short, this tells VSCode to use the TakeShape metaschema on every file that matches `schema*json`, including — but not limited to — `schema.json`, `schema.v2.jneiubciub.json`, and `schema.v4.json`. 

3. **Test to make sure it works.**

    If you have a `schema.json` file handy, feel free to use that; otherwise, you can download one from any of the repos listed at [https://github.com/takeshape/patterns](https://github.com/takeshape/patterns). 

    You should see something like this, where you'll get a yellow squiggly warning line if you try to add a property to the schema that TakeShape won't know what to do with.

    ![Demo](https://images.takeshape.io/4d46e476-8704-42c4-8d0d-06ebdd0e3c93/dev/5eb74ef0-36e5-4c57-90d8-8e67f3023264/metaschema%20demo.png?auto=compress%2Cformat)

Now VSCode will optimize your workflow by reminding you of any typos in your `schema.json` right as you type them, instead of when you import the whole schema back into TakeShape later. If you have any trouble with this process, feel free to reach out to the TakeShape team by clicking the chat bubble in the bottom right corner of your screen.
Cómo hacer que el tamaño del formulario cambie cuando el borde es "none" en C#
Published: 2021-05-12 21:08:15

Copiamos y pegamos este código en el formulario que queremos que se pueda redimensionar su tamaño.

```
 protected override void WndProc(ref Message m)
        {
            const int RESIZE_HANDLE_SIZE = 10;

            switch (m.Msg)
            {
                case 0x0084/*NCHITTEST*/ :
                    base.WndProc(ref m);

                    if ((int)m.Result == 0x01/*HTCLIENT*/)
                    {
                        Point screenPoint = new Point(m.LParam.ToInt32());
                        Point clientPoint = this.PointToClient(screenPoint);
                        if (clientPoint.Y <= RESIZE_HANDLE_SIZE)
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)13/*HTTOPLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)12/*HTTOP*/ ;
                            else
                                m.Result = (IntPtr)14/*HTTOPRIGHT*/ ;
                        }
                        else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE))
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)10/*HTLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)2/*HTCAPTION*/ ;
                            else
                                m.Result = (IntPtr)11/*HTRIGHT*/ ;
                        }
                        else
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)16/*HTBOTTOMLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)15/*HTBOTTOM*/ ;
                            else
                                m.Result = (IntPtr)17/*HTBOTTOMRIGHT*/ ;
                        }
                    }
                    return;
            }
            base.WndProc(ref m);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= 0x20000; // <--- use 0x20000 
                return cp;
            }
        }

```
Stop using SSH, use AWS Session Manager
Tags: aws, sessionmanager, ssm, ssh
Published: 2021-05-12 21:05:47

---
title: Stop using SSH, use AWS Session Manager
published: true
description: I will never again open a port on a security group explicitly for ssh. Session manager is fantastic, let me show you.
tags: #aws #sessionmanager #ssm #ssh
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ng6yqzoyzs3102ti25t9.png
---

Stop opening port 22 for ssh (or any port). AWS SSM Session Manager can manage ssh connections to instances for you from your CLI, even private networked resources, and permission based on IAM policies.

You can "ssh" to your instances using session manager in your CLI and also open tunnels, which allows you to use features like VSCode remote development (example included).

**Dependencies:**
- [aws cli](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)
- [session manager plugin for aws cli](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)
- [enable session manager in your account](https://github.com/drewmullen/terraform-aws-session-manager) _(this is a fork, feel free to use the original)_
- create an instance with the instance profile created by the above terraform

**Basic SSH Connection:**

`aws ssm start-session --target i-<your instance id>` 

**VSCode via tunnel**

1. [Enable vscode remote plugin](https://code.visualstudio.com/docs/remote/remote-overview)
2. Copy your public ssh key to an instance (unless you added it to the instance via user data)
4. [Add your connection to VSCode](https://code.visualstudio.com/docs/remote/ssh#_connect-to-a-remote-host)
5. Update your local ssh config
```
$ vim ~/.ssh/config
Host i-<your instance id>
   ProxyCommand sh -c "aws ssm start-session --profile <your aws profile name> --target %h --document-name AWS-StartSSHSession --parameters 'portNumber=%p'"
```
\\6. connect with vscode `ubuntu@i-<instance id>`

**Bonus!** Use the terraform above to deploy vpc endpoints so zero traffic goes over the internet between SSM and your instance!

`vpc_endpoints_enabled = true`

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

**Troubleshooting:**

- Does your user have permissions to access ssm?
- Did I miss something? please lmk in the comments and ill update!
Notes on CSS image-set() with type()
Tags: css, imageset, cssimages4, webdev
Published: 2021-05-12 21:04:23

The html `<picture>` element has had the ability to use fallback image file types since it's inception. The `type()` function in `image-set()` adds this ability to CSS image declarations (`background-image`, `border-image`, `mask-image`, etc).

## Syntax with with fallback

```css
background-image:  url("images/test.jpeg");
background-image:
  image-set(
    "images/test.avif" type("image/avif"),
    "images/test.webp" type("image/webp"),
    "images/test.jpeg" type("image/jpeg")
  );
```
Assuming the above example code in a browser with `image-set()` and `type()` support the browser will first check for AVIF support. If not supported the browser will skip this option and move on to check for WEBP support etc. Once the browser finds a supported file type it will begin the process of using that file. The browser will not download images with unsupported mime types.

If `image-set()` with `type()` is not supported the entire `image-set()` declaration will be ignored and the browser will fallback to: 
>background-image: url("images/test.jpeg");

Like the `url()` function `image-set()` (if supported) will never fallback. You can think of `image-set()` with `type()` as is a more flexible dead end than `url()`.

## Combining type() and resolution

```css
background-image: 
  image-set( 
    "foo.jpg",
    "foo-2x.avif" 2x type("image/avif"),
    "foo-2x.jpg" 2x
  );
```

You may want to take advantage of a file type with better compression for devices with high resolutions. In the above example a 2x device would be served an AVIF if the browser supports it and fall back to a JPG if not.

## @supports

```css
@supports not (background: image-set("foo.png" type("image/png")) ){
    .notwebp .contain{
        background-image: url('test.jpg');
    }
    .webp.notavif .contain{
        background-image: url('test.webp');
    }
    .avif .contain{
        background-image: url('test.avif')
    }
}

@supports (background: image-set("foo.png" type("image/png")) ){
    .contain{
        background-image: image-set(
            "test.avif" type("image/avif"),
            "test.webp" type("image/webp"),
            "test.jpg" type("image/jpg")
        );
    }
}
```

If you are already using a Modernizer like script to add mime type support information to your `html` tag through classes the above `@supports` example can be used to check for `image-set()` and `type()` support so it can be used as a replacement if available.

## Browser Support

Support only in Firefox 89 (as of writing - 5/2021). If you want this implemented in Chrome star this bug: https://bugs.chromium.org/p/chromium/issues/detail?id=630597&can=2&q=css%20image-set

## Links

W3C Spec: https://drafts.csswg.org/css-images-4/#image-set-notation
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/image-set()#using_image-set_to_provide_alternative_formats
Chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=630597&can=2&q=css%20image-set
Developer tools support in Firefox: https://bugzilla.mozilla.org/show_bug.cgi?id=1687033
Cómo hacer que tu Formulario se mueva cuando se le quitan los bordes en c#
Tags: csharp, design
Published: 2021-05-12 21:00:25

Lo primero es quitar el Borde al formulario.

Copiamos y pegamos este código  en el formulario
```
[DllImport("user32.DLL", EntryPoint = "ReleaseCapture")]
private extern static void ReleaseCapture();

[DllImport("user32.DLL", EntryPoint = "SendMessage")]
private extern static void SendMessage(System.IntPtr hwnd, int wmsg, int wparam, int lparam);
```

Importamos las librerías que nos pida importar  y en el evento de MouseDown desde el control que queremos que se mueva el formulario copiamos este código.
```
ReleaseCapture();
SendMessage(this.Handle, 0x112, 0xf012, 0);
```
si queremos que al presionar clic derecho en un panel se pueda mover el formulario, simplemente copiamos el código anterior en el evento MouseDown del panel, aplica lo mismo para Label, Button y todos los controles.

Si quieres ver cómo se puede cambiar el tamaño del formulario cuando se le quita los bordes mira esta publicación.

[clic aquí](https://dev.to/juandiego/como-hacer-que-el-tamano-del-formulario-cambie-cuando-el-borde-es-none-24ke)

> # Mis redes 

[Facebook](https://www.facebook.com/eljuandi.mejiamaestre)
[Instagram](https://www.instagram.com/eljuandi36_)
[YouTube](https://www.youtube.com/channel/UCBruvsN18FvqNHSHe7E6WWg)
how to solve, Exception EAccessViolation in module xampp-control.exe (Solution)
Published: 2021-05-12 20:52:42

after long time i switch to vale to xampp local server but when i was trying to quite my xampp application its show me an alert like below screen shot:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mr5xmn3qhd769kucesfn.png)
and the i was trying to solve the issue, that's why i was trying to find out why this is happen and after searching some times i find out how to solve this. the solution procedure is: 
first i go to my local xampp directory and then find out the xampp-control.ini file after that i go to the properties of that file after that i go to security tab of that file and then Under security tab i was Select users Everyone and then click to edit permission button and checked in to full control check box and then click Apply and ok. which is like below screen shot:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5395ncnf88sxg0uohnhp.PNG)
that's it. all done.
.
Happy Coding.
osman forhad
Mobile & Web Application Developer💻
Using NestInterceptor to capture requests and responses
Tags: nestjs, express, requests, responses
Published: 2021-05-12 20:27:19

We needed a provision to capture API requests and responses. This was so that our mobile team could get a summary of what the app was sending and receiving. Once captured we wrote them in a file in the last-in-first-seen order.

We eventually started off by implementing the **Nest Middleware** but then we realized a middleware can only receive requests. So we switched to **Interceptors**. 

An interceptor has access to both requests and responses.

Here is the code.

```
class LoggerInterceptor implements NestInterceptor
{
	intercept(context: ExecutionContext, next: CallHandler): Observable<any>
	{
		let logFile = process.env.LOGGER_APP + ".log";
		let logPath = process.cwd() + "<path>" + logFile;

		let { url, method, headers, body } = context.switchToHttp().getRequest();

		if (url != "/logs/dev.log")
		{
			let logMessage = "\n\n=======================================\n\nTIME: " + Date().toString() + "\nMETHOD: " + JSON.stringify(method) + "\nURL: " + JSON.stringify(url) + "\nHEADERS: " + JSON.stringify(headers) + "\nBODY: " + JSON.stringify(body) + "\nRESPONSE: ";
	
			return next.handle().pipe(tap((data) => 
			{
				let responseBody = JSON.stringify(data);

				logMessage += responseBody;

				// Reading old data.
				logMessage += fs.readFileSync(logPath);

				fs.writeFile(logPath, logMessage, function (err, file) { });
			}));
		}
	}
}
```

A couple of points worth mentioning - 
1. **<path>** is the path to where your log files should be stored. We wanted the app team to have access to the logs so we kept them in a **public** folder.
2. We put up a check (!= "/logs/dev.log") to prevent logging access to the log file into the log file :D Lol!


Happy Programming!!!
Testing AWS' Network Load Balancer on Commit’s open source Zero infrastructure
Tags: aws, opensource
Published: 2021-05-12 20:22:11

Commit's Chief Architect - formerly at Hootsuite - manages an open source project Zero (https://github.com/commitdev/zero). As part of regular maintenance, he was trying to make a switch to using Amazon Web Services’ Network Load Balancer from their “Classic” Elastic Load Balancer. NLB is billed as AWS’s next generation of load balancers. He was hoping for a better experience than he's had with ELB—although my experience with ELB has been mostly positive, as it tends to be fairly fast and stable. We’ve been using ELB with Kubernetes for quite some time, and he's fairly confident in how these technologies work together.

The goal was to be able to use Network Load Balancer stably as the load balancer on the edge of our infrastructure, sending traffic to an internal Elastic Kubernetes Service cluster running Nginx Ingress Controller. He wanted to be able to add and remove nodes, do a deploy rollout to the ingress controller without any disruption of traffic, and retain client IP information for logs and application functionality.

He found that in all three modes of operation—External Traffic Policy: Local, External Traffic Policy: Cluster, and NLB–IP—there were gotchas that would lead to traffic loss under not unrealistic conditions, such as nodes being added and removed and rollouts of the ingress controller. The ingress controller is a fairly stable piece of the setup and shouldn’t require many updates, restarts, etc., but he expects to be able to perform these operations when I need to, without any impact on users.

He wrote a piece about the planned transition, his blockers, and what he thinks stands in the way of broader adoption of Amazon Web Services’ Network Load Balancer.

https://blog.commit.dev/articles/testing-network-load-balancer-on-commits-open-source-zero-infrastructure
Workout Generator
Tags: python
Published: 2021-05-12 20:15:14

```python
import random
import datetime

back = ['bent-over row', 'lying row', ]
quadriceps = ['lunge', 'side lunge', 'walking lunge', 'rear lunge', 'split squat',
              'front squat', 'step ups']
chest = ['bench press', 'fly', 'pullover']
hamstrings = ['straight-leg deadlift', 'straight-back stiff-leg deadlift']
deltoid = ['arnold press', 'front raise', 'shoulder press']
calves = ['standing calf raise', 'single leg calf raise']
biceps = ['curl', 'seated curl', 'incline curl']
abdominal = ['push crunch', 'crunch', 'jack-knife', 'reverse crunch']
triceps = ['kickback', 'lying tricep extension', 'incline tricep extension']
cardio = ['skaters', 'jump jacks', 'burpees', 'jump rope', 'mountain climbers',
          'high knees', 'fanny kickers', 'jump squats']


def random_exercise_generator(lst):
    ran_num = random.randint(1, len(lst))
    return lst[ran_num - 1]


back_exercise = random_exercise_generator(back)
quadriceps_exercise = random_exercise_generator(quadriceps)
chest_exercise = random_exercise_generator(chest)
hamstrings_exercise = random_exercise_generator(hamstrings)
deltoid_exercise = random_exercise_generator(deltoid)
calves_exercise = random_exercise_generator(calves)
biceps_exercise = random_exercise_generator(biceps)
abdominal_exercise = random_exercise_generator(abdominal)
triceps_exercise = random_exercise_generator(triceps)
cardio_exercise = random_exercise_generator(cardio)

name = input("Name: ")
date = datetime.datetime.now()

print(f"Client's name: {name.title()}")
print(f"Todays date: {date}")
print("******* Workout Generator *******")
print(f"Back: {back_exercise}")
print(f"Quads: {quadriceps_exercise}")
print(f"Chest: {chest_exercise}")
print(f"Hams: {hamstrings_exercise}")
print(f"Delts: {deltoid_exercise}")
print(f"Calves: {calves_exercise}")
print(f"Bis: {biceps_exercise}")
print(f"Abs: {abdominal_exercise}")
print(f"Tris: {triceps_exercise}")
print(f"Cardio: {cardio_exercise}")
print("**********************************")
```
Unicorn Sendbird is hiring a Developer Advocate!
Tags: hiring
Published: 2021-05-12 19:55:35

Sendbird is looking for our next </span><span class="s2">Developer Advocate!  As part of our growing Developer Advocate team, you will help build interest for Sendbird products through your efforts to educate and evangelize to developers. Participation in developer events and communities will help you share your expertise on building in-app messaging with Sendbird leading chat and voice/video APIs. You'll build demos, samples for mobile and web, and more! Get paid for doing what you love – check us out! https://sendbird.com/careers/5121691002

</span><span class="s3">#flutter #iOS #android #jscript #react #python #chat </span></p>
</body>
</html>
Failing the CI build if django migrations are out of date
Tags: django, python
Published: 2021-05-12 19:13:10

A common mistake in django is to make a model change but forget to run `makemigrations` to generate a migration for the model change. Sometimes it is not entirely obvious when this need to happen. For example, let's say I'm using the [django-extensions](https://github.com/django-extensions/django-extensions) library and I define a model like:

```py
# models.py

from django.db import models
from django_extensions.db.models import TimeStampedModel

class MyModel(TimeStampedModel, models.Model):
    pass
```

In this situation, upgrading django-extensions to a new version might require me to regenerate the migrations in my app, even though I haven't made any changes to `models.py` and overlooking this could generate unexpected results.

Fortunately there is a simple thing I can do to detect and warn if this happens: If I run

```
python manage.py makemigrations --check
```

in my CI build, this will cause the build to fail if my migrations are out of sync with the models, warning me about the problem.