teleren/devto huggingface dataset:
GraphQL Arguments & Variables 🚀
Tags: graphql, javascript, beginners, apollo
Published: 2020-08-15 19:05:32

When writing a GraphQL `Query`, `Mutation` or `Subscription` you'll need to pass dynamic data to the query when making the request, to be able to make the app dynamic and respond to different data set.


#### Basic GraphQL Query

```graphql
query currentUser {
  id
  firstName
  lastName
  email
}
```

The above GraphQL query will fetch the authenticate the user. This query does not require any argument, due that the server should know how to return the authenticated user. Not a GQL thing, but in general good practice not to allow end-users to call a user endpoint and pass an i.e. user_id.


#### GraphQL query with arguments, without variables

```gql
query {
  educators(first: 25, ids: [1,2]) {
    edges {
      node {
        id
        firstName
        lastName
        schools {
          id
          name
          location {
            id
            name
            address
          }
        }
      }
    }
  }
}
```

`educators` take two arguments `first` of type Int and `ids` of type ID in a collection. This is how we define the arguments and assign the type to them (note: this could be named anything, it will be the response key name). 

The SQL statement that matches the above GraphQL Query

```SQL
SELECT * FROM educators
WHERE id in (1,2)
LIMIT 10;
```


#### GraphQL query with variables

Now the same as the query above, with dynamic variables that we can pass to the query in execution time. This is great now because now this query can be reuse around multiple clients.

```graphql
query educators($first: Int, $ids: [ID!]) {
  educators(first: $first, ids: $ids) {
    edges {
      node {
        id
        schools {
          id
          name
          location {
            id
            name
          }
        }
      }
    }
  }
}
```

#### Varaibles definition

```graphql
{
  "first": 25,
  "ids": [1,2]
}
```

i.e. with Apollo Client hook example

```javascript
import { useQuery } from '@apollo/client'

// GET_EDUCATORS_QUERY is the above query
useQuery(GET_EDUCATORS_QUERY,
  { variables: { first: 25, ids: [1,2] } }
);
```

### Conclusion

To help explore GraphQL Variables, you can use the GraphQL Playground. GraphQL variables give the flexibly of sending dynamic variables to the query and at the same time the ability to use the query in multiple clients that require to fetch the same data.
Learn to code with the right mindset!
Tags: webdev, productivity, motivation
Published: 2020-08-15 19:01:06

It's critical to have the right mindset when learning to code.

Having the right mindset can put you ahead in the learning process. It can help you become a better developer just by changing the way you think and the way you approach it.

Our mindset affects our productivity, and if you don't have proper knowledge, you could stop progressing, and maybe even start procrastinating.

In this post, I will share with you the five tips that will help you with getting the right mindset, become a better developer, and overall a better person.

# Five mindset tips that you should know as a programmer:

# 1. Errors will happen
When learning to code, be prepared that you will face errors, and things will break. No one at the beginning of their coding journey knew how to program, either you do.

When you get errors, and you try solving them, you are immediately progressing, and that makes you a better programmer.

# 2. Understand the code
Don't copy and paste the code without knowing what every single line means. If you do want to learn from someone else's code, you can rewrite it line by line and see what stuff does what.

If your learning resource is YouTube courses, make sure to analyze their code and understand how it works.

# 3. Give yourself time
Everyone is different when it comes to learning. Some people learn fast, while some people learn slow. Giving yourself enough time to discover how long it takes for you to understand things, and write your code is very efficient.

When you finally will learn something that appeared challenging, you won't forget it, and you won't repeat the same mistakes.

# 4. Don't compare
Different people have different methods of learning and have different metrics for themselves. Everyone's goals are also different, which means the outcome is going to be disparate. Figure out what you want and stick to it.

Don't compare yourself to others because that's just counter-productive.

# 5. Degree is optional
Degrees are not necessary when it comes to web development. Many self-taught are professionally working because employers want someone who can get the job done.

It doesn't matter if you acquired your skills in college, or with the help of online courses.

# That's it!
What do you think about my tips? Would you add or remove something from the list? Please let me know all of that in the comment section below!

