Trending December 2023 # How Does Mongodb Unique Works With Examples # Suggested January 2024 # Top 15 Popular

You are reading the article How Does Mongodb Unique Works With Examples updated in December 2023 on the website Kientrucdochoi.com. We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested January 2024 How Does Mongodb Unique Works With Examples

Introduction to MongoDB Unique

MongoDB’s Unique Constraint makes certain that the fields indexed in it, do not store duplicate values for the same field, i.e., making sure the uniqueness of fields. By default, MongoDB enforces this unique constraint on the “_id” field, while inserting new data. One of the major responsibilities is to ensure no duplicate data has been stored in a single key. We also have restrictions here, like MongoDB will be unable to establish a unique index on any specific field, in case if the collection somehow has already stored any data that would breach the feature of unique constraint for the index.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Syntax:

Now that we have understood what Unique Constraint in MongoDB, let us learn the standard syntax to write this Unique method.

db.collection_name.createIndex( {field_name : 1} , {unqiue : true} )

How UNIQUE Constraint works in MongoDB?

The Unique Index allows the insertion and storing of the values in a document into a collection IF there is no other document in the same collection with the same index key and value. The unique constraint can be implemented on compound indexes. This helps MongoDB to implement uniqueness when combining the index key values.  Unique Constraint over separate multiple documents is possible in MongoDB, and it is an essential function in avoiding storing of same values for the indexed key in a different document.

Unique Constraint in MongoDB will allow only a single document with the same value for the indexed key. If we attempt to insert the same value for a single indexed key, it will result in an error.

Query #1

db.code.find()

This returns every document in the collection.

Query #2

db.code.insert( { name:”kumar”, city:“Pune”, code:19 } )

This is an attempt to insert a record with the same code.

Code:

db.code.find()

Output:

Explanation: Here, we have implemented the unique index for “code” key, and so when we try to store a document with existing code, it results in “duplicate key error”.

Unique Constraint for Null Value

When we store any document, we store values for the respective keys, and it is stored as per indexing. But in case, if we attempt to store a document that has no specific value or data for a key, for any uncertain key, the document will be stored, and the empty value will be stored as a null value in that document.  In MongoDB, only on the document is allowed to be stored with a single index field missing.

Examples to Implement UNIQUE Constraint in MongoDB

Implementing Unique Contraint on separate documents to not store the same value for the indexes key, in two different documents.

Example #1

We will attempt to insert and store documents with duplicate values. We have a collection named educba, which we will check with find method: db.educba.find()

Code:

db.educba.find()

Output:

As you can see in the above image, we have a collection named educba, and the document has one default unique “_id” and two more keys. We will now implement the unique constraint on the “Name”, which will make it unique, duplicate insertion proof.

Code:

db.educba.createIndex( { “Name” : 1 } , { unique : true } )

Output:

Code:

db.educba.insert({ Name : "Sulaksh" ,  City : "Pune" })

Output:

First Query:db.educba.insert({ Name : "Sulaksh" ,  City : "Pune" })

The above query will be successfully inserted.  Then we attempted to insert the same query, i.e. same document with the same values, but it resulted in an error that states, “terms”: “E11000 duplicate key error collection: test.educba index: Name_1 dup key: { : ”Sulaksh” }””. This makes our unique constraint applied over the Name field successfully.

Example #2

Code:

db.educba.createIndex( {email : 1},{unique : true} )

Output:

We will not attempt to insert a document with a different name but an email id that already exists in another document. Expectations are that the insertion operation will not work and through us an error of duplicate value. We have another document with a slightly different name: Sanket1, for the test purpose, and now we will attempt to update the document with an email: [email protected]

Code:

db.educba.update( { “Name” : ”Sanket1” } , { $set : {email : “[email protected]” }})

Above query will aim to search a record with Name: Sanket1 and will update the record with adding an email id to the document, here $set will add a field for the document.

Output:

As you can see in the above screenshot, when we attempted to update a record with the different Name field, the email was the same as one existing document. It threw us a write error, which means an error occurred while writing the document. The error states “duplicate key error collection: test. educba index: email_1 dup key”. The error points to the issue and makes things clear for us to understand.  Like in our case, the email with the value of “[email protected]” is duplicated, already stored, so it will not store again due to unique indexing on the email field. In case you want to know, I’ve used the update with $get to add another field for existing records.

Use Case for this example: Is the New User Registration where we have to ensure that a single mail id is not used to create multiple accounts.

Conclusion

Implementing Unique Constraint will restrict the database from storing duplicate values for the same indexed key to wrap it up. This feature helps in storing documents with uniqueness. We learned and understood the syntax followed by the working of it. Then we implemented the unique constraint with example and understood the same along with screenshots, respectively.

Recommended Articles

This is a guide to MongoDB Unique. Here we discuss an introduction, how does Unique works and examples for better understanding. You can also go through our other related articles to learn more –

You're reading How Does Mongodb Unique Works With Examples

How Php Ucwords() Works With Examples

Introduction to PHP ucwords()

Ucwords() in PHP is a built-in function. It is helpful to convert the first and foremost character of a string into uppercase. The ucwords() only supports PHP 4 & above versions. ucwords() function takes a string as an input value and it outputs the string by changing the first letter/character of the string into uppercase. Other than this every other character remains the same as the previous time. The ucwords() function in PHP returns converted to string by changing the first letter of all words to uppercase.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax Ucwords($string, $separator)

The ucwords() syntax accepts just two parameters.

1. $string( string mandatory ): Between the parenthesis of ucwords() function, string input is required. It is a must and mandatory to this function declaration in order to specify the string which is to be converted.

2. $separator ( Optional Parameter ): Separator is the optional parameter of ucwords() function. It contains words separator characters. The separator used in the input string for the words. The listed characters which are listed below are by default:

t for tab

Space

r for Carriage return

n for newline

v for vertical tab

f for form feed

$Separator parameter added in 5.5.16, 5.4.32 versions of PHP.

How PHP ucwords() works?

PHP ucwords works when the text/words contain mixed types of letters/characters inside words. Only the first character of the word/ first characters of all the words which are in the sentence will be converted to capital letters. It works using a string value that contains word/words and it also uses one separator/delimiter value but it is optional. No issue with the separator variable.

Examples of PHP ucwords()

Given below are the examples

Example #1

How the basic program works by using ucwords() PHP function.

Code:

<?php $input_string = "hey buddy, pavan sake is coming just wait."; echo "Before:". $input_string; $result_string = ucwords($input_string); echo "After: ".$result_string;

Output:

Example #2

Code:

<?php $result_string1 = ucwords($input_string); echo $result_string2;

Output:

Example #3

This example here is to use ucwords() function on arrays which has a list of names/strings by removing delimeters/parameters “–“ and “”.

Code:

<?php function ucname($string1) { $string1 =ucwords(strtolower($string1)); foreach (array('-', ''') as $parameters1) { if (strpos($string1, $parameters1)!==false) { $string1 =implode($parameters1, array_map('ucfirst', explode($parameters1, $string1))); } } return $string1; } <?php $names1 =array( 'SAKE-PAVAN KUMAR', 'ANIL O'KUMAR', 'MARUTHI PRASAD', 'surendra la gandham', 'rAjAsEkHaR KAtUbaDi' ); /* Sake-Pavan Kumar Anil O'Kumar Maruthi Prasad Surendra La Gandham Rajasekhar Kattubadi */

Output:

Example #4

This is one of the sample programs of ucwords function.

This program has features like:

Multibyte/bytes Compatability

It handles delimiters even if there are multiple

Code:

<?php function ucwords_specific1 ($string1, $delimiters1 = '', $encoding1 = NULL) { if ($encoding1 === NULL) { $encoding1 = mb_internal_encoding();} if (is_string($delimiters1)) { $delimiters1 =  str_split( str_replace(' ', '', $delimiters1)); } $delimiters_pattern11 = array(); $delimiters_replace11 = array(); $delimiters_pattern21 = array(); $delimiters_replace21 = array(); foreach ($delimiters1 as $delimiter1) { $uniqid1 = uniqid(); $delimiters_pattern11[]   = '/'. preg_quote($delimiter1) .'/'; $delimiters_replace11[]   = $delimiter1.$uniqid1.' '; $delimiters_pattern21[]   = '/'. preg_quote($delimiter1.$uniqid1.' ') .'/'; $delimiters_replace21[]   = $delimiter1; } $return_string1 = $string1; $return_string1 = preg_replace($delimiters_pattern11, $delimiters_replace11, $return_string1); $words1 = explode(' ', $return_string1); { $words1[$index1] = mb_strtoupper(mb_substr($word1, 0, 1, $encoding1), $encoding1).mb_substr($word1, 1, mb_strlen($word1, $encoding1), $encoding1); } $return_string1 = implode(' ', $words1); $return_string1 = preg_replace($delimiters_pattern21, $delimiters_replace21, $return_string1); return $return_string1; } <?php mb_internal_encoding('UTF-8'); $string1 = "PAVAN KUMAR-SAKE d'alltechscience şŠ-òÀ-éÌ hello - web"; echo ucwords_specific1( mb_strtolower($string1, 'UTF-8'), "-'");

Output:

The main parameters which are involved in the above program are $string1, $delimeter1, $delimiters, encoding. Delimeter/Delimeters are the parameters that are an option but needed In the development. The string is the parameter that is to be converted. The encoding parameter is to know the character encoding. Internal characters encoding value/values will be used if the parameter don’t omits.

Example #5

Code:

<?php $title1 = 'PAVAN "THE KING" SAKE - (I WANT TO BE YOUR) SERVANT'; echo ucwords(strtolower($title1)); <?php function my_ucwords($string1) { $noletters1='"([/'; for($i=0; $i<strlen($noletters1); $i++) $string1 = str_replace($noletters1[$i], $noletters1[$i].' ', $string1); $string1=ucwords($string1); for($i=0; $i<strlen($noletters1); $i++) $string1 = str_replace($noletters1[$i].' ', $noletters1[$i], $string1); return $string1; } $title1 = 'PAVAN "THE KING" SAKE - (I WANT TO BE YOUR) SERVANT'; echo my_ucwords(strtolower($title1));

Output:

Example #6

This is the example of the code below which will convert all your words into small letters except the first letter. They will be a capital letter. Here ucfirst() function is used. It is also a part of ucwords() function.

Code:

<?php $text1 = "What Buddy ? No 'parameters',shit! "happening" chúng tôi solves many problems now???"; for ($i = 0; $i < count($data1[0]); $i++) { $data1[0][$i] = ucfirst($data1[0][$i]); } $text1 = implode("", $data1[0]); print $text1;

Output:

The above program’s output contains the same text which is under $text1 variable but just the first characters of the words which are listed in the variable will be changed to the capital letters remaining ones will remain as small letters.

Recommended Articles

This has been a guide to PHP ucwords(). Here we discuss syntax, parameters, and examples of PHP ucwords(). you may also have a look at the following articles to learn more –

Learn How Untar Works In Ansible With Examples

Introduction to Ansible untar

Ansible untar module also known as unarchive for Unix OS or win_zip for the windows operating system is used to extract or unpack the archive files or folders on the remote destination by copying the archive file first by default on the remote server and also supports many parameters to deal with the unarchive or win_zip functionality like the owner, dest, exclude and more.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

For the non-windows target unarchive or ansible.builtin.unarchive command uses the below syntax. We have shown the basics parameters

Parameters:

copy: No / Yes (Default)

The default Option is Yes and it copies the files from the local controller to the remote host if specified yes or nothing specified. For working with the remote source need to specify the remote_src and this copy parameter is not helpful there.

src (required):

Source path of the file. If remote_src is ‘yes’ then the source path would be on the remote location otherwise the source path is on the local controller node.

dest (required):

Remote server absolute path where the archive is going to extract.

remote_src: no (Default) / yes

If set ‘yes’ specifies that the source archive path is on the remote computer. For the ‘no’ value the path is on the local controller node.

owner:

name of the user that should own the files/directory after unpack and same replicates (added) to the chown.

group:

Name of the group that should own the files/directory and same replicates (added) to the chown.

exclude:

List of files or directories that need to be excluded from the unpacking.

include:

List of files or directories that need to be included in the unpacking process.

keep_newer: no (default) / yes

If set yes, it replaces the existing files that are newer than the files inside the archive.

mode:

Permissions that the files or directories should have after unpacked (like 644, 777, etc).

For the windows target src, dest, creates parameters remain the same as unarchive module and the additional parameters are as below.

Parameters:

delete_archive: no (default) / yes

Removes the zip file after unzipping.

password

If the Zip file is password encrypted then this parameter is useful and it requires the PSCX module to be installed.

recurse: no (default) / yes

recursively expands the zip file within the src directory.

Setting value ‘yes’ requires the PSCX module to be installed.

Please note: the win_unzip module doesn’t use the remote_src parameter.

How untar works in Ansible?

Ansible unarchive module for non-windows target comes with the ansible-base and so it is included in the Ansible installations. For the windows target, we need to use the win_unzip module. If the module is not available then you can download it from the galaxy.

ansible-galaxy collection install community.windows

Below is the simple playbook for windows untar (unzip).

dest: c:temp7zipInstaller

Output:

The above playbook will unzip the file from the source location to the destination remote servers. If the destination path doesn’t exist it creates the destination path.

You must have noticed here, although the source path is remote, we don’t need to use remote_src because the win_unzip module doesn’t support it and when we use the remote source path for the non-target windows server we must specify the remote_src. For example,

remote_src: yes

Examples

Here are the following examples mention below

Example #1 – unarchive module task for UNIX os.

dest: /tmp/phyes

In this playbook, it will retrieve the chúng tôi file to the destination remote host /tmp/phyes. Before running this task unlike the win_unzip module, you need to make sure that the destination path exists otherwise it will throw an error.

Output:

Example #2 – Exclude files from the archive.

To exclude the certain file from the unpacking we can use h

Code:

exclude: ’Test1 document.txt’

If there are multiple files to exclude then you can provide the list as below.

- ’sourcefile.py’

Example #3 – Include files from the archive

Code:

include: ’Test1 document.txt’

The above playbook will include only the test1 text file and to include the multiple documents, use the below command.

- ’sourcefile.py’

Example #4 – using multiple parameters together.

Code:

owner: ansibleadmin

In the above playbook, it will include only 2 files, keep_newer parameter will not replace the existing files that are newer than files from the archive, remote_src indicates the remote source and it will set the owner permission on the files and it will keep the file permission 0644.

Conclusion

Untar or unarchive or unzip modules are very useful when we write the playbook. It makes it easier to extract the files or folders on the destination server without using any third-party software and in addition, it uses various parameters like we don’t need to copy the file before extracting, adding permissions after extract, etc.

Recommended Articles

This is a guide to  Ansible untar. Here we discuss How untar works in Ansible and Examples along with the codes and outputs. You may also look at the following articles to learn more –

How Does Date Function Work In Xml With Examples?

Definition on XML Date

XML Date is defined as a data type to specify the date in the XML Documents. According to W3C XML Schema, a date is a period of one day in its time zone. The date rule could be customized according to the requirements where sometimes it is necessary to do some date operations or parse dates to a specific format provided time zone should be specified if not local time is used. And the date format is defined by date pattern Strings by assigning letters from A to Z.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In this article, we have used a Class XML Gregorian Calendar for the data Utilities.

Syntax

The XML format for Date is given in the following formats

CCYY-MM-DD

Where the data type specifies Year, Month, and Day. It’s a finite-length sequence of characters with yy-mm-dd. The four-digit numeric represents a year, the negative value is restricted, and the year 0000 is neglected. And there is a symbol ‘- ‘separator between this format; finally, two-digit numerals signify month and date.

The element declaration is illustrated as

The current date on Xpath is defined as

xs:date fn:current-date() How does Date function work in XML?

Generally, this Date function includes Data types like

xs:dateTime (CCYY-MM-DDThh:mm:ss)

xs:date (CCYY-MM-DD)

xs:time (hh:mm:ss)

xs:gYearMonth (CCYY-MM)

xs:gYear (CCYY)

xs:gMonthDay (–MM-DD)

xs:gMonth (–MM–)

xs:gDay (—DD)

and XML formatter prefers to use Simple Date Format, and it is not thread-safe. Also, this constructor is not supported in all the local files. The format comes like this:

public SimpleDateFormat(String pattern, DateFormatSymbols formatSymbols)

The Gregorian Calendar is specified as

2011-11-21

2011-11-21 +02:00

2011-11-21 Z

2011-11-21+00:00

2011-11-21

2011-02-03

The value of the datetime given is parsed by the XML parser, which converts the datetime value declared in the input XML to the value of the local time zone format. Thus, even a daylight-saving option could be made.

Using the Current date() function to display the current date of that day. This function is called without passing any parameters. As a result, it returns the date manipulated from the System time, i.e., gives out a constant value. Let’s see a simple working code of the XSD file.

<xsl: stylesheet version=”2.0″ The current date today is:

And in Xpath, we have like

And Few functions on Date are dateTime (), year-from-dateTime (), year-from-date(date), month-from-date(date) , day-from-date(date).

Next, for the sample XML schema, the customization of XML date and time is specified as

public class Client { @XmlElement(name = "dob") @XmlSchemaType(name = "date") protected XMLGregorianCalendar dateOfBirth; public XMLGregorianCalendar getDateOfBirth() {return dateOfBirth;} public void setDateOfBirth(XMLGregorianCalendar value) {this.dateOfBirth = value; } } Examples

Now let’s see how this function works well in XSLT and java.

Example#1 – Simple XML file displays the date

chúng tôi

Output:

Example#2

Educ.java

import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.GregorianCalendar; import javaxxml.datatype.DatatypeConfigurationException; import javaxxml.datatype.DatatypeFactory; import javaxxml.datatype.XMLGregorianCalendar; public class Educ { private final static String TIMESTAMP_PATTERN = "MM/dd/yyyy hh:mm a z"; private final static DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(TIMESTAMP_PATTERN); public static void main(String[] args) throws DatatypeConfigurationException { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); XMLGregorianCalendar xc = DatatypeFactory.newInstance() .newXMLGregorianCalendar(c); ZonedDateTime zon = xc.toGregorianCalendar().toZonedDateTime(); System.out.println( DATE_TIME_FORMATTER.format(zon) ); ZonedDateTime zond = zon.withZoneSameInstant(ZoneId.of("UTC")); System.out.println( DATE_TIME_FORMATTER.format(zond) ); } }

Explanation:

Output:

Example#3 – Showing java code to convert Date Object to String Value Using Gregorian Calendar

Rule.java

import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; import javaxxml.datatype.DatatypeConfigurationException; import javaxxml.datatype.DatatypeFactory; import javaxxml.datatype.XMLGregorianCalendar; public class Rule { public static void main(String[] args) throws DatatypeConfigurationException { GregorianCalendar gca = new GregorianCalendar(); gca.setTime(new Date()); XMLGregorianCalendar xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar(gca); System.out.println(convertXmlGregorianToString(xgc)); } public static String convertXmlGregorianToString(XMLGregorianCalendar xgc) { DateFormat datef = new SimpleDateFormat("MM/dd/yyyy hh:mm a z"); GregorianCalendar gCalendar = xgc.toGregorianCalendar(); Date dd = gCalendar.getTime(); String dStr = datef.format(dd); return dStr; } } 

Explanation:

The above java code converts an XML file document into java code by converting their data objects to display date. It uses simple packages like Date Format and Simple Date Format.

Output:

Example#4 – Using a Style sheet to give out the date.

.xsl

chúng tôi

Explanation:

Here we have used an XML file with various elements, and XSLT is created,

Output:

Example#5 – Xml date using C#

Code:

using System; using System.IO; using System.Xml; public class test { public static void Main() { Int16 cid = 3252; String oID = "3524f5"; DateTime orderDate = new DateTime(); orderDate = DateTime.Now; Double price = 20.95; XmlTextWriter writer = new XmlTextWriter (Console.Out); writer.Formatting = Formatting.Indented; writer.WriteStartElement("order"); writer.WriteAttributeString("date", XmlConvert.ToString(orderDate, "yyyy-MM-dd")); writer.WriteAttributeString("time", XmlConvert.ToString(orderDate, "HH:mm:ss")); writer.WriteElementString("orderID", oID); writer.WriteElementString("custID", XmlConvert.ToString(cid)); writer.WriteElementString("price", XmlConvert.ToString(price)); writer.WriteEndElement(); writer.Close(); } }

Explanation:

The above code automatically generates the current date from the System, which is shown below. The XML is written using the writer methods, where it starts from the root element ‘order.’

Output:

Conclusion

Therefore this article shows how to apply Date Format value types in java and also taught us the customization formats by changing the different settings as explained in the working sections.

Recommended Articles

This is a guide to XML Date. Here we discuss how the XML date function works well in XSLT and java, along with different examples and its code implementation. You may also have a look at the following articles to learn more –

Guide On How Does Ansible Synchronize Works

Introduction to Ansible Synchronize

Web development, programming languages, Software testing & others

Explaining the Ansible Synchronize

Ansible synchronizes work like rsync in many ways. But we must remember the below points while using it in our environments. These will explain this module and show its limitations:

To work with this module, rsync must be installed on both source and target systems.

By default, the source of files is localhost i.e. the controller machine and destination of files is the machine where the connection is made to transfer files. This default feature can be changed by using parameter delegate_to, which allows you to change your source from localhost to some other host. Thus you can copy files from a remote machine to another remote machine.

On synchronize source machine, file’s permissions are of the user who is running the tasks on localhost or remote_user in the case when delegate_to is used.

On synchronize destination machine, the file’s permission will be of remote_user on destination host or of become_user if become=yes is given in parameters, but to elevate the permission, password less sudo should be set up, as rsync itself does not give a way to pass sudo credentials.

Currently, we have only below few connection types to work with Ansible synchronize viz are ssh, paramiko, local, and docker.

Always give the full path of the destination host location, as there may be cases where you used sudo, but files will be copied to remote_user home directory.

Linux rsync limitations related to hard links are also applied here.

Ansible synchronizes module forces -delay-updates to avoid the broken state in case of connection failure.

How does Ansible Synchronize Works?

Ansible synchronize user below parameters and their acceptable values are listed as below. Using the combination of these parameters, we can decide the behavior and output of Ansible synchronize.

archive: The acceptable values are yes and no. The default value is set to yes. This mirrors the rsync flag, enable recursive, links, perm, group, owner, time flag.

hecksum: The acceptable values are yes and no. The default value is set to no. This is used to skip based on checksum.

compress: The acceptable values are yes and no. The default value is set to yes. This is used to compress files during transfer to speed up the transfer.

copy_links: The acceptable values are yes and no. The default value is set to no. This is used to copy the referenced items rather than links.

delete: The acceptable values are yes and no. The default value is set to no. This is used to delete files in dest location, which does not exist on the source somehow when the transfer is completed. This works when recursive=yes is set.

dest: The absolute or relative path on the destination machine. Which will be synced from the source.

src: The absolute or relative path on the source machine. Which will be synced from the destination.

dirs: The acceptable values are yes and no. The default value is set to no. This is used to transfer directories without recursive.

dest_port: Port number of ssh on destination.

link_dest: Default value is null. This is used to add a destination to hard links against during the rsync.

links: This is used to copy syslinks as syslinks, not referenced items.

mode: Acceptable values are push and pull. The default value is push.

owner: The acceptable values are yes and no. This is used to preserve owner.

rsync_path: This is used to specify the rsync command path on remote hosts.

times: To preserve the modification times. The acceptable values are yes and no.

Examples of Ansible Synchronize

Now by using examples, we will try to learn about Ansible synchronize, which you might have to use in day to day operations. We will take some examples, but before going there, we first understand our lab, we used for testing purpose. Here we have an Ansible control server named ansible-controller and few remote hosts named host- remote, host-one, and host-two. We will create playbooks and run Ansible commands on the ansible- controller node and see the results on the remote hosts.

In this example, we will do the synchronization of files from source machine viz. Ansible controller node to the remote host. We have a set of files under /var/tmp/sync_folder on the Ansible controller node which will be transferred to remote host via Ansible synchronize module. For this we have a playbook like below:

src: /var/tmp/sync_folder dest: /var/tmp/

ansible-playbook ansible_synchronize.yaml

ls -l

In this example, we will do the synchronization of files from one remote host to another remote host. For this we have a playbook like below:

src: /var/tmp/sync_folder dest: /var/tmp/ delegate_to: host-two

On the remote machine, we can cross-check to confirm the files have been transferred.

ls -l

Conclusion

As we saw, Ansible synchronize is powerful but easy to use the module, but we must also acknowledge that this is not the replacement of rsync in Linux systems. So keeping in mind, you must also remember all the limitations mentioned above in this article to avoid unexpected outcomes. So learn it first and then use it carefully.

Recommended Articles

This is a guide to Ansible Synchronize. Here we also discuss the Introduction and how does ansible synchronize works along with examples and its code implementation. You may also have a look at the following articles to learn more –

Learn How Does Either Works In Haskell?

Introduction to Haskell either

In Haskell either is used to represent the possibility of two values. Either is used to represent two values that can be correct or error. It has two constructors also which are named Left and Right. These constructors also represent and show some purpose either in Haskell. Here Left constructor will show the error value, while on the other hand Right constructor will show the correct value. In the coming section of the tutorial, we will see how this function works in Haskell in more detail, and also we will see its implementation and usage while doing programming in Haskell.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

In this section we will see the syntax for either in Haskell, which is given by their official documentation, let’s have a closer look at the syntax of it for better understanding see below;

data Either a b

As you can see in the above line of syntax we have its basic definition with us. Here we are using either keyword followed by two values ‘a’ and ‘b’. Let’s have a look at the practice syntax for either, which will be more helpful to get a better idea for either in Haskell for beginners to see below;

Example:

let variable_name = Your_constructor "value if any" :: Either a basic How does either work in Haskell?

As we already know that either is used to represent two values which can be either correct or error. It also contains two constructors which further used to represent these values in Haskell either. So by the use of either, we can represent our value which is either correct or error. In this section we will first see its definition by the Haskell documentation to get a better idea, let’s get started to see below;

Method signature:

As you can see in the above line of definition for either in Haskell, is given by the Haskell official documentation. This is available inside the Data library, so we can use it as Data.eithe in Haskell. Also if we can see this closely we have two values here ‘a’ and ‘b’. These values are represented by the Left and Right constructor which will turn represent the value as correct and error. After the ‘=’ operator in the above definition, we are trying to represent the ‘a’ value by the Left constructor, and ‘b’ values is represented by the Right constructor. Below we will see the detailed description of both these constructors for better understanding see below;

Available Constructor:

1. Left: As per the official documentation of the Haskell, and as per the convention Left constructor in either is used to represent the error value. Below see the syntax to use it for better understanding see below;

Example:

Left a

1. Right: As per the official documentation of Haskell, and as per the convention Right constructor in either is used to represent the correct value. Below see the syntax to use it for better understanding see below;

Example:

Right a

1. isRight: This method is used to check whether we have passed the right value or not. It will return us the Boolean true or false. If the value if Right value then it will return true else it will return false. Below see the definition of the method as per the Haskell documentation for better understanding see below;

Example:

Now we will see one practice syntax how we can use this while programming in Haskell;

Example:

isRight (Right "your value ")

As you can see in the above line of code we are using the isRight method followed by the Right value passed inside the bracket. In this way, you can use it to evaluate the result of the passed value.

2. isLeft: This method is used to check whether we have passed the left value or not. It will return us the Boolean true or false. If the value is Left value then it will return true else it will return false. Below see the definition of the method as per the Haskell documentation for better understanding see below;

Example:

Example:

isLeft (Left "your value ")

As you can see in the above line of code we are using the isLeft method followed by the Left value passed inside the bracket. In this way, you can use it to evaluate the result of the passed value.

Examples

1. In this example we are trying to identify the value as string or int by using the either Left and Right constructor available. Remember if you want to use either while programming does not forget to import this in your program otherwise it will not work.

Example:

import Data.Either main = do print("Demo to show wokring of either in Haskell !!") print("Using either to evaluate the value either instance of string or inte using either in Haskell !!") let val1 = Left "Hello" :: Either String Int let val2 = Right 100 :: Either String Int let val3 = Left "Hellow world" :: Either String Int let val4 = Left "I m string !!" :: Either String Int let val5 = Right 900 :: Either String Int let val6 = Left "I am another string" :: Either String Int let val7 = Right 500 :: Either String Int print("Printing the result after either evalution !!") print("result one is :: ", val1) print("result two is :: ", val2) print("result three is :: ", val3) print("result four is :: ", val4) print("result five is :: ", val5) print("result six is :: ", val6) print("result seven is :: ", val7)

Output:

Conclusion

By the use of either in Haskell we can easily identify the passing value is correct or error. We also have so many methods available which can be used either to get the result fast for passing Right and Left value in Haskell. Mainly it is used to show the possibility between the two values either a or b.

Recommended Articles

We hope that this EDUCBA information on “Haskell either” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

Update the detailed information about How Does Mongodb Unique Works With Examples on the Kientrucdochoi.com website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!