teleren/devto huggingface dataset:
BACKTRACKING
Tags: daa, backtracking
Published: 2021-05-06 11:41:55

Many problems which deal with searching for a set of solutions or for a optimal solution satisfying some constraints can be solved using the backtracking formulation.

To apply backtracking method, the desired solution must be expressible as an n-tuple (X1…Xn) where Xi is chosen from some finite set Si.

Often the problem to be solved calls for finding one vector that maximizes (or minimizes or satisfies) a criteria function P(X1,X2, --- Xn). Sometimes it seeks all vectors that satisfy P.

Suppose mi is the size of set Si. Then the number of n-tuples may satisfy the criteria function P(x1,x2,---,xn) are m=m1,m2,---mn. The brute force approach would be to form all these n-tuples, evaluates each one with P, and save those which yield the optimum and save those which yield optimum.

In backtracking we will get the same answer but fewer than m trials. Its basic idea is to build up the solution vector one component at a time and to use modified criteria function P(x1,x2, ---xi) (sometimes called bounding functions) to test whether the vector being formed has any chance of success.

The major advantage of this method is if it is realized that the partial vector (x1,x2,---xi) can no way lead to an optimal solution, then mi+1….mn possible test vectors can be ignored entirely.

Many problems solved using backtracking require that all the solutions satisfy a complex set of constraints. These constraints are classified as
1.Explicit constraints
2.Implicit constraints
How to start SpringBoot ElasticSearch using Spring Data
Tags: springboot, springdata, elasticsearch
Published: 2021-05-06 11:32:20

https://grokonez.com/spring-framework/spring-data/start-springboot-elasticsearch-using-spring-data

How to start SpringBoot ElasticSearch using Spring Data

<strong>Elasticsearch</strong> is a distributed, full-text search engine based on Lucene with JSON schema. In the tutorial, <strong>JavaSampleApproach</strong> will show you how to start <strong>SpringBoot ElasticSearch</strong> by sample code.

Related posts:
- <a href="https://grokonez.com/spring-framework/spring-data/solr-start-spring-data-solr-springboot">Apache Solr – How to start Spring Data Solr with SpringBoot</a>

<!--more-->
<div id="tuttoc" class="jsa-toc"></div>

<div id="tutcontents">
<h2>I. Technologies</h2>
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE
- ElasticSearch: 2.4.0
<h2>II. Practice</h2>
<strong><em>Step to do</em></strong>
- Create SpringBoot project
- Create a mapping model
- Create an ElasticSearch repository
- Create a test client
- Run & check result
<h3>1. Create SpringBoot project</h3>
- Using <strong>SpringToolSuite</strong>, create a SpringBoot project. Then add <strong>elasticsearch</strong> dependency:
<pre><code class="language-html">&lt;dependency&gt;
	&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
	&lt;artifactId&gt;spring-boot-starter-data-elasticsearch&lt;/artifactId&gt;
&lt;/dependency&gt;</code></pre>
<h3>2. Create a mapping model</h3>
Using annotation: <code>@Document(indexName = "javasampleapproach", type = "customer")</code>

More at:

https://grokonez.com/spring-framework/spring-data/start-springboot-elasticsearch-using-spring-data

How to start SpringBoot ElasticSearch using Spring Data
Some Essential things in JavaScript
Published: 2021-05-06 11:23:12

1.What are Cookies?
A cookie is a piece of data that is stored on your computer to be accessed by your browser. You also might have enjoyed the benefits of cookies knowingly or unknowingly. Have you ever saved your Facebook password so that you do not have to type it each and every time you try to log in? If yes, then you are using cookies. Cookies are saved as key/value pairs. 

2.Javascript Set Cookie

You can create cookies using document. cookie property like this.

document.cookie = "cookiename=cookievalue"

3.What is DOM in JavaScript?
JavaScript can access all the elements in a webpage making use of Document Object Model (DOM). In fact, the web browser creates a DOM of the webpage when the page is loaded.



4.JavaScript  Hoisting
Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local.
It allows us to call functions before even writing them in our code.

5.Variable Scope

In JavaScript, the scope of a variable is controlled by the location of the variable declaration, and it defines the part of the program where a particular variable is accessible.
there are three ways to declare a variable in JavaScript: by using the old var keyword, and by using the new let and const keywords.

6.JavaScript Arrow Function
Arrow function is one of the features introduced in the ES6 version of JavaScript. It allows you to create functions in a cleaner way compared to regular functions. 
For example:
// using arrow functions
const x = (x, y) => x * y;

7.JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add information about the code, warnings or suggestions so that end user can easily interpret the code.

8.splice() method in JavaScript
The JavaScript splice() method changes the elements of the array by replacing or removing the elements, in place.

9.What are JavaScript Data Types?

Following are the JavaScript Data types:

    Number
    String
    Boolean
    Object
    Undefined


10. What is === operator?

=== is called a strict equality operator, which returns true when the two operands have the same value without conversion.
Apache Solr – How to start Spring Data Solr with SpringBoot
Tags: apache, solr, springdata, springboot
Published: 2021-05-06 11:19:04

https://grokonez.com/spring-framework/spring-data/solr-start-spring-data-solr-springboot

Apache Solr – How to start Spring Data Solr with SpringBoot

Solr powers the search with highly reliable, centralized configuration, scalablility and more for heavily-trafficked websites and applications. So in the tutorial, <a href="https://grokonez.com">JavaSampleApproach</a> will show how to create a <strong>Spring Data Solr</strong> application with SpringBoot.

Related posts:
- <a href="https://grokonez.com/spring-framework/spring-boot/start-springboot-elasticsearch-using-spring-data">How to start SpringBoot ElasticSearch using Spring Data</a>

<!--more-->
<h2>I. Technology</h2>
– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.6RELEASE
- Solr 6.6.0
<h2>II. SpringBoot & Solr</h2>
<img src="https://grokonez.com/wp-content/uploads/2017/08/spring-data-solr-springboot-architecture.png" alt="spring data solr - springboot - architecture" width="377" height="309" class="alignnone size-full wp-image-7353" />

SpringBoot provides <code>spring-boot-starter-data-solr</code> <em>Starter</em> to support connecting and abstractions on top of Spring Data Solr.
<h3>1. Solr connection</h3>
In <strong>application.properties</strong> file, We use <code>spring.data.solr.*</code> to configure Solr connection.
Here is the details of sourcecode - <strong>SolrProperties</strong>:

<pre><code class="language-java">
@ConfigurationProperties(prefix = "spring.data.solr")
public class SolrProperties {

	/**
	 * Solr host. Ignored if "zk-host" is set.
	 */
	private String host = "http://127.0.0.1:8983/solr";

	/**
	 * ZooKeeper host address in the form HOST:PORT.
	 */
	private String zkHost;
	
	...

}</code></pre>

By default the instance will attempt to connect to a server using <code>http://localhost:8983/solr</code>. And we can add <code>@Bean</code> with <strong>SolrClient</strong> type to override it.
<h3>2. Spring Data Solr repositories</h3>
We use <code>@SolrDocument</code> to create Solr document:

More at:

https://grokonez.com/spring-framework/spring-data/solr-start-spring-data-solr-springboot

Apache Solr – How to start Spring Data Solr with SpringBoot
What I learnt from the GSOC 2021 Application
Tags: gsoc, googlecloud, googlesummerofcode, google
Published: 2021-05-06 11:12:11

Here are all the problems that I faced while applying to GSOC 2021 as a learner🙂

This is my first article😊

It all started in the month of January. When I started my Open Source contributions, I faced a lot of problems😢 using git and git-bash but slowly I got the grip and started making Pull Request to some of my own repositories. With this, I uploaded all my project to the Github website. All this took time and I reached the end of January. By the beginning of February, I planned to raise some issue to some popular repo. I raised some documentation and some typing errors. These helped me gained some knowledge on how to raise a PR and how to write an issue template. At the end of February, I shortlisted some organisation🧧 based on my interest and skill set which are present in GSOC as well. Then I started reading their codebase to understand the working of the web app. In some days time, I was able to contribute some examples to the website. Google then released some changes for the GSOC program 😮

Some major changes 
- Time period was reduced to 1.5 months
- Stipend reduced to $1500
- More students to be selected this year
- Organisations reduced 

The number of organisations selected for this year was nearly the same, some organisations were replaced with new ones and some removed. The application process was the same as for the previous years. We have to prepare a proposal and submit it to the organisation before the deadline. The main ingredient of the application process is to prepare a really good proposal, which in itself is a tough task. I have applied for the Processing organization. It was a really good learning experience for me as a learner I get to know how to communicate with others and build a better connection with the Open Source Community. 

Thanks for scrolling 🤗
TIL that you can pass variables to Ansible’s import_playbook module
Tags: todayilearned, ansible
Published: 2023-05-19 20:39:51

---
title: TIL that you can pass variables to Ansible’s import_playbook module
published: true
date: 2021-05-06 10:51:00 UTC
tags: TIL,ansible
canonical_url: https://www.zufallsheld.de/2021/05/06/til-that-you-can-pass-variables-to-ansibles-import_playbook-module/
---

Using Ansible’s [import\_playbook](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/import_playbook_module.html) module I was always under the impression that the module accepts no parameters and [boldly stated so](https://www.reddit.com/r/ansible/comments/n5nic6/passing_variables_to_an_imported_playbook/gx2abus)! However another commentor helpfully pointed out that I was wrong.

Here’s an example. The first playbook (`importer_playbook.yml`):

```
- import_playbook: imported-playbook.yml
  vars:
    foo: hunter2

```

… simply imports a second playbook (`imported_playbook.yml`):

```
- hosts: localhost
  tasks:
  - debug:
      var: foo

```

Running the importer-playbook results in this:

```
> ansible-playbook importer-playbook.yml
PLAY [localhost] 
********************************************
TASK [debug] 
********************************************
ok: [localhost] => {
    "foo": "hunter2"
}

PLAY RECAP 
********************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

```

It’s even stated in the documentation as an example. However I did not scroll this far down. :(
Duplicate HashSet entries with original class
Tags: java
Published: 2021-05-06 09:36:28

---
title: Duplicate HashSet entries with original class
published: true
description: 
tags: java
//cover_image: https://direct_url_to_image.jpg
---

# TL;DR
You should implement both of `hashCode` and `equals` for using in HashSet.

# Env
```
openjdk version "1.8.0_265"
OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_265-b01)
OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.265-b01, mixed mode)
```

# Try
Below MyModel class is my sample class with some properties and provide same hashcode with same property values.
However `equals` returns false.

```java
public class MyModel {
    private String name;
    private int age;

    public MyModel(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        return false;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

```

```java
import org.junit.Test;

import java.util.HashSet;

import static org.junit.Assert.*;

public class MyModelTest {

    @Test
    public void testHashSet() {
        HashSet<MyModel> set = new HashSet<>();

        // Add models with same property values.
        set.add(new MyModel("taro", 10));
        set.add(new MyModel("taro", 10));

        // We want the set has only 1 entry.
        assertEquals(1, set.size());
    }

}
```

But, you will see the result as below.

```
java.lang.AssertionError: 
Expected :1
Actual   :2
```

For pass the assertion, you should implement `equals` also.

```java
public class MyModel {
    private String name;
    private int age;

    public MyModel(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MyModel myModel = (MyModel) o;

        if (age != myModel.age) return false;
        return name != null ? name.equals(myModel.name) : myModel.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

```

# Why
In OpenJDK, HashSet depends on HashMap implementation.

- HashSet::add

https://github.com/openjdk/jdk/blob/jdk8-b120/jdk/src/share/classes/java/util/HashSet.java#L219

- HashMap::putVal

https://github.com/openjdk/jdk/blob/jdk8-b120/jdk/src/share/classes/java/util/HashMap.java#L633-L634
ACME - The Accordion Web Component in 187 Bytes
Tags: webcomponents, webdev, javascript, html
Published: 2021-05-06 10:40:22

---
title: ACME - The Accordion Web Component in 187 Bytes
published: true
description: Build a Accordion Web Component with default HTML Elements details and summary
tags: WebComponents,WebDev,JavaScript
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yigtbnpc5z9pqgs31ser.png
---

### TL;DR;

* Do **not _unlearn_** HTML when you build Web Components.
* "Design Systems" add bloated code to create an Accordion.
* Use the default ``<details>`` and ``<summary>`` elements to built a ``<details-accordion>`` Custom Element.

### _If you have a hammer,_
### _everything starts to look like a nail_

Now we got this great technology **Web Components**, it is easy to get excited and use _Custom Elements_ for **everything** in your _Design System_:

I won't name the Design Systems, and won't link to bloated JavaScript code.

Their HTML looks like this:

```html
<ACME-accordion>
    <ACME-accordion-item label="..." content="Content 1" expanded></ACME-accordion-item>
    <ACME-accordion-item label="..." content="Content 2"></ACME-accordion-item>
</ACME-accordion>
```
or
```html
<ACME-accordion>
    <ACME-accordion-panel>
        <div slot="summary">...</div>
        <div>...</div>
    </ACME-accordion-panel>
    <ACME-accordion-panel>
        <div slot="summary">...</div>
        <div>...</div>
    </ACME-accordion-panel>
</ACME-accordion>
```
or
```html
<ACME-accordion>
    <h3 slot="invoker"><button>...</button></h3>
    <p slot="content">...</p>
    <h3 slot="invoker"><button>...</button></h3>
    <p slot="content">...</p>
</ACME-accordion>
```

## Good, old, HTML

The Open/Close functionality **_is_** available in **standard HTML** with the ``<details>`` and ``<summary>`` elements.

#### Add a **7** line _vanilla_ Web Component:

```js
customElements.define('details-accordion', class extends HTMLElement {
 connectedCallback() {
  this.onclick = evt => [...this.children].map(detail => {
   !evt.ctrlKey && detail.toggleAttribute("open", evt.target == detail);
  });
 }
});
```

#### To create an Accordion:

```html
<details-accordion>
    <details open>
        <summary>...</summary>
        ...
    </details>
    <details>
        <summary>...</summary>
        ...
    </details>
    <details>
        <summary>...</summary>
        ...
    </details>
</details-accordion>
```

**hold down the Ctrl key to open multiple ``<details>``**

{% jsfiddle https://jsfiddle.net/WebComponents/d0sh9q7f result,html,js,css %}


#### Notes:

* There is no shadowDOM, so easily apply any CSS styling you want
* ``<details>`` **itself** also has a click handler and will open/close!
* For every click on ``<details-accordion>`` **all children** are toggled; 
* using ``.map`` instead of ``.forEach`` saves 4 bytes

<br>
<hr>
<br>

{% jsfiddle https://jsfiddle.net/WebComponents/62f1eLay result,html,js %}
what is hamiltonian?
Tags: hamiltonian
Published: 2021-05-06 10:38:53

what is hamiltonian cycle ?  
In a connected graph ,a closed walk that vists every vertex  of the graph G exactly once except the starting and ending vertices .it is called hamiltonian cycle.

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

what is hamiltonian path? 
In a connected graph ,an open walk that visits every vertex of the graph G exactly once.but it containan open walk.

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

what is hamiltonian graph?
A graph G is said to be hamiltonian graph if it contain a hamiltonian cycle. 


 ![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hwhq7v3cwb7r22d7qb20.png)
A case of premature optimization?
Tags: react, webdev, optimization, typescript
Published: 2021-05-06 10:36:40


Recently I ran into an interesting problem in a live coding session. The interviewer found a problem with my code and asked me to improve the code. Take a look at the following code. What do you think can be optimized?

```typescript
const HeadLine: React.FC<{ text: string }> = ({ text }) => <h1>{text}</h1>;
const TextBlock: React.FC<{ text: string }> = ({ text }) => <p>{text}</p>;

export interface Item {
  type: 'Headline' | 'Block';
  text: string;
}

export const RenderBlock: React.FC<{ block: Item }> = ({ block }) => {
  const { text, type } = block;
  const RenderMap = {
    Headline: () => <HeadLine text={text} />,
    Block: () => <TextBlock text={text} />,
  };

  return RenderMap[type]();
};
```

## Solution

When you use the RenderBlock component, the constant RenderMap is going to be recreated every time the component is used. You can extract the constant and put it into a higher scope to solve that problem.

The optimized code would look like this:

```typescript
const HeadLine: React.FC<{ text: string }> = ({ text }) => <h1>{text}</h1>;
const TextBlock: React.FC<{ text: string }> = ({ text }) => <p>{text}</p>;

export interface Item {
  type: 'Headline' | 'Block';
  text: string;
}

const RenderMap = {
  Headline: (text: string) => <HeadLine text={text} />,
  Block: (text: string) => <TextBlock text={text} />,
};

export const RenderBlock: React.FC<{ block: Item }> = ({ block }) => {
  const { text, type } = block;
  return RenderMap[type](text);
};
```
## How much did we improve the code?
If we benchmark a similar piece of code with [js.bench](https://jsben.ch/yY9aT) we can see a 15% performance improvement. Technically we can see a real-world improvement. More operations can be done in the same amount of time (390000ops vs 400000ops)

The downside is that the code is harder to read (it is not reading a single block but jumping up and down in the code) and harder to extend (if parameters change for example).

In a real-world environment, you probably will have a maximum of 100 instances of this component. By optimizing the code we probably will save only a couple of microseconds.

I would argue that this is a case of premature optimization. It will not have any noticeable benefit for the end-user, while at the same time make the developer experience worse. This is an issue that would be needed to be discussed with the team to further define the style of how the code is written in the codebase.

In the end, this is a coding interview, so there is no real debate. The interviewer is expecting a certain solution. Even if your solution is correct, it might not be correct because you did not match the values and expectations of the interviewer. – I probably should have answered: “Not everything that can be optimized should be optimized.”

_Originally published at_ https://codeandchaos.com/excercise/jobinterview/2021-05-01-ReactOptimizationQuestion/ on May 1, 2021.
Make your first web app using Python and Flask!
Tags: python, flask, webdev
Published: 2021-05-06 10:26:40

Flask is a micro web framework for Python that's simple and easy to use. 

From getting Flask installed, to understanding the basic concepts behind a Flask app, as well as writing our first "Hello World" app, we'll cover it all. So without further delay, let's jump in!

Before you begin Developing your first web app with Python and Flask requires an understanding of some [Basic Python programming](https://pythonbasics.org) concepts like: variables, functions, loops, conditionals, objects, and classes. 

It also requires an understanding of how to write code that can run on a web server. But it's easy to [put your Python apps online](https://www.pythonanywhere.com/?affiliate_id=00535ced) with a few clicks.

## Hello world

In a terminal, we use pip to install Flask.

```
pip install flask
```

As an example, let's take a look at a very simple Flask app. First of all, let's create a new directory for our app:

```bash
$ mkdir flask-app 
$ cd flask-app
```

In this directory, we're going to start with a "hello world" app

Now let's create a file called hello.py and add the following to it:

```python
# hello.py
from flask import Flask
app = Flask(__name__)
def hello_world():
    return 'Hello World'
```

We will then create another file called app.py that imports our hello function and maps it to the root of our web app:

```python
# app.py
from flask import Flask
from hello import hello_world
app = Flask(__name__)
app.add_url_rule('/', hello_world)
app.run(host='localhost', port=5000)
```

Finally, we run the dev server:

```
python app.py
```

And now we can go to localhost:5000 and see "Hello World".

## Routes

Flask provides routes, which are functions that map a URL to a function call. The default behavior is to call the function view , but you can add your own functions to be called in the following manner:

```python
from flask import url_for 

@app.route('/') 
def index(): 
    return 'This is the index page'
```

URLs starting with / will be handled by this function; if you route with /admin/ then only URLs starting with /admin/ will be handled by this function (see below).

```python
from flask import url_for 

@app.route('/admin') 
def admin(): 
    return 'This is the admin page'
```

You can return not only text, but also HTML, Javascript, CSS etc. See [this example](https://pythonspot.com/flask-web-app-with-python/). You can [interact with databases](https://python-commandments.org/flask-crud/) and also use it for [APIs](https://pythonprogramminglanguage.com/python-flask-rest-api/)

If you are new to Flask, I suggest [this course](https://gum.co/IMzBy)