teleren/devto huggingface dataset:
How to add a Graphql endpoint into a Sveltekit app
Tags: svelte, graphql, sveltekit, tailwindcss
Published: 2021-05-10 10:46:44

*Warning: The code provided in this post is not well tested for every environment, and may not provide all the features, use with caution.*

Hello, In this post I will show you how you can add a `graphql` endpoint in a `sveltekit` app with `apollo-server-lambda`.

## TLDR;
If you want to start quickly, here's the boilerplate Repo: https://github.com/vibhanshu909/sveltekit-with-graphql

> Note: I'm using typescript here, if you don't use typescript, make the required changes.
This Project also uses tailwindcss, if you don't want to use tailwindcss, perform the following steps.
- Delete `postcss.config.cjs`, `tailwindcss.config.cjs` & `src/app.css` files.
- remove `postcss: true` option in `preprocess` function from `svelte.config.js` file.
- remove `import '../app.css';` statement from the `script` block in `__layout.svelte` file.

# Follow the below steps.
### Step 1: Install the required dependencies
```sh
npm i apollo-server-lambda graphql
```

### Step 2: create a file `src/routes/graphql.ts` with the following contents.

```ts
import type { EndpointOutput, RequestHandler } from '@sveltejs/kit';
import { ApolloServer, gql } from 'apollo-server-lambda';

const typeDefs = gql`
	type Query {
		hello: String
	}
	type Mutation {
		double(x: Int!): Int!
	}
`;

// Provide resolver functions for your schema fields
const resolvers = {
	Query: {
		hello: () => 'Hello world!'
	},
	Mutation: {
		double: (_, { x }) => x * 2
	}
};

const apolloServer = new ApolloServer({
	typeDefs,
	resolvers,
	playground: true,
	introspection: true,
	tracing: true
});

const graphqlHandler = apolloServer.createHandler();

// This is where the magic happens.
const handler: RequestHandler = async (args) => {
	return await new Promise<EndpointOutput>((resolve, reject) => {
		graphqlHandler(
			{
				httpMethod: args.method,
				headers: args.headers,
				path: args.path,
				body: args.rawBody as string
			} as any,
			{} as any,
			(err, result) => {
				if (err) {
					reject(err);
				} else {
					resolve({
						status: result.statusCode,
						body: result.body,
						headers: result.headers as any
					});
				}
			}
		) as any;
	});
};

export const head = handler;
export const get = handler;
export const post = handler;

```

### Step 3: Test the endpoint.
```sh
npm run dev
```

Goto `http://localhost:3000/graphql`, you should see the graphql playground.

And that's it. :)

Comment down below, if you have any questions.
How do I exit the Vim editor?
Tags: vim, productivity, linux
Published: 2021-05-10 10:18:02

Are you stuck in vim and cannot exit? 

Vim is a **powerful** text editor, but if you are new to vim it may seem very confusing.

Personally I use the command `ZZ` to exit. This saves the file and exists. I use this all the time because what is simpler than pressing `Z` twice?

## Exit vim

Vim works using commands. Before you enter a command, hit the `Esc` key. 

You can exit *without saving* your changes with `:q!`. This is useful if you accidentally modified a file you didn't want to.

If you don't want to quit without saving, instead use `:wq`.

* `:q` to quit (short for :quit)
* `:q!` to quit without saving (short for :quit!)
* `:wq` to write and quit
* `:x` to write and quit (similar to :wq)
* `:exit` to write and exit (same as :x)

Vim is a program that gives me the ability to edit text files, and it has a ton of features. If you are new to vim, I recommend [this course](https://vim.is/)

## Why Vim?

Vim is a text editor. It’s been around for a long time and has an avid community of users. 

* Vim does not require a mouse. This makes it incredibly efficient for editing text files that just contain text or code, increasing your productivity.

![productivity](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0zjceo3jl2aifo0uylz6.jpg)

* Vim can be used remotely over [SSH](https://en.wikipedia.org/wiki/Secure_Shell), in the shell or inside an IDE. Personally I use vim inside visual studio code.

![vim visual studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86lji4vejctgbg9wxxwj.png)

* Vim has been around for more than 30 years and it hasn’t changed its philosophy. Learn vim once and you can use it for years. 

* I've used several IDEs through my career and having to learn shortcuts only once saved me tons of time.

* It hasn’t become bloated and neither added flashy GUI (but you can use it inside IDEs like [Visual Studio Code](https://code.visualstudio.com/), [Jetbrains](https://www.jetbrains.com/)). That is what makes vim so unique among editors. 

Vim is an editor for everyone and not just programmers. It simply does its job with minimal set of commands.
Do you track your expenses/income?
Tags: watercooler, business, finances
Published: 2021-05-10 10:13:30

---
title: Do you track your expenses/income?
published: true
description: 
tags: watercooler, business, finances,
cover_image: https://static-app-misc.teachbanzai.com/img/income-and-expenses-spot.jpg
---
One of the cornerstones of successful budgeting is tracking the expenses and income.

Do you keep a log for that? Maybe you have an app you can recommend?
Git GUI vs Git CLI
Tags: git, github, discuss
Published: 2021-05-10 10:03:12

I recently read through the Pro Git book. It's an awesome book. <sub><sup>(but I think it's a bit abstract – I could make my own git tutorial, what do you say?)</sup></sub> I learned a lot about the Git CLI and now I'm temporarily leaving GitHub Desktop.

What about you guys? Do you use a GUI or the CLI?
What makes python a python🐍?
Tags: python, programming, productivity
Published: 2021-05-10 09:44:06

Python, python and python 🐍.

# What makes python so powerful? 

**Python** is an interpreted, high-level, general-purpose programming language. High-level because of the amount of abstraction, it is very abstract and uses natural language elements, which are easier to use and understand. It makes the whole process simpler and more automated than lower-level languages.

An interpreted language is a type of programming language for which most of its implementations execute instructions directly, without previously compiling a program into machine-language instructions.

A general-purpose programming language is designed to be used for writing software in the widest variety of application domains. A general-purpose programming language has this status because it does not include language constructs designed to be used within a specific application domain.


# But this python is slow 

Python is not the fastest programming language💔 when it comes to speed and performance comparing it to other programming languages.
Unless you have a really big ecosystem and network for your operation, the user won’t really care for the speed of execution.
Here is a comparison of programming languages including Python:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4yzrh5ztpr3gty6u2fah.png)
 
In this day and age, it is much easier to scale⚖ the system and upgrade on that front rather than using something that can not do the job efficiently. Of course, Python can not cover every single field of programming and you should not strictly use Python, but for the time being this is the best option that we have.



# Python has a really big family 👪👩‍👩‍👧‍👦👨‍👩‍👧‍👧👨‍👩‍👦‍👦

Python communities are everywhere on the internet from stack overflow to Instagram. If you get stuck somewhere anywhere you will have an answer for your problem. With new updates and bug improvements python community has been growing rapidly. As more and more people join the crowd it becomes easier for a newbie to get the answers right on time.

Here is the no. of questions asked on stack overflow 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t2l87f8x9kqx7l6g3eap.png)


# What makes python one of the most demanding🤓 language of 2021? 

Python is one of the most demanding language of 2021 because of its vast application in the Tech Industry. Python has a really vast application from running a small `hello world` program to a complex neural network everything can be achieved with the help of python. 

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7c9beqlm4kqazmelyg1.png)
 

```
Thanks for scrolling 😊 
```
Why your z-index isn't working
Tags: html, css
Published: 2021-05-10 09:16:14


I was building a sidebar recently, and I encountered a bug where the content of the page was always on top of the mobile navbar no matter how high I raised the z-index of the sidebar. This took me a while to figure out and I'm writing this article hoping that someone out there won't waste a lot of time like I did trying to solve the bug.

## What is z-index

z-index is a CSS property that allows you to set the [stacking order](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context) of *positioned* elements in the DOM. Here's how to specify the z-index from your CSS:

```css
.element {
  z-index: 1;
}
```

When no z-index is set, the stacking order follows the appearance 
of the elements in the DOM. 

## I set the z-index correctly, so why doesn't it work?

The z-index of an element depends on a number of things, and usually, when these conditions aren't met, the z-index of your element would most likely not take effect.

Here are some of the reasons why your z-index doesn't work;

### You set z-index on a static element

By default, every element has a position of static. z-index only works on positioned elements (relative, absolute, fixed, sticky) so if you set a z-index on an element with a static position, it won't work.

### A ridiculously large z-index was previously set

You might be working on an existing codebase that had the z-index of an element set to 999 (for example). This would affect the stacking order as only an element with a higher z-index can show on top. So you would need to set the z-index of at least 1000 for the z-index to work. Also, it's good practice to avoid setting large z-index values, that way you can avoid issues such as this.

### The parent element has a lower z-index

The z-index of an element can only go as far as the maximum z-index of its parent (it cannot appear in a higher stacking context than its parent). Take for example;

```css
.child {
  z-index: 3;
}

.element-to-cover {
  z-index: 2;
}

.parent {
  z-index: 1;
}
```

In this case, you want to display the `child` element over the `element-to-cover` element so you set the z-index to 3. This should work since it has a z-index higher than the `element-to-cover`, but because the parent element has a z-index of 1, the `child` element would not appear above the `element-to-cover`

## Summary

1. You have to set the position of an element for the z-index to work
2. Check to see if the element has a lower z-index value than the element you want it to appear over 
3. The z-index won't work if the parent element has a z-index lower than the z-index of your element

This article was originally post on [my blog](https://ibnabubakre.xyz/blog/why-your-z-index-isnt-working/)
TIL: Using decorators in Storybook to document invalid inputs
Tags: todayilearned, webdev, frontend
Published: 2021-05-10 08:35:09

---
title: TIL: Using decorators in Storybook to document invalid inputs
published: true
description: Today I learned about Storybooks and used them for documenting validation errors on inputs
tags: #todayilearned #webdev #frontend 
//cover_image: https://direct_url_to_image.jpg
---

Today I learned about [Storybooks decorators](https://storybook.js.org/docs/vue/writing-stories/decorators) and used them for documenting validation errors on inputs.

Decorators are Storybooks way to wrap a story into some extra HTML.
 By that, a basic component can for example be documented in a better visual way, as suggested by Storybooks, by adding some space around a story.

## Writing an input component

Now to my use-case: I was developing input components with Vue, while writing the related stories.
Besides showing the default state of an input, I alse wanted to show the invalid state.

As an example I'd have a component called InputText.vue in which I would simply pass down all the props and attrs to the input field.

```vue
<template>
  <div class="input-group">
    <label v-if="label" :for="id">{{ label }}</label>
    <input type="text" v-bind="{...$props, ...$attrs}" />
  </div>
</template>

...

<style>
...
input:invalid {
  border-color: red;
}
</style>
```

With an InputText.stories.js as follows:
```javascript
export default {
  title: "Forms/Inputs/Text",
  component: InputText,
  decorators: [],
};

const Template = (args) => ({
  props: Object.keys(args),
  components: { InputText },
  template: '<InputText v-bind="$props" />',
});

export const EmptyRequired = Template.bind({});
EmptyRequired.story = {
  name: "Required field",
  args: {
    id: "field1",
    label: "Some Label",
    required: true,
  },
};
```

So the `required` attribute would end up at the components input tag, making it invalid with an empty value.

Per default the invalid state would never be shown in Storybook. 

Sure, I could've added an extra class to my CSS, which probably wouldn't ever be used in the final application, so I wanted to avoid that.

## Adding a decorator

Instead I used a decorator to wrap my story into a `form` tag with:
```
  decorators: [() => ({ template: "<form><story /></form>" })],
``` 

By that I could make use of the browser built-in validation and have my possible validation states show up right away when setting the attribute required and no value. 

This of course works not only with the `required` attribute, but also with something like an invalid e-mail address on `type="email"` inputs.
I made an AR Rick Rolling app!
Tags: unity3d, csharp, gamedev, showdev
Published: 2021-05-10 08:15:04

# AR - RR
> Augmented Reality Rick Rolling!

Recently, I was learning the workings of AR when I had the pointless idea of Rick Rolling people in AR. Because I already had some experience with the Unity game engine, I started by learning Vuforia and soon enough, had a working app.

## Check out AR-RR here:
{% youtube wNbb3LDrM-0 %}

## Links
- Download for Android [here](https://github.com/virejdasani/AR-RR/releases/tag/v1.0)             
- AR-RR on [GitHub](https://github.com/virejdasani/AR-RR/)

A star on the GitHub repo would mean a lot. Thanks for reading!
FlowJS Cheat Sheet
Tags: flowjs, cheatsheet, javascript
Published: 2021-05-10 08:14:46

A JavaScript library providing multiple simultaneous, stable, fault-tolerant, and resumable/restartable file uploads via the HTML5 File API.


###References

- [Flow website](https://www.saltycrane.com/flow-type-cheat-sheet/latest/) _(flow.org)_
- [Getting started with Flow](https://flow.org/en/docs/getting-started/) _(flow.org)_
- [FlowJS cheatsheet](https://cheatsheetmaker.com/flow)

```js
type Callback = (?Error, string) => any

function fetch (callback: Callback) {
  ···
}
```
###[Examples] Examples

```js
var myNumbers: Array<number> = [42]
function foo(): any { return 42 }
var b: boolean = false
var b: ?boolean = false  /* maybe */
var b: string | boolean = false

var a: Class<MyClass> = MyClass
var b: MyClass = new a()
```
###[Advanced features] React

```js
type Props = {
  bar: number,
}

type State = {
  open: boolean,
}

class Foo extends React.Component<Props, State> {
  // Component code
}
```
###[Advanced features] Comment syntax

```js
/*::
  export type Foo = { ... }
*/

function add(n /*: number */) { ... }
```
###[Advanced features] Imports

```js
import type { Person } from '../person'
import typeof Config from '../config'
```

```js
export type Person = { id: string }
```
###[Advanced features] Functions

```js
const callback: () => void = function () {}
```

```js
function filter<T> (
  list: Array<T>,
  callback: (item: T) => boolean
): Array<T> {
  ···
}
```

See: [Functions](https://flow.org/en/docs/types/functions/)
###[Advanced features] Interfaces

```js
interface Jsonable {
  toJSON(): string
}

class Foo {
  toJSON() { return '{}' }
}

(new Foo: Jsonable)
```

See: [Interfaces](https://flow.org/en/docs/types/interfaces/)
###[Advanced features] Generic classes

```js
class GenericClass<T> {
  x: T
  constructor (x: T) { ... }
}

var n: GenericClass<number> = new GenericClass(0)
```

See: [Generic classes](https://flow.org/en/docs/types/generics/#toc-classes-with-generics)
###[Advanced features] Type aliases

```js
type Tree = {
  foo: string,
  bar: number,
  qux: (foo: string, bar: number) => boolean
}

type Generic<T> = {
  foo: T
}
```

See: [Type aliases](https://flow.org/en/docs/types/aliases/)
Cron Job Tutorials - How to set up cron job for BackupBuddy?
Published: 2021-05-10 08:09:44



I installed BackupBuddy on my server, and I want to set up a cron job to trigger BackupBuddy's cron job script. What should I do to set up the cron job?

https://www.easycron.com/cron-job-tutorials/how-to-set-up-cron-job-for-backupbuddy

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4r91v2nnkndgltzvkuk.png)
Async Await in Javascript
Tags: javascript, programming, webdev
Published: 2021-05-10 08:04:05

So in the [last post](https://dev.to/deepansh946/promises-in-javascript-1nbp), we learned about how promises work in javascript.

Today, we gonna learn about how async-await works together for the seamless working of promises and makes the developer experience better.

The concept of async-await comes into use when we have more than 2 promises, the code becomes messy and sometimes unbearable.

If you remember the previous example of making a `promise`, that's great. If not here it is:


```javascript
const isNumEven = (num) => new Promise((resolve, reject)=> {
  if(num % 2 === 0) {
    resolve(true)
  } else {
    reject(false)
  }
})
```

Now this `promise` can be used as:

```javascript
async function isEven(num) {
  try {
    const result = await isNumEven(num);
    return result;
  } catch(err) {
    console.log('Something went wrong!')
  }
}

isEven(4); // true
```

As you can see, it makes our code less sloppy and easier to manage. Now if the `isNumEven` function returns another `promise`, then we can use `await` again and get the result.

Now some of you must be wondering why `try catch` is used in this example?

The answer to this is error handling. If any of the statements fail in the `try` block, then the code directly goes into the `catch` block. So, if our promise fails, the error will be handled by the `catch` block. 

Some important points related to `async await`:

- Avoid using it inside `for` loops, and if there is a need to perform an operation on all entities use `Promise.all` rather than `async await`.

- If you have used the `async` keyword before a function, it'll return a promise every time.

- Async await is just syntactic sugar for promises, the code runs the same way as it runs for promises. The code looks synchronous and the program waits until the promise is resolved.

- If a function is `async`, then only you can use `await` inside it.

Connect with me on [Twitter](https://twitter.com/deepansh946), [Instagram](https://instagram.com/deepansh.codes) & [LinkedIn](https://www.linkedin.com/in/deepansh946)

Happy Coding!
Day 57 of 100 Days of SwiftUI
Tags: swift, 100daysofcode
Published: 2021-05-10 05:59:52

I just completed day 57 of 100 days of SwiftUI. Today I learnt more about CoreData. I learnt how to create CoreData models without optional, how to ensure the uniqueness of your models using constraints and the conditional saving of NSNSManagedObjectContext.

By default, properties of models created by CoreData are optional. To make them non-optional, you have to opt out of code-gen. You can do this by selecting the code-gen manual/none option and creating an NSManagedObject subclass.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uoc7sr7nql2q4hj9ei2r.png)
This will create to two classes for you. `Person+CoreDataProperties.swift` and `Person+CoreDataClass.swift` (Person is the name of my model)
```swift
extension Person {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Person> {
        return NSFetchRequest<Person>(entityName: "Person")
    }

    @NSManaged public var name: String?

    public var wrappedName: String {
        name ?? "Unknown Name"
    }
}

extension Person : Identifiable {

}
```
The code above is an NSManagedObject subclass. It has an optional property called `name`. In order to make that property non-optional, we simply created a computed property called `wrappedName`.

In order to make your data unique, all you have to do is add this line of code to the `willConnectTo` method in the `SceneDelegate.swift` directly below the code that starts with `let context`
```swift
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
```
Don’t Live With Broken Windows
Tags: programming, codequality
Published: 2021-05-10 07:25:13

Hunt and Thomas on their book “the Pragmatic Programmer" concentrates on a very important aspect on code quality .

One broken window, left unrepaired for any substantial length of time, instills in the inhabitants of the building a sense of abandonment—a sense that the powers that be don’t care about the building. So another window gets broken. People start littering. Graffiti appears. Serious structural damage begins. In a relatively short space of time, the building becomes damaged beyond the owner’s desire to fix it, and the sense of abandonment becomes reality.
The "Broken Window Theory" has inspired police departments in New York and other major cities to crack down on the small stuff in order to keep out the big stuff. It works: keeping on top of broken windows, graffiti, and other small infractions has reduced the serious crime level.

Don’t leave "broken windows" (bad designs, wrong decisions, or poor code) unrepaired. Fix each one as soon as it is discovered. If there is insufficient time to fix it properly, then board it up. Perhaps you can comment out the offending code, or display a "Not Implemented" message, or substitute dummy data instead. Take some action to prevent further damage and to show that you’re on top of the situation.
We’ve seen clean, functional systems deteriorate pretty quickly once windows start breaking. There are other factors that can contribute to software rot, and we’ll touch on some of them elsewhere, but neglect accelerates the rot faster than any other factor.
You may be thinking that no one has the time to go around cleaning up all the broken glass of a project. If you continue to think like that, then you’d better plan on getting a dumpster, or moving to another neighborhood. Don’t let entropy win.
[Video] Manage configuration and multiple environments in Node.JS with Foal
Tags: typescript, javascript, node, webdev
Published: 2021-05-10 07:22:37

---
title: [Video] Manage configuration and multiple environments in Node.JS with Foal
published: true
description: This tutorial describes how to manage configuration with Foal across one or more environments.
tags: TypeScript, JavaScript, NodeJS, webdev
//cover_image: https://direct_url_to_image.jpg
---

This tutorial describes how to manage configuration with Foal across one or more environments using:
- JSON, YAML and JS files,
- .env files
- and environment variables.

It also explains how to check and convert the types of configuration values.

{% youtube e_W8QnImazo %}