Thank you so much, have a great day!
Github Actions - Day 0
Tags: github, githubactions, day0, actionshackathon
Published: 2020-08-15 18:43:49

Hello peeps!

Just read the article on GitHub Actions Challenge and how one can make an amazing GitHub action for this challenge.

Will try to do my part in this challenge mostly as to learn new things and how to optimise my workflow with these amazing software development tools in my repository.

And so my day 0 will mostly be to covering up all the important resources I feel are worth looking to have a minimal understanding of GitHub Actions!

My start is https://github.com/features/actions
Let me know if you have got any good ones!
RESTful API
Tags: api, nasa, github, public
Published: 2020-08-15 18:22:58

Some open RESTful APIs to get you started with excitement. I think there should be enough excitement when we start learning something new to keep up the spirit.

So if you're looking to learn what RESTful APIs are then first play with few open available RESTful APIs. Trust me it is really exciting to see how smooth it works.

I am using Visual Studio Code extension 'REST Client' to make these requests and see headers but there are many good alternative and you should check them too. If you like to do everything in terminal than curl is obvious choice. Postman is also good for interactive client application.

# NASA APIs
**NASA** has https://api.nasa.gov/ API portal. Let's hear from them,

> Welcome to the NASA API portal. The objective of this site is to make NASA data, including imagery, eminently accessible to application developers. The api.nasa.gov catalog is growing.

You will have to get the API key if you're developing any application but let's just use their endpoints which do not require and you can learn more on NASA's API portal but here I am just diving straight to working.



```GET https://images-api.nasa.gov/search?description="Kalpana"&media_type=image```

Read documentation for this endpoint [here](https://images.nasa.gov/docs/images.nasa.gov_api_docs.pdf)

**Kalpana Chawla** is my favorite Indian astronaut so I am requesting all data which has in description 'Kalpana' and media_type=image returns only those results which have images along with it. Exciting right.




# GitHub APIs
Now let's do something more interesting. We all have github account and so you must be knowing that github also have jobs portal. Good news is they have few APIs public and you can interact with them.

```GET https://jobs.github.com/positions.json?description=python&full_time=true&location=colorado```

Read more in their documentation [here](https://jobs.github.com/api)

Here I am requesting all full time jobs in Colorado which has python in their description.
How to build a dark mode theme using React Material UI, React context API and React hooks
Tags: react, typescript, javascript, opensource
Published: 2020-08-15 18:09:43

This article is about creating your own 'ThemeProvider' component to toggle between the light mode and dark mode built using React Context API and React hooks useMemo() and useCallback() even created a new custom hook useChangeTheme()

I recently added a button to toggle between light mode and dark mode on [my personal blog](https://surajsharma.net), for that I created a separate library called **'react-material-ui-dark-mode'**

If you're interested in reading more about how to build own your toggle button or want to use my library in your projects.

Follow my [blog post on my personal website](https://www.surajsharma.net/blog/react-material-ui-dark-mode) or you can fork the GitHub repository [react-material-ui-dark-mode](https://github.com/creativesuraj/react-material-ui-dark-mode)

Please leave your feedback on the comment box below.


Thank You!
C# Value Task
Tags: csharp, beginners
Published: 2020-08-15 18:07:42

System.Threading.Task is one of the de facto best practices for .net programming for async programming for all these years. C# 7.0 has added a cherry on top of it with Value Task for optimizing performance and abstraction. 

## Performance benefit
To illustrate the benefit in performance, Let's call an API to return the restaurant data for a particular city and cache the result. I have used caching here to show that there is a mix of synchronous and asynchronous code.

``` c#
    [MemoryDiagnoser]
    public class ZomatoCitySearch
    {
        private static IDictionary<string, SearchSuggestion> CacheList = new Dictionary<string, SearchSuggestion>();

        [Benchmark]
        public async Task<SearchSuggestion> SearchCity()
        {
            if (CacheList.ContainsKey("ben"))
            {
                return CacheList["ben"];
            }
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("user-key","*****");
            var response = await client.GetAsync(
                "https://developers.zomato.com/api/v2.1/cities?q=ben");
            var content = await response.Content.ReadFromJsonAsync<SearchSuggestion>();
            CacheList["ben"] = content;
            return content;
        }
        
        [Benchmark]
        public async ValueTask<SearchSuggestion> SearchCityWithValueTask()
        {
            if (CacheList.ContainsKey("new"))
            {
                return CacheList["new"];
            }
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("user-key","***");
            var response = await client.GetAsync(
                "https://developers.zomato.com/api/v2.1/cities?q=new");
            var content = await response.Content.ReadFromJsonAsync<SearchSuggestion>();
            CacheList["new"] = content;
            return content; 
        }
    }
```
I ran the benchmark test with the Value Task and Task, Here is what the benefit

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/f97039t1e5bakradwqc5.PNG)

As per the result, we are using half the memory of Task and in a high-performance environment that can a lifesaver.

Value Task being a struct helps avoid the creation of the object also the internal state machine when the code is executing the synchronous way. 

## Abstraction

One of the problems with using Task in the abstraction is we will force the implementation to use the asynchronous code where it may not be required.

For example, If we create an ICacheprovier interface with the async Get method, We will force the same to Implemented by MemoryCacheprovider too. With the advent of ValueTask, this can be avoided and memory cache doesn't need to cost of Task creation with this model
What browser extensions do you use?
Tags: webdev, discuss, productivity
Published: 2020-08-15 18:01:18

---
title: What browser extensions do you use?
published: true
description: 
tags: webdev, discuss, productivity
cover_image: https://www.dissertation-help-online.com/wp-content/uploads/2020/02/Chrome-Extensions-to-Expand-Vocabulary-770x385.jpg
---
I'm using Chrome and currently I have:

[AdBlocker Plus](https://chrome.google.com/webstore/detail/adblock-plus-free-ad-bloc/cfhdojbkjhnklbpkdaibdccddilifddb) to block video ads, banners, pop-ups and other forms of intrusive and annoying advertising
[Gmail Checker Plus](https://chrome.google.com/webstore/detail/checker-plus-for-gmail/oeopbcgkkoapgobdbedcemjljbihmemj) to get notifications, read, listen to or delete emails without opening Gmail and easily manage multiple accounts
[ColorZilla](https://chrome.google.com/webstore/detail/colorzilla/bhlhnicpbhignbdhedgjhgdocnmhomnp) to get the color of any pixel on the page
[Wappalyzer](https://chrome.google.com/webstore/detail/wappalyzer/gppongmhjkpfnbhagpmjfkannfbllamg) to explore tech stacks behind the websites
[Lighthouse](https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk) - an open-source, automated tool for improving the performance, quality, and correctness of your web apps
[WhatFont](https://chrome.google.com/webstore/detail/whatfont/jabopobgcpjmedljpbcaablpmlmfcogm) to identify the fonts on the websites
[JSON Formatter](https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa) - beautiful and customizable JSON/JSONP highlighter
[Bitwarden](https://chrome.google.com/webstore/detail/bitwarden-free-password-m/nngceckbapebfimnlniiiahkandclblb) - a password management tool
[OctoTree](https://chrome.google.com/webstore/detail/octotree/bkhaagjahfmjljalopjnoealnfndnagc) - to browse GitHub projects in a tree view
[Momentum](https://chrome.google.com/webstore/detail/momentum/laookkfknpbbblfpciffpaejjkokdgca) for new tab customization
[Grammarly](https://chrome.google.com/webstore/detail/grammarly-for-chrome/kbfnbcaeplbcioakkpcpgfkobkghlhen) to reduce writing errors and get grammar suggestions
[React Developer Tools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi) to inspect rendered components in dev tools and record performance information
[Redux DevTools](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) for debugging application's state changes

What browser extensions do you use?
Leetcode - Move Zeros (with JavaScript)
Published: 2020-08-15 17:32:29

Today I am going to show how to solve the Move Zeros algorithm problem.

Here is the problem:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/lls29781w0ylkr13gld7.png)

There are multiple ways to solve this problem. Brute Force is the first method everybody  comes up with. We iterate through the given array, push all non-zero elements to the newly created array, and then fill the rest of it with 0’s.

But as noted in the problem, we should solve this in-place without making a copy of the array. That’s why I am using the two pointer approach. 

1) First, I declare variable nonZeroIndex to keep track of where (index) I am going to place the variable if it is not 0. 

```javascript
var moveZeroes = function(nums) {
    let nonZeroIndex = 0;
};
```

2) I walk through the array by using the “for” loop to check whether or not an element is 0. As we keep finding new non-0 elements, we just overwrite them at the "nonZeroIndex + 1" 'th index. 

```javascript
var moveZeroes = function(nums) {
    
    let nonZeroIndex = 0;
    
    for(let i=0; i < nums.length; i++){
        if(nums[i] != 0) {
            nums[nonZeroIndex] = nums[i];
            nonZeroIndex ++;
        }
    }
};
```

3) Once we’ve reached the end of the array, we see that all of the non-zero elements have been moved to the beginning of the array in their original order. We now need to  move all of the 0's to the end. We do this by simply filling the rest of the array (all the indexes after the "nonZeroIndex" index) with 0’s.

 
```javascript
var moveZeroes = function(nums) {
    
    let nonZeroIndex = 0;
    
    for(let i=0; i < nums.length; i++){
        if(nums[i] != 0) {
            nums[nonZeroIndex] = nums[i];
            nonZeroIndex ++;
        }
    }
    
    for(let i = nonZeroIndex; i < nums.length; i++) {
        nums[i] = 0;
    }
    
};
```
Can you run Enterprise Grade workloads for under $100 a month?
Tags: aws, kubernetes
Published: 2020-08-15 17:27:51

With the recent pandemic and a global recession in our midst affecting all kinds of markets, businesses are looking for ways to save money and remain competitive. At Mobilise we have been asked by customers to find new innovative ways to save costs on digital services whilst still delivering at an ever increasing pace.

But does reducing costs on IT infrastructure necessarily lead to a poorer service?

As an AWS Well Architected Partner and Kubernetes Certified Service Provider, we are uniquely positioned to offer customers the latest in Cloud technology and solution designs. With that in mind, we have been working with customers to pair two amazing technologies together and produce enterprise grade level platforms at a fraction of the cost.

Full post: https://www.mobilise.cloud/can-you-run-enterprise-grade-workloads-for-under-100-a-month/
Python Facebook messenger webhook with FastAPI on Glitch
Tags: python, chatbot, webdev, serverless
Published: 2020-08-15 17:12:58

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zbu4maxpcvm05rs7zfep.jpg)

This webhook can be accessed on [Glitch](https://glitch.com/~wit-ai-pywebhook) and re-used ("remixed") to start a new project.

## Demo

![The facebook messenger output](https://cdn.glitch.com/529fa55b-87a8-4024-9f8a-84d263c206b3%2Fmessenger.png?v=1597507445635)

![Logging output](https://cdn.glitch.com/529fa55b-87a8-4024-9f8a-84d263c206b3%2Flogs.png?v=1597507449109)

Also check out Scott's [introduction video](https://vimeo.com/417820077) on setting up facebook messenger based on his node.js app.

## Requirements

- Python 3.6+
- FastAPI
- Uvicorn

## API Gateway features

- **GET verification** of a received _challenge_
- **POST message reponse** after validating the signature _X-Hub-Signature_ of the received message

# Verify the Webhook

The webhook will return the received variable "challenge" as required by [Facebook's instructions](https://developers.facebook.com/docs/messenger-platform/webhook) to set up a webhook. You will have to add the webhook in your Messenger settings for each App, which you can access on [Facebook Developers](https://developers.facebook.com/).

![Added webhook](https://cdn.glitch.com/529fa55b-87a8-4024-9f8a-84d263c206b3%2Fappsettings.png?v=1597508804453)

## Respond to a message received on a Facebook Page

After glueing your app together with a facebook page and this webhook you will be able to focus your _pythonista skills_ on the responses of your virtual alter ego.

## Wit.ai Hackathon 3 submission

This webhook will be used as a contribution for the 2020 Facebook Hackathon Series, Hackathon 3 with the submission deadline as of _7 September 2020_. This contribution aims to tickle some strategic points out of the judges and particularly encourages all the smart data scientists out there to focus on their algorithmic models to make a compelling case for a friendly, clever and helpful chatbot.

## Pull Requests, Issues, Comments

All feedback is welcome. Hope to hear if you find this contribution useful. The repo is [here](https://github.com/factorlive/fbmessenger-pywebhook).

ToDo list:

- Refactored [dependency](https://fastapi.tiangolo.com/tutorial/dependencies/) to check signature
- Util function to package outgoing message
- Full testing coverage with test client
- Add response time to logs
- Explain code line by line in Readme
Django+Dropzone to load Excel sheet Data into Database
Published: 2020-08-15 17:08:14

Dear Team,

Hope you all doing well!
we are trying to create a django web application to load excel sheet data into database, using dropzone. But we are getting below error
django.utils.datastructures.MultiValueDictKeyError: 'file'

Below is the Code:-
views.py:
def p2p_req_import(request):
    if request.method == 'POST' and request.FILES['file']:
        dataset = Dataset()
        #try:
        new_sup = request.FILES.get['file']
        if not new_sup.name.endswith('xlsx'):
            messages.warning(request, 'Incorrect File Format...!')
            return render(request, 'req_upload.html')

        imported_data = dataset.load(new_sup.read(), format='xlsx')
        success_cnt = 0
        error_cnt = 0
        for data in imported_data:
            #print(data[27])

            if data[27] == 'New Fully Approved':
                rec = moss_req_staging()
                rec.moss_id = data[0]
                rec.request_id = data[1]
                rec.legal_entity = data[2]
                rec.requester_name = data[3]
                rec.currency= data[4]         
                rec.save()
                print('Success Manoj')
                success_cnt = success_cnt+1
            else:
                error_cnt = error_cnt+1

        if (success_cnt != 0) and (error_cnt==0) :
            messages.success(request, 'Requisition MOSS Data Processed Successfully.')
        elif ((success_cnt == 0) and (error_cnt!=0) ):
            messages.error(request, 'Requisition MOSS Data Import Failed For All, Please Check The Data..!')
        else:
            msg = 'There are some Invalid Data, Please check.'
            messages.warning(request, msg)
        '''
        except Exception as e:
            messages.error(request, 'Requisition MOSS Data Import Failed, Please Check The Data..!')
            print('Exception Manoj')
        '''
    return render(request, 'req_upload.html')

req_upload.html:
<form action="/reqimport/" method="post" class="dropzone well" enctype="multipart/form-data" id="dropzone">									{% csrf_token %}										<div class="fallback">											<input name="file" type="file" multiple="" />										</div>										<div class="btn-group pull-right">										{{data_external}}										<button class="btn btn-sm btn-success btn-white btn-round" type="submit">															<i class="ace-icon fa fa-globe bigger-125"></i>															Upload															<i class="ace-icon fa fa-arrow-right icon-on-right bigger-125"></i>										</button>														</div>									</form>


Could you please help me, your suggestion is much appreciated.


Thanks
Manoj
Django: set default value for datetime field
Tags: django
Published: 2020-08-15 16:42:47

When running `makemigrations` after adding new fields to the current model, django would ask for a default value in order to save in the datebase when fields created.

However, I do not set default value to fields I know it is not nullable and would have a certain value assigned already before saving in the database.

The way I compromise is to give a default value when django asks me to in the terminal. For numeric fields I go with 0, and an empty string for character fields.

I find it quite confusing when I first encounter the issue of setting a default value for datetime field since I do not often encounter this problem if I set the field in the first place as the model initially created.

The terminal gives a useful tip suggest that you can use `timezone.now()` as default. But I still kind of prefer a more generic datetime. And `datetime.datetime(1900,1,1)` works.

PS. I am referring to both date and datetime field when mentioning datetime field.

2020/8/17 edit: It is rather dumb to not set default in field argument, cause later giving default values in terminal would be such a pain when there are many fields.