teleren/devto huggingface dataset:
Validating Django models that are created without forms
Tags: python, django, webdev
Published: 2020-05-28 17:33:33


Usually instances of models (objects) are created using a `ModelForm`. You know the drill: The user inputs some values in the form, hits submit and sends a `POST` request with the data. In the view function/class, we do a model validation using `form.is_valid()` and then save the object in the database. This gives a basic level of validation for the model fields. 

But what if we want to do a more comprehensive validation on the object? And what about a scenario where we want to create objects in some other way than using forms? Let's say through an API call. How do we validate the objects in that case?

That is what **validators** are for. Validators are callable functions that will check the object fields and raise `ValidationError` if they contain values that don't meet our desired criteria. In case of `ModelForm` the validation is done  when we call `form.is_valid()`. Note that if we create an instance of the model ourselves, validators will not be run automatically. So we need to validate the objects first before saving them.

Let's say we have a model called Person. Each person has a first name, a last name and an age. And for some reason, we don't want to save the person in our database if their age is less than 18. We can create a validator that checks for that. 

In `models.py`:
``` python
from django.db import models
from django.core.exceptions import ValidationError
    
def validate_age(value):
	if value < 18:
        raise ValidationError(
            ('Age must be at least 18.'),
            params={'value': value},
        )
    
class Person(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()
    age = models.IntegerField(validators=[validate_age])
```

Now just before we save the object, we ask django to validate it by calling the `full_clean()` method. 

In `views.py`:
``` python
from myapp.models import Person
from django.core.exceptions import ValidationError
    
# let's create an object
person = Person()
person.first_name = "John"
person.last_name  = "Doe"
person.age = 17
    
try:
    person.full_clean()
    person.save()

except ValidationError:
    # Do something with the error here.
    # Maybe display to user or log it somewhere.
```

`person.full_clean()` will run the relevant validators for all fields of the `person` object. In this case it will run the `validate_age` function on the `person.age` field and throws an exception. This prevents this object from being saved. So young John will not be saved into the database! 🙂


<a href="https://chipper-musician-9131.ck.page/71c2932d23">![signup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rx6dciscpdwtk3z6j4u6.png)</a>
Brainstorming 101
Tags: productivity, tools, startup
Published: 2020-05-28 17:06:59

Be open to every idea. List everything you think and don't censor yourself or others. Brainstorming starts by creating all kind of ideas that can be really crazy and by being open to all kind of ideas instead of right away rejecting some your brain become more creative.

It's important to think the place and time for brainstorming. Creative location might inspire people more than some office. It's also important to make sure people feel comfortable so that they aren't hungry, it's not too warm, or the chairs aren't uncomfortable.

Often talking with other people is better than thinking alone because as you explain ideas you might see something new or the other people might add something to your ideas. If brainstorming is done alone it often helps to say things out loud. Writing things done is anyways necessary to document ideas but it might help to understand things better.
Behind the Scenes,React Native
Tags: reactnative, node, android, ios
Published: 2020-05-28 16:57:29

Above explains the internal working of the react native application. Where  the code can be divided in two parts such as special components(<VIEW></VIEW>..etc) and the JavaScript code. Now the special components are only compiled to native views and not the JavaScript code. The JavaScript code is kept separately and  is written according to the business logic. Now we can use the API  native component such as camera because the JavaScript code runs internally in your app ,where we have virtual JavaScript machine running internally by react native. This virtual machine knows how to talk to native machine by using bridge present internally inside react native application.

The native views which can be on any native platform iOS or Android can be used by writing a single code.This reduces the cost of the application and hence is preferred more these days..

Hope it was helpful!
GitHub README templates & tips on writing high-quality documentation
Tags: writing, opensource, tutorial, beginners
Published: 2020-05-28 16:54:02

I've been working on a project wherein I'm curating various documentation templates and compiling tips that help create better documentations. It'd be awesome if y'all could check it out and give feedback!

Link: https://github.com/kylelobo/The-Documentation-Compendium

Cheers! :)
#AzureFunBytes - Azure Storage - Live at 2pm EDT Thursday 5/28 on Twitch - Live Video Azure Fundamentals Show
Tags: twitch, azure, storage, beginners
Published: 2020-05-28 16:49:32

![AzureFunBytes logo](https://dev-to-uploads.s3.amazonaws.com/i/699md0mmakw0cbutamyq.jpg)

AzureFunBytes! - Byte-sized content with a live Twitch show!  Learn about 
Azure fundamentals with me!

Live stream is available on Twitch at 2pm EDT today.  You can also find the recordings there as well.

https://twitch.tv/azurefunbytes
https://twitter.com/azurefunbytes

Join me, ask questions and learn about Azure Storage options!

Microsoft Learn: [Azure Fundamentals](https://cda.ms/1jV)
Microsoft Azure: [$200 Free Credit](https://azure.microsoft.com/free/?WT.mc_id=blog-devto-jagord)
A New Type of AWS Summit
Tags: aws, distributedsystems
Published: 2020-05-28 16:49:09

Recently I attended, via video conference, the [AWS Summit 2020](https://aws.amazon.com/events/summits/) (US & Canada); so I thought I'd share my thoughts and learning from the topics presented. 

This is the beginning of my series on AWS’s recent Online Summit 2020.

The content here describes my own thoughts and understandings from the material presented, not the views of the presenters, who I do not speak for.

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

### My thoughts on the AWS Summit Online 2020

Given that all the talks were actually pre-recorded videos, I could have watched each one over several days after the event. However, I still wanted to emulate the feeling of a conference, and let’s be honest, there’s only so much time in the day.

So instead I chose the talks that I would have attended had it been in person, and ones that lined up on the virtual agenda. With all of these talks I want to emphasise that these are my own views and how I interpreted/understood the content presented to me, rather than the views of the speakers.

### Will 2020 see more organisations move to cloud based environments?

Amazon’s CTO, Werner Vogels, thinks so;

> "If nothing else, these past few months have truly ushered in an era in technology where we are seeing fundamental shifts in how everyone is feeling, not only in technology itself but how to access that technology, as well as how we build that technology” - Werner Vogels, Amazon CTO at AWS summit online

Werner Vogels opened the conference by talking about the unprecedented increase in demand for AWS due to the sudden shift to WFH practices, as individuals and organizations alike lean on the cloud to support them.

He predicted that in 2020 and beyond, we would see most organisations moving to a completely cloud based environment as it would allow their workers to access any application, service, or data, from anywhere in the world.

A sentiment I share, and something I'm not surprised to hear from the author of [All Things Distributed](https://www.allthingsdistributed.com/).

*What do you think - will more organisations be moving to Cloud based environments?*

#### For more on my AWS Summit series, check out the summaries on the talks I attended.
handy Ruby methods #4 - Hash#dig
Tags: ruby, beginners
Published: 2020-05-28 16:05:30

![cool diglet](https://media.giphy.com/media/Dbp2zw1MjeK5i/giphy.gif)

##### Before Ruby 2.3
```ruby
class AutomationController < ActionController::Base
  def automation_trigger_type
    params.fetch(:automation_rule, {}).fetch(:trigger_attributes, {}).fetch(:type).tap do |trigger_type|
      raise "unknown type" unless trigger_type.blank?
    end
  end
end
```

##### After Ruby 2.3
```ruby
class AutomationController < ActionController::Base
  def automation_trigger_type
    params.dig(:automation_rule, :trigger_attributes, :type).tap do |trigger_type|
      raise "unknown type" unless trigger_type.blank?
    end
  end
end
```

Life after Ruby 2.3 breathes an elegant expression to drill into a hash.

In the first example, `Hash#fetch` is invoked multiple times. It drills two levels into a nested params hash `:automation_rule`. A default is included to avoid the dreaded `NoMethodErrors on nil` error. 

This approach is verbose to say the least. It's painful to look at in the eyes of a Ruby dev.

The latter example is more terse. First, `Hash#dig` checks if the param key `:automation_rule` exists. If there's a key, it digs down a nested level and looks for the key `:trigger_attributes`. And so on..

Anywhere `Hash#dig` does not find a key, it returns nil in lieu of an error.

I notice `Hash#dig` used in Rails controllers. Digging into controller params is commonplace as an app builds in complexity. It's also prevalent digging through an API response where the returned payload is a deeply nested JSON object.

`Hash#dig` is a staple to write battle-tested code.
Why Ecommerce website?
Tags: ecommerce
Published: 2020-05-28 16:27:10

<a herf="https://webstod.com/ecommerce-development-company/">Ecommerce website designer</a> that is Fantastic is essential for turning website visitors. Ideally, your website's design must make the purchase process as simple, fast, and stress-free as you can. If your site isn't optimized for earnings, However great your advertising are, you might be losing customers.

If traffic click the moment they reach it, you can be wasting your ad dollars.

Keep the consumer in mind

Each and every detail of your site from product pictures to contact kinds could promote an individual's choice. That is why you need to keep the consumer in mind with each and every choice you make in regards to your website. User expertise is paramount for turning clients and turning traffic.

Not certain if your site has a fantastic user experience? Get another opinion by minding a buddy or perhaps hiring someone to check over your site . Have them rate your website on visual appeal ease, endurance, and total satisfaction.
The Blue Leopard Responsive Mobile & Web Page Completed
Tags: webdev, html, css, 100daysofcode
Published: 2020-05-28 15:52:46

Its been a Day3 of 100DaysOfCode and Have completed building a website...

Used Media Queries to make the webPage responsive.

Syntax:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qwh82imzlbxaoe4c6l2b.png)

Testing HTML CODE:
https://validator.w3.org/

Color Contrast Checker:
https://webaim.org/resources/contrastchecker/

Below is a glimpse of the Project:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dg1dawqcdv6mroehm3eq.gif)
JS / explain undefined, null, and NaN
Tags: javascript, interview, tutorial, learning
Published: 2020-05-28 15:39:02

We all know that `null`, `undefined` and `NaN` are falsy values, but what are their different use cases and where do they commonly appear? Here's a TL;DR version I've come with.

### Undefined

Undefined is always the default value of unassigned variables. We rarely if ever in practice assign undefined to a variable because JavaScript does that automatically for us. Every declared variable is initialized to undefined by default, and it's our job to replace that with an assigned value of our choice.

```js
let someVar;
console.log(someVar) // undefined
```

### null

Unlike undefined, null is never assumed by default. Null is typically used when we want to reset a variable; this is typically more clear than reassigning a variable to an empty string, 0, or undefined. It's null. Something happened, and we're explicitly resetting a variable to nothing - aka null. You will also frequently encounter null as a return value of a function. It's pretty context driven as to what that really means, so I'll leave it up to you to figure it out.

### NaN

Last but not least, there is NaN (not a number). Ironically though, NaN is of type number and therefore can be used in calculations. If you ever use NaN in a calculation, the result is also NaN. Think of NaN as like an error in a mathematical context. You made an invalid calculation, so this is what you get: NaN.

Most recently, I encountered NaN when I was multiplying a DOM node with an integer. How silly!

```js
// incorrect
const priceEl = document.getElementById("invoice");
const quantity = 4;
console.log(price * quantity); // NaN
```

This is what I should have done!

```js
// correct
const price = parseFloat(document.getElementById("invoice").innerHTML);
const quantity = 4;
console.log(price * quantity); // YaY, I got my total price
```

Admittedly, this was a pretty long read. So much for TL;DR... I'm sorry if you feel tricked (😅). Here's the real TL;DR:

- undefined
    - default value of uninitialized variables
- null
    - never assumed by default
    - explicitly typed by the programmer to signal many different things: the resource doesn't exist, something went wrong, etc.
- NaN
    - of type number and can therefore be used in calculations
    - used to signal that a miscalculation took place

PS: Admittedly, I'm not sure if I'm doing a good job with these pedagogic blog posts, so I need feedback! I would greatly appreciate it if you could leave some helpful reviews below (😁).

Warmly,
EK
Abstract World
Tags: oop, abstract
Published: 2020-05-28 15:38:33

Intro:

Hi,

Am I someone to listen to or be read/heard about? Possibly not. It might not make any sense at any point of what I say or decisions I make.
I spent most of my social life trying to prove my point about one or another point. With regret I can say it was never a success, but a failure in the eyes of those who ever had any contact with me.
So am I really that lousy?
One of my first harvests of success was back in the teenage days when I was a bass guitarist in a band. I got a contract offer that was implying a small, but stable income just for what I like doing in my own leisure, considering the fact I had to invest financially into this hobby before I would had got the contract.
Social opinions made their best to keep me were I was. No contract, no money, poor social status was the result of emotional pressure from my social environment. I mean, I was 18, what did I know?
These days I find it no different. Moving into IT industry put more questions into me, imposing the above complications.
If all of this might not made any sense so far, I have one thing to say, that I learned throughout many courses of traditional education - be sceptical, abstract as much as possible from what you see, hear, or feel.

P.S.
OOP is based around abstractions for a fair amount.
 
Thanks
Write flexible vue logic components in my team
Tags: vue, javascript, flexible
Published: 2020-05-28 15:35:25

---
title: Write flexible vue logic components in my team
published: true
description: flexible write vue.js components
tags: Vue.js, Javascript, flexible
---

Generally if we write logic component which same as computed but different with ui, my team just do this

### Vue.js `slot`

**slot** can render whatever you want, so if you have multiple logic components but different ui styles, the direct way is create multiple **SFC** which mean's single file component. 

If these **SFC** have many same logic code, like methods, computed etc, we shouldn't write multiple **SFC** anymore. we can write **parent** component and then **slot** what you want ui child.

```javascript
// parent.vue
<template>
<div class='parent'>
  <slot :list="list"/>
</div>
</template>

<script>
export default{
  props:{
    slug: String
  },
  methods:{ 
    method1(){},
    method2(){}
  },
  computed:{
    list(){
      return [...]
    }
  }
}
</script>

// AComponent.vue
<template>
 <Parent>
  <template slot-scope='{ list }'>
    <ul class='list'>
     <li v-for='item in list' >{{item}}</li>
    <ul>
  <template>
 </Parent>
</template>

<script>
// ....
</script>

<style scoped type='scss'>
.list{
  background: blue; // here background is blue
}
</style>

// BComponent.vue
<template>
 <Parent>
  <template slot-scope='{ list }'>
    <div class='list>
     <a v-for='item in list'>{{item}}</a>
    </div>
  <template>
 </Parent>
</template>

<script>
// ....
</script>

<style scoped type='scss'>
.list{
  background: red; // here background is red 
}
</style>

```

You can see we have two components and AComponent `list` dom is `ul`
and Bcomponent `list` dom is 'div'. also `AComponent` with `BComponent` has different background color.
 
Use **slot** we can easyily isolate logic code and ui style.


### Vue.js `Mixin`

Extract `mixin` which includes all the commons `methods`, `computed`, `props` .. then component A and B all mixin it.

```javascript
// _mixin.js
export defeat{
  props:{},
  methods:{ 
    method1(){},
    method2(){}
  },
  computed:{}
}

// A.vue
...
<script>
 import commonMixin from '_mixin.js'
 export default{
   mixin:{commonMixin}
   methods:{
     methoda(){
       this.method1()
     }
   }
 }
</script>
..

// B.vue
...
<script>
 import commonMixin from '_mixin.js'
 export default{
   mixin:{commonMixin}
   methods:{
     methodb(){
       this.method2()
     }
   }
 }
</script>
..

```

So we can reuse `commonMixin` methods and just write difference style ui isolated.

Vue.js [slot](https://vuejs.org/v2/guide/components-slots.html)
Add Tailwind CSS to your Quasar project in 5 minutes or less. 
Tags: javascript, tailwindcss, quasar, css
Published: 2020-05-28 15:22:26

### Why do this? 
I've been building a passion project of mine, [Jiujitsio](https://jiujits.io), in Quasar for the past few months and wanted to implement Tailwind styling when prototyping new or creating custom components. 

### Step 1 - Install Tailwind
> Install Tailwind via NPM or Yarn. 

![Install via npm or yarn screenshot](https://dev-to-uploads.s3.amazonaws.com/i/onwx5bc2rgcggnj4jqrk.png)

### Step 2 - Add Tailwind to your CSS. 
> Import Tailwind Directives. Add the following in between the `style` tags of any Quasar component you wish to style with Tailwind. 

![Tailwind directives screenshot](https://dev-to-uploads.s3.amazonaws.com/i/s79juh9oz1u4h82ttuoy.png)

### Step 3 - Process your CSS with Tailwind
> Since `Vue` styles are piped through PostCSS we are going to need to modify our `.postcssrc.js` file to require Tailwind. 

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

### Step 4 - Profit & Next Steps
> That's it! Any Quasar components in your project where you add the Tailwind directives will now respond to Tailwind class styling. You can also optionally also add a Tailwind config file (may be a follow up post) for further customization. 

Video Demo: 
* [Add Tailwind CSS to your Quasar project in 5 minutes or less](https://www.youtube.com/watch?v=c5jCzmModKo&feature=youtu.be)

Relevant Docs:
* [Tailwind Installation](https://tailwindcss.com/docs/installation/)
* [Quasar - Handling Webpack](https://quasar.dev/quasar-cli/handling-webpack)
useEffect Hook
Published: 2020-05-28 15:14:23

The useEffect hook helps us tap into the power of lifecycle methods within functional components without having to write class components.
This hook takes in a call back function as a parameter which basically contains the code we want to run every time the component re-renders. It is most commonly used to serve the function of a componentDidMount lifecycle method in order to communicate with a database or an API. However in this example, we will simply console log some information anytime the component re renders.

In order to use this, we do;

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

First we import `{useEffect}` from `react` at the top, then within the component we write out our code and it takes in the call back method that simply logs `How to use the useEffectHook`. Now, everytime the page first loads , the useEffect hook is rendered.


It is important to note that by default, when the page first loads and on every new update or change to any state depending on the number of states we have in our application, the useEffect hook runs and this may lead to unintended consequences. As such, the hook takes in a second parameter that specifies exactly when we want this hook to run. 

Lets add some state to our function component, using the `useState` hook earlier discussed and create a new state we call `person`. Now assume we want the data in our `useEffect` Hook to only re render  once on page load and whenever our `person` state is updated using the `setPerson` hook, we can add a second parameter to our `useEffect` to specify this.

Look at the following code example:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4x2drjfku2i6crdn1ee0.png)


Note how we added the second parameter `[person]` in the `useEffect` hook
in order to specify exactly when it renders.

In summary, the useEffect hook helps improve on the power of functional components and reduces the need to always write class based components.
重み付きUnion-Find木(Weighted Union-Find Tree)
Published: 2020-05-28 12:27:43

{% youtube sNMngyzPwF4 %}

## コード

```js
const Node = function (val) {
  this.val = val
  this.parent = this
  this.rank = 1
  this.weight = 0 // 親に対してのweight
}

const WeightedDisjointSet = function () {
  this.m = []
}

WeightedDisjointSet.prototype.add = function (val) {
  this.m[val] = new Node(val)
}

WeightedDisjointSet.prototype.merge = function (val1, val2, weight) {
  const p1 = this.find(val1)
  const p2 = this.find(val2)
  const w1 = this.weight(val1)
  const w2 = this.weight(val2)
  if (p1 === p2) {
    return
  }
  if (p2.rank <= p1.rank) {
    if (p1.rank == p2.rank) {
      p1.rank++
    }
    p2.parent = p1
    p2.weight = weight + w1 - w2
  } else {
    p1.parent = p2
    p1.weight = -weight - w1 + w2
  }
}

WeightedDisjointSet.prototype.find = function (val) {
  let cur = this.m[val]
  if (cur.parent != cur) {
    const root = this.find(cur.parent.val)
    cur.weight += cur.parent.weight
    cur.parent = root
  }
  return cur.parent
}

WeightedDisjointSet.prototype.diff = function (val1, val2) {
  const p1 = this.find(val1)
  const p2 = this.find(val2)
  if (p1 != p2) {
    return null
  }
  return this.weight(val2) - this.weight(val1)
}

WeightedDisjointSet.prototype.weight = function (val) {
  let weight = 0
  let cur = this.m[val]
  while (cur.parent != cur) {
    weight += cur.weight
    cur = cur.parent
  }
  return weight
}

let input = require('fs').readFileSync('/dev/stdin', 'utf8');
const lines = input.trim().split("\n")
let n, q, d

for (let i = 0; i < lines.length; i++) {
  if (i === 0) {
    [n, q] = lines[i].split(" ")
    d = new WeightedDisjointSet()
    for (let i = 0; i < n; i++) {
      d.add(i)
    }
  } else {
    const [com, x, y, w] = lines[i].split(" ").map(v => parseInt(v))
    switch (com) {
      case 0:
        d.merge(x, y, w)
        break;
      case 1:
        const diff = d.diff(x, y)
        console.log(diff == null ? '?' : diff)
        break;
      default:
        throw Error('invalid com')
    }
  }
}
```

## 問題

* https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/1/DSL_1_B