teleren/devto huggingface dataset:
Difference between print() and println() in Java
Tags: java, programming, oop
Published: 2020-11-28 07:34:10

#Print(): 
print() function  in Java is used to show a text on the console. This text is approved as the parameter to this function in the form of String. This function prints the typescript on the console and the pointer leftovers at the end of the typescript at the console. 

##Dissimilarity between print() and println() in Java
The following printing taking place from just here.
###Varioud println() methods:
```
Various print() functions:
void print(boolean b) – Prints a boolean value.
void print(char c) – Prints a char..
void print(char[] s) – Prints an array of char.
```

##Example
```
import java.io.*; 
class KodLogs { 
    public static void main(String[] args) 
    { 
        // The pointer will remain 
        // just afterward the 1 
        System.out.print("Gf1G12"); 
        // This will be printed 
        // just after the Gf1G12 
        System.out.print("Gf1G12"); 
    } 
} 


Output:
Gf1G1GfG2
```
[Read more](https://www.kodlogs.com/blog/2451/difference-between-print-and-println-in-java)
What does %= mean in Java?
Tags: java, oop, programming
Published: 2020-11-28 07:29:54

In this article, a detailed explanation of assignment operators and its uses is observed which in particular will be the Modulus AND assignment operator ( %= ).
#Assignment Operators
You know different operators are supported by the Java language and one of its kind is the assignment operator. These assignment operators are basically divided into eleven types and are shown below

1. Simple assignment operator “ = “

2. Add AND assignment operator “ += “

3. Subtract AND assignment operator “ -= “

4. Multiply AND assignment operator “ *= “

5. Divide AND assignment operator “/=”

6. Modulus AND assignment operator “%=”

7. Left Shift AND assignment operator “<<=”

8. Right Shift AND assignment operator “>.=”

9. Bitwise AND assignment operator “ &=”

10. Bitwise exclusive OR and  assignment operator “ ^= “

11. Bitwise inclusive OR and assignment operator “!=”

##Approach
The modulus AND operator (%=) will perform modulus operation of the two operands and the obtained result is allocated to the left operand of the statement. [Read more](https://www.kodlogs.com/blog/2604/what-does-%25-mean-in-java)
Best Cyber Monday Deals on Online Courses- 25%-100% OFF
Tags: datascience, machinelearning
Published: 2020-11-28 07:24:35

This is the best time to grab your favorite online course from e-learning platforms right from **Udacity, Coursera, Datacamp, Codecademy, edX, and more.** These courses and certificates will help you propel your career. 

So without further ado, let’s get **Best Cyber Monday Deals on Online Courses.**

**[Click to continue Reading...](https://www.mltut.com/best-cyber-monday-deals-on-online-courses-huge-discount-on-courses/#1-coursera-black-friday-sale-[100-off])**
#13 Nesting Documents
Tags: mongodb
Published: 2020-11-28 07:22:23

```
const mongoose = require('mongoose');
const assert = require('assert')
const Author = require('../models/author');

describe('Nesting Documents', function(){

    //Create tests
    it('Create an author with sub-documents', function(done){

        var pat = new Author({
            name: 'Patrick Ruffus',
            books:[{title:'Name of the wind', pages: 400}]
        });
        pat.save().then(function(){
            Author.findOne({name:'Patrick Ruffus'}).then(function(record){
                assert(record.books.length === 1);
                done();
            })
        })
    })

    it('Add a book to an existing author', function(done){

        var rus = new Author({
            name: 'Ruskin Bond',
            books:[{title:'The eyes have it', pages: 400}]
        });
        rus.save().then(function(){
            Author.findOne({name:'Ruskin Bond'}).then(function(record){
                record.books.push({title:"7 husband", pages:200});
                record.save().then(function(){
                    Author.findOne({ name: 'Ruskin Bond' }).then(function(record){
                        assert(record.books.length===2);
                        done();
                    })
                })
            })
        })
    })
})
```
Debugging Strategies
Tags: javascript, development, code, debug
Published: 2020-11-28 07:14:57

As developers we debug more than we write new code.

Throughout the years I refined some techniques that helped me structure my problem solving and debugging skills.

## Simplify

Remove everything that is not part of what you are trying to fix.
Comment out code, remove unused modules, remove all unrelated code that doesn't affect what you are trying to reproduce. If what you removed fixed the problem, good job, you might have found the cause.

## Read the error messages carefully

I can't stress enough how much not paying attention to errors messages hold me back to becoming a better developer. Usually these messages give you a lot of context and a starting point. Specially if it's a widely used framework or library, the chances of you just Googling the error message and finding the answers right away are really high.

## Back tracing

A system is usually constructed from units called functions. Every function might called another function and then the call stack is born. Start from the function where the error was thrown and step back on the call stack using a debugger and try to find the point where the error occurred.

## Rubber duck

Have you ever simply explained what you were trying to achieve to a colleague and all of a sudden you knew what was wrong? Well, me too! What happens is that we usually get caught up in the details of a solution and forget the big picture, what we are really trying to achieve. Externalizing your thoughts and clearly communicating them helps you spot the reasons you are failing.
If you colleague is busy, have a rubber duck on your desk and that will do.

## Minimal reproducible case

Use tools such as [Stackblitz](https://stackblitz.com/) or [JSfiddle](https://jsfiddle.net/) and try to replicate the same scenario. With this approach you can focus only on the problem instead of also having to deal with your project dependencies, compilation time and so on.

## Log points

On Chrome you can use log points which are basically a marker on a line that when that line is executed the provided log point expression will be called, i.e. `console.log()` without having to compile every time you want to log something.

This is very useful when debugging async code like Observables.

## Conclusion

Up your debugging game! It will save you tons of time and make you a more efficient developer.
Using an iphone in 3rd world country can hurt you
Tags: webdev, mobile, performance
Published: 2020-11-28 06:42:02

Recently, I was doing speed test on a new website for a client, and I was puzzled by Chrome's report saying that my images were too big.

I looked at the details and it seems like the browser is using a way bigger image than what I think it should use. All my images use srcset with w descriptor to provide different sizes of images for different device resolution, and on iphone it shows an image of 2600px being used. dang. How can it be so big when the phone screen is relatively small? I spent hours thinking it was a bug and tried various ways to fix it. 

It turned out that new devices have this thing called DPR (device pixel ratio), and apparently high end devices may have very high DPR such as 3 or even more. What it means is that now if the normal css pixel is 500, you need an image of 1500px for the given device.

This can have huge impact on the site performance because the device needs to download 3 times more data (more or less). For third world countries like mine where 4g feels sluggish, this can really delay the rendering of the site. For the clients they have to wait longer, and also unknowingly pay for more bandwidth.

Do we really need those big images? Only sometimes. And should not come at the cost of potential users abandon the site due to slow load.

For people using lazysizes, you can use the optimumux plugin to set the optimal DPR. The default is 1.6 mx which is reasonable IMHO. 

For above the fold content which should not be loaded lazily IMHO, I'm looking into the setting of srcset with the x descriptor and sizes. I will update this post once I have a solid answer.
React + Firebase + Stripe = Fireact, the open-source project for your next SaaS product.
Tags: react, firebase, opensource, saas
Published: 2020-11-28 06:35:30

> A new version has been released as NPM packages to make the project more flexible and customizable. Please read [the Fireactjs update announcement](https://dev.to/chaoming/fireactjs-my-open-source-npm-packages-for-building-saas-using-react-firebase-and-stripe-4n4j).



Many SaaS products are moving to React these days, and my own product has been through the same journey this year.

As I started the project, I decided to use Firebase for authentication, hosting and storing data. So I was looking for an existing solution. However, I couldn't find one so I built the first version of Fireact back in May 2020.

But that's not enough. As with most SaaS applications, I needed the feature to collect subscription payment. Now, the project version 2 is released.

##Key features are:

- Single-sign-on supporting Google, Facebook, Microsoft and a wild range of sign-in methods.
- Stripe integration to manage subscription accounts and payments.
- Supporting multiple subscription accounts per user
- User permission management in subscription accounts
- User permission framework for the development of your SaaS functionalities

##Why Fireact

I hope the project can be a good starting point for developers working on SaaS projects. It comes with the features you need to manage users and subscriptions so you don't need to spend time on developing these features again. Just focus on the key functionalities of your SaaS project, it will save you tons of time.

##Contribution

This is the first open-source project I created. If you like the project, please support it by contributing code, documentation, or simply spreading the word.

Here is the Github link: https://github.com/chaoming/fireact

Here is the demo: https://fireact-e1bdc.firebaseapp.com/
Use testing credit card `4242 4242 4242 4242` to create your testing subscription account.

Any feedback is welcomed.

Cheers,
#12 Relational Data
Tags: mongodb
Published: 2020-11-28 06:27:32

Suppose, Author(name, age, books) and Book(title, pages) are two relations.
In the following way we construct it in MongoDB
```
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const BookSchema = new Schema({
    title: String,
    pages: Number 
});

const AuthorSchema = new Schema({
    name: String,
    age: Number, 
    books: [BookSchema] 
})

const Author = mongoose.model('author', AuthorSchema);

module.exports = Author;
```
`books: [BookSchema]` tells us that `books` property is an array where the array elements will be of the form `BookSchema`
Element prototyping workflow with Tailwind CSS for a Rails + Stimulus app
Tags: rails, stimulus, tailwindcss
Published: 2020-11-28 06:24:14

In my latest project I am using a combination of Rails, Stimulus JS, and Tailwind CSS. After some initial effort, I decided I would rather not do all of the new element prototyping in my Rails development environment.

Instead, I created a separate environment for rapid HTML / TailwindCSS / Stimulus JS prototyping.

Some of the main features of this environment include:
* Live-reloading for Tailwind.css changes, as well as both HTML and JS changes.
* Focus on the design and Javascript UX before focusing on merging that with Ruby code.
* Keep design and development workflows more separated.

So far, I have just used this environment to create interactive elements that I then easily port over to my Rails project, simply by copying the HTML partial, Stimulus controller(s), and my new @apply's to my Rails project. I am planning on using it to build out whole pages using multiple partials, but I just set this up today and have yet to see how effective it is for such a task.

Try out the environment if you are itching for a new workflow for your Rails/Stimulus/Tailwind projects!

https://github.com/vincenttaglia/RST-Element-Prototype
Working with Forms in React
Tags: tutorial, react, javascript, popular
Published: 2020-11-28 06:09:08

>Almost every application needs to accept user input at some point, and this is usually achieved with the venerable HTML form and its collection of input controls. If you’ve recently started learning React, you’ve probably arrived at the point where you’re now thinking, “So how do I work with forms?”

This article will walk you through the basics of using forms to React to allow users to add or edit information. We’ll look at two different ways of working with input controls and the pros and cons of each. We’ll also take a look at how to handle validation and some third-party libraries for more advanced use cases.

#Uncontrolled Inputs
The most basic way of working with forms in React is to use what is referred to as “uncontrolled” form inputs. What this means is that React doesn’t track the input’s state. HTML input elements naturally keep track of their own state as part of the DOM, and so when the form is submitted we have to read the values from the DOM elements themselves.

In order to do this, React allows us to create a “ref” (reference) to associate with an element, giving access to the underlying DOM node. Let’s see how to do this:
```
class SimpleForm extends React.Component {
  constructor(props) {
    super(props);
    // create a ref to store the DOM element
    this.nameEl = React.createRef();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    alert(this.nameEl.current.value);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>Name:
          <input type="text" ref={this.nameEl} />
        </label>
        <input type="submit" name="Submit" />
      </form>
    )
  }
}
```
As you can see above, for a class-based component you initialize a new ref in the constructor by calling `React.createRef`, assigning it to an instance property so it’s available for the lifetime of the component.

In order to associate the `ref` with an input, it’s passed to the element as the special ref attribute. Once this is done, the input’s underlying DOM node can be accessed via `this.nameEl.current`.

[Read More on Sitepoint], **Thank You**
Released gem MarkdownToRspec💎✨
Tags: ruby, markdown
Published: 2020-11-28 05:42:52

I released My new Gem MarkdownToRspec💎✨

https://rubygems.org/gems/markdown_to_rspec

`MarkdownToRspec` converts text in markdown format into text in `RSpec` format.

This gem uses `RDoc::Markdown` to parse the text in markdown format, generates `RDoc::Markup::Document`, and then generates an text in `RSpec` format from it.

Usage

``` ruby
$ gem install markdown_to_rspec
```

for CLI

``` sh
$ markdown_to_rspec -f `MARKDOWN_FILE_PATH`
#=> return A string in RSpec format
$ markdown_to_rspec -t `MARKDOWN__TEXT`
#=> return A string in RSpec format
```

for in ruby code

``` ruby
require 'rspec_to_markdown'
markdown = "A string in markdown format"
MarkdownToRspec.to_rspec(markdown)
#=> return A string in RSpec format
```

Sample

markdown

``` md
# Details.
A screen to check something
ref: https://example/com/tickets/1

## Initial Display.

### When a record exists.
* The title must be displayed.
* The text must be displayed.

### When the record does not exist.
* The title should not be displayed.
* The text should not be displayed.

### Other cases.
* 500 pages to be displayed.

# Index.
A screen to check something

## Initial Display.
* The items must be displayed.
```

converted to `RSpec`

``` ruby
RSpec.describe 'Details.' do
  # A screen to check something
  # ref: https://example/com/tickets/1
  describe 'Initial Display.' do
    context 'When a record exists.' do
      it 'The title must be displayed.' do
      end
      it 'The text must be displayed.' do
      end
    end
    context 'When the record does not exist.' do
      it 'The title should not be displayed.' do
      end
      it 'The text should not be displayed.' do
      end
    end
    context 'Other cases.' do
      it '500 pages to be displayed.' do
      end
    end
  end
end
RSpec.describe 'Index.' do
  # A screen to check something
  describe 'Initial Display.' do
    it 'The items must be displayed.' do
    end
  end
end
```


Please use it if you like :wave:
Guides for creating an appealing accessible web design
Tags: webdev, design, develop, webdesign
Published: 2020-11-28 05:30:31

Welcome to my humble abode. Here, I shall guide you to achieve your best in web design. To create a visually pleasing and accessible website, I will start by explaining some basics to start with and then branch out. I have put together some quick helpful tips and resources to help you in creating your best design. Without further ado, lets get started.


1. Moodboard & Wireframes

Think of a Moodboard as a sketchbook, start adding your ideas, pictures, colors, fonts, whatever you want to set the *mood* your website gives and of course *CONSISTENCY IS KEY*! Doing this allows you to get a sense of what your goal is, what your colors will be, what fonts you want to use and so on. Move on to the wireframing process once this is complete.

Create a wireframe, setting up the skeleton of your website, decide where and how you want your headers, sections, and buttons to be while also thinking how your user will be directed. Spending some time thinking will save you valuable hours in your design process. A wireframe is a quick and effective way to detect issues early on in your design process, and remember its best to keep your layout simple.

3. Your design

When you open Figma, inDesign, inVision, Xd, or whatever tool you'll use for designing, you want to start adding what you did in your wireframe. While slowly adding in your pictures, adding in your text and font styles you chose as well as applying the color scheme you chose, I am going to mention a few things to look out for during the process. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/n1j2lg7upphnpivfl3kj.PNG)
a. Set a color pallet, it helps keep you organized and not have shades lighter or darker. Check out this article for more information.
   https://www.addthis.com/blog/2015/08/18/why-the-right-color-palette-matters-for-your-brand/#more-12006.

b. Pick 2-3 fonts, its best not to overload the page with different fonts because some catch the eye more than others and information gets lost. Here are two articles, 1 trending fonts:
https://www.addthis.com/blog/2015/02/23/top-trending-fonts-for-graphic-designers/#.X8AqxmhKgUG
and 2 why we keep the fonts number at a minimum: 
https://uxplanet.org/10-tips-on-typography-in-web-design-13a378f4aa0d

c. Allow even spacing and don't be afraid of white space. Keeping hierarchy allows you to nicely section the website. Your navigation bar/menu must be simple and easy to navigate.

4. Accessibility

Lastly, I wanted to set a separate section for this because you MUST remember to keep your design within accessibility guidelines. Font to small for elder folk to read, or certain colors like red that people with colorblindness cant see. Here is an article you can read more about regarding this topic: 
https://www.w3.org/WAI/GL/WCAG20/
You should also put in the extra effort to make your site load quickly for those with slow internet connection to view it. And lastly, allowing your site to be viewable on mobile, tablets, and larger monitor screens. 

Thanks! I hope this was quick and helpful for you all.
JavaScript removing HTML tags
Tags: javascript, html
Published: 2020-11-28 05:01:33

I recently needed to remove all HTML from the content of my own application.

In this case, it was to share a plain text version for meta descriptions, but it can be used for several outputs.

Today I'll show you two ways of doing this, which are not fully safe if your application accepts user inputs.

Users love to break scripts like this and especially method one can give you some vulnerabilities.

## 1. JavaScript removing HTML tags with innerHTML

One method is to create a temporary HTML element and get the innerText from it.

```js
const original = `<h1>Welcome to my blog</h1>
<p>Some more content here</p><br /><img alt="a > 2" src="img.jpg" />`;

let removeHTML = input => {
	let tmp = document.createElement('div');
	tmp.innerHTML = input;
	return tmp.textContent || tmp.innerText || '';
} 
console.log(removeHTML(original));
```

This will result in the following:

```js
'Welcome to my blog
Some more content here'
```

As you can see we removed every HTML tag including a bogus image.

## 2. JavaScript removing HTML tags with regex

My personal favourite for my own applications is using a regex, just a cleaner solution and I trust my own inputs to be valid HTML.

How it works:

```js
const original = `<h1>Welcome to my blog</h1>
<p>Some more content here</p><br /><img src="img.jpg" />`;

const regex = original.replace(/<[^>]*>/g, '');
console.log(regex);
```

This will result in:

```js
'Welcome to my blog
Some more content here'
```

As you can see, we removed the heading, paragraph, break and image.
This is because we escape all `< >` formats.

It could be breached by something silly like:

```js
const original = `<h1>Welcome to my blog</h1>
<p>Some more content here</p><br /><img alt="a > 2" src="img.jpg" />`;
```

I know it's not valid HTML anyhow and one should use `&gt;` for this.

But running this will result in:

```js
'Welcome to my blog
Some more content here 2" src="img.jpg" />'
```

It's just something to be aware of.

You can have a play with both methods in this Codepen.

{% codepen https://codepen.io/rebelchris/pen/Exyqbqa %}

### 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)
Quick difference in ruby's Each vs Map vs Collect vs Select
Tags: ruby, rails, codenewbie, webdev
Published: 2020-11-28 04:54:34


Ruby iterators simply explained with an example

## Each vs Map vs Collect vs Select

All of them iterators an array but the difference is on the return value 

```
array = [1,2,3,4]
```

Below code prints 2,3,4,5 but returns original array
```
array.each do |a|
  puts a+1
end
2
3
4
5
=> [1, 2, 3, 4]
```

Map and Collect have the same functionality with a different name. Iterates through each element and return a new array of elements returned by the block
```
array.collect {|a| a + 1}
=> [2, 3, 4, 5]
```

Select iterates and return new array of elements for which given block is true
```
 array.select  { |num|  num.even?  } 
[2, 4]
```

###Summary:

Each -> returns same array
Map & collect -> returns new array with code executed in block for each element
Select -> return new array for the which give block is true

In next post, we will look into more enumerable methods which are handy to know.
JavaScript Modern Interview Code Challenges
Tags: javascript, webdev, interview, career
Published: 2020-11-28 04:53:01

"JavaScript Modern Interview Code Challenges" is a collection of __180+ modern interview code challenges on JavaScript__ suitable for interviewees, interviewers, knowledge test and practice.

The challenges are divided into 5 sections topic wise and each section will have list of questions generally from easy to advanced level with increasing difficulty. The challenges are suitable for beginners to experts.

You can find it on github:
{% github sadanandpai/javascript-code-challenges %}

Now crack your next JavaScript interview with confidence