code-rag-bench/online-tutorials huggingface dataset:
How to return a json object from a Python function?

20 Dec, 2021
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json and this module can be used to convert a python dictionary to JSON object. In Python dictionary is used to get its equivalent JSON object.
Import module
Create a Function
Create a Dictionary
Convert Dictionary to JSON Object Using dumps() method
Return JSON Object
Syntax: json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
Implementation using the above approach is given below:
Example 1:
Python3
# Import Moduleimport json # Create geeks function  def geeks():     # Define Variable    language = "Python"    company = "GeeksForGeeks"    Itemid = 1    price = 0.00     # Create Dictionary    value = {        "language": language,        "company": company,        "Itemid": Itemid,        "price": price    }     # Dictionary to JSON Object using dumps() method    # Return JSON Object    return json.dumps(value)  # Call Function and Print it.print(geeks())
Output:
{“language”: “Python”, “company”: “GeeksForGeeks”, “Itemid”: 1, “price”: 0.0}
Example 2: Using the list as Dictionary value.
Python3
# Import Moduleimport json # Create geeks function  def geeks():     # Create Dictionary    value = {        "firstName": "Pawan",        "lastName": "Gupta",        "hobbies": ["playing", "problem solving", "coding"],        "age": 20,        "children": [            {                "firstName": "mohan",                "lastName": "bansal",                "age": 15            },            {                "firstName": "prerna",                "lastName": "Doe",                "age": 18            }        ]    }     # Dictionary to JSON Object using dumps() method    # Return JSON Object    return json.dumps(value)  # Call Function and Print it.print(geeks())
Output:
{“firstName”: “Pawan”, “lastName”: “Gupta”, “hobbies”: [“playing”, “problem solving”, “coding”], “age”: 20, “children”: [{“firstName”: “mohan”, “lastName”: “bansal”, “age”: 15}, {“firstName”: “prerna”, “lastName”: “Doe”, “age”: 18}]}
sweetyty
Picked
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Extract Content from HTML

How to extract content from an HTML document using java.
Following is the program to extract content from an HTML document using java.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.html.HtmlParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;

public class ExtractContentFromHTMLDoc {
   public static void main(String[] args) throws IOException,SAXException, TikaException {

      //detecting the file type
      BodyContentHandler handler = new BodyContentHandler();
      
      Metadata metadata = new Metadata();
      FileInputStream inputstream = new FileInputStream(new File(
         "C:/tika/htmlExample.html"));
      ParseContext pcontext = new ParseContext();

      //Html parser
      HtmlParser htmlparser = new HtmlParser();
      
      htmlparser.parse(inputstream, handler, metadata,pcontext);
      System.out.println("Contents of the document:" + handler.toString());
      System.out.println("Metadata of the document:");
      String[] metadataNames = metadata.names();

      for(String name : metadataNames) {
         System.out.println(name + ":   " + metadata.get(name));
      }
   }
}
Contents of the document:Sheet1 
   ID   NAME     BRANCH     PERCENTAGE       EMAIL 
   1     Ram       IT          85         ram123@gmail.com 
   2    Rahim      EEE         95         rahim123@gmail.com 
   3    Robert     ECE         90         robert123@gmail.com  
   
Metadata of the document: 
Content-Encoding:   windows-1252 Content-Type:   text/html; charset=windows-1252 

 Print
 Add Notes
 Bookmark this page
Python - Pairs with Sum equal to K in tuple list - GeeksforGeeks

06 Mar, 2020
Sometimes, while working with data, we can have a problem in which we need to find the sum of pairs of tuple list. And specifically the sum that is equal to K. This kind of problem can be important in web development and competitive programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis can be solved using loop. This is brute way in which this task is performed. In this, we iterate the list for pair summation and retain whose sum is K.
# Python3 code to demonstrate # Pairs with Sum equal to K in tuple list# using loop  # Initializing listtest_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]  # printing original listprint("The original list is : " + str(test_list))  # Initializing K K = 9  # Pairs with Sum equal to K in tuple list# using loopres = []for ele in test_list:    if ele[0] + ele[1] == K:         res.append(ele)  # printing result print ("List after extracting pairs equal to K : " + str(res))
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]

 
Method #2 : Using list comprehensionThis is yet another way in which this task can be performed. In this, we extract the elements in similar method as above, the difference is that we perform this task as shorthand and in one line.
# Python3 code to demonstrate # Pairs with Sum equal to K in tuple list# using list comprehension  # Initializing listtest_list = [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]  # printing original listprint("The original list is : " + str(test_list))  # Initializing K K = 9  # Pairs with Sum equal to K in tuple list# using list comprehensionres = [(ele[0], ele[1]) for ele in test_list if ele[0] + ele[1] == K]  # printing result print ("List after extracting pairs equal to K : " + str(res))
The original list is : [(4, 5), (6, 7), (3, 6), (1, 2), (1, 8)]
List after extracting pairs equal to K : [(4, 5), (3, 6), (1, 8)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Java Program for Counting Sort

The Counting Sort counts the number of objects having distinct key values. Let us see an example −
Note − The below code can be used with negative numbers as well.
 Live Demo
import java.util.*;
public class Demo{
   static void count_sort(int[] arr){
      int max_val = Arrays.stream(arr).max().getAsInt();
      int min_val = Arrays.stream(arr).min().getAsInt();
      int range = max_val - min_val + 1;
      int count[] = new int[range];
      int result[] = new int[arr.length];
      for (int i = 0; i < arr.length; i++){
         count[arr[i] - min_val]++;
      }
      for (int i = 1; i < count.length; i++){
         count[i] += count[i - 1];
      }
      for (int i = arr.length - 1; i >= 0; i--){
         result[count[arr[i] - min_val] - 1] = arr[i];
         count[arr[i] - min_val]--;
      }
      for (int i = 0; i < arr.length; i++){
         arr[i] = result[i];
      }
   }
   static void printVal(int[] arr){
      for (int i = 0; i < arr.length; i++){
         System.out.print(arr[i] + " ");
      }  
      System.out.println("");
   }
   public static void main(String[] args){
      int[] arr = {-5, 0, -3, 8, 34, 56, 89, -11, -95, -1, 10};
      System.out.println("The array contains");
      for (int i = 0; i < arr.length; i++){
         System.out.print(arr[i] + " ");
      }
      System.out.println();
      System.out.println("Implementing Counting Sort in Java results in : ");
      count_sort(arr);
      printVal(arr);
   }  
}
The array contains
-5 0 -3 8 34 56 89 -11 -95 -1 10
Implementing Counting Sort in Java results in :
-95 -11 -5 -3 -1 0 8 10 34 56 89
A class named Demo contains the ‘count_sort’ function. Here, the array is iterated over and the count value is increment.
Next, this count array is iterated over and previous value is assigned to the next value. The array is iterated over again and the element of the array is assigned to the result array and the count array is decremented. Then, the array is iterated over again and the elements in the result array is assigned to the array. A print function is defined that prints the data on the console. The main function defines the elements of the array and calls the count sort on these elements.
Django - Apache Setup

So far, in our examples, we have used the Django dev web server. But this server is just for testing and is not fit for production environment. Once in production, you need a real server like Apache, Nginx, etc. Let's discuss Apache in this chapter.
Serving Django applications via Apache is done by using mod_wsgi. So the first thing is to make sure you have Apache and mod_wsgi installed. Remember, when we created our project and we looked at the project structure, it looked like −
myproject/
   manage.py
   myproject/
      __init__.py
      settings.py
      urls.py
      wsgi.py

The wsgi.py file is the one taking care of the link between Django and Apache.
Let's say we want to share our project (myproject) with Apache. We just need to set Apache to access our folder. Assume we put our myproject folder in the default "/var/www/html". At this stage, accessing the project will be done via 127.0.0.1/myproject. This will result in Apache just listing the folder as shown in the following snapshot.
As seen, Apache is not handling Django stuff. For this to be taken care of, we need to configure Apache in httpd.conf. So open the httpd.conf and add the following line −
WSGIScriptAlias / /var/www/html/myproject/myproject/wsgi.py
WSGIPythonPath /var/www/html/myproject/

<Directory /var/www/html/myproject/>
   <Files wsgi.py>
      Order deny,allow
      Allow from all
   </Files>
</Directory>
If you can access the login page as 127.0.0.1/myapp/connection, you will get to see the following page −

    39 Lectures 
     3.5 hours 

 John Elder

    36 Lectures 
     2.5 hours 

 John Elder

    28 Lectures 
     2 hours 

 John Elder

    20 Lectures 
     1 hours 

 John Elder

    35 Lectures 
     3 hours 

 John Elder

    79 Lectures 
     10 hours 

 Rathan Kumar
 Print
 Add Notes
 Bookmark this page
Kibana - Management

The Management section in Kibana is used to manage the index patterns. In this chapter, we will discuss the following −
Create Index Pattern without Time filter field
Create Index Pattern with Time filter field
To do this, go to Kibana UI and click Management −
To work with Kibana, we first have to create index which is populated from elasticsearch. You can get all the indices available from Elasticsearch → Index Management as shown −
At present elasticsearch has the above indices. The Docs count tells us the no of records available in each of the index. If there is any index which is updated, the docs count will keep changing. Primary storage tells the size of each index uploaded.
To create New index in Kibana, we need to click on Index Patterns as shown below −
Once you click Index Patterns, we get the following screen −
Note that the Create Index Pattern button is used to create a new index. Recall that we already have countriesdata-28.12.2018 created at the very start of the tutorial.
Click on Create Index Pattern to create a new index.
The indices from elasticsearch are displayed, select one to create a new index.
Now, click Next step.
The next step is to configure the setting, where you need to enter the following −
Time filter field name is used to filter data based on time. The dropdown will display
all time and date related fields from the index.
Time filter field name is used to filter data based on time. The dropdown will display
all time and date related fields from the index.
In the image shown below, we have Visiting_Date as a date field. Select Visiting_Date as the Time Filter field name.
Click Create index pattern button to create the index. Once done it will display all the fields present in your index medicalvisits-26.01.2019 as shown below −
We have following fields in the index medicalvisits-26.01.2019 −
["Visit_Status","Time_Delay","City","City_id","Patient_Age","Zipcode","Latitude 
","Longitude","Pathology","Visiting_Date","Id_type","Id_personal","Number_Home_
Visits","Is_Patient_Minor","Geo_point"].

The index has all the data for home medical visits. There are some additional fields added by elasticsearch when inserted from logstash.
 Print
 Add Notes
 Bookmark this page
Python | Average String length in list - GeeksforGeeks

29 Nov, 2019
Sometimes, while working with data, we can have a problem in which we need to gather information of average length of String data in list. This kind of information might be useful in Data Science domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + sum() + len()The combination of above functions can be used to perform this task. In this we compute lengths of all Strings using list comprehension and then divide the sum by length of list using len() and sum().
# Python3 code to demonstrate working of# Average String lengths in list# using list comprehension + sum() + len()  # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list print("The original list : " + str(test_list))  # Average String lengths in list# using list comprehension + sum() + len()temp = [len(ele) for ele in test_list]res = 0 if len(temp) == 0 else (float(sum(temp)) / len(temp))   # printing resultprint("The Average length of String in list is : " + str(res))
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The Average length of String in list is : 3.4

 
Method #2 : Using map() + sum() + len()The combination of above functions can also be used to perform this task. In this, we compute lengths using map(). Rest all the logic is similar to above method.
# Python3 code to demonstrate working of# Average String lengths in list# using map() + sum() + len()  # initialize list test_list = ['gfg', 'is', 'best', 'for', 'geeks']  # printing original list print("The original list : " + str(test_list))  # Average String lengths in list# using map() + sum() + len()res = sum(map(len, test_list))/float(len(test_list))  # printing resultprint("The Average length of String in list is : " + str(res))
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The Average length of String in list is : 3.4

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Working with Times and Dates in BigQuery | by Christianlauer | Towards Data Science

Who is not familiar with this situation? What was that thing again with the correct timestamp format? Just google it and next time it will end so again. Here are some of the use cases, that I often come in touch with and which I wanted to write down, in the hope not to have to google them again.
Let’s start with a very easy but useful one. Get the current time — you might need it for comparison e.g. within analytics or for technical data transformations:
SELECT CURRENT_DATETIME() as now;
This function supports the optional timezone parameter. See Timezone definitions for instructions on how to set a timezone [1].
Return a value corresponding to the specified part from a provided datetime_expression. For example, here I extracted only the year. I often use this logic for constraints in analyses or for data transformations, where I convert date formats and store them in new tables in a different format.
SELECT EXTRACT(YEAR FROM DATETIME(2021, 07, 02, 15, 45, 00)) as year;
Calculates the difference between two dates. If the first DATETIME is before the second, the output is negative [1].
Select DATETIME_DIFF(DATETIME”2021–03–03", DATETIME”2021–04–04", Day)as difference;
This results in -32.
Format a DATETIME object according to the specified format_string. Similar to the other examples, one likes to use this formatting option in the data transformation process.
SELECT FORMAT_DATETIME(“%c”, DATETIME “2008–12–25 15:30:00”) AS formatted;
Here, for example with %c, the whole date and time representation are output [2].
With PARSE_DATETIME you can do the opposite of the example mentioned above. It converts the string representation of a DATETIME object into a DATETIME object.
SELECT PARSE_DATETIME(‘%Y-%m-%d %H:%M:%S’, ‘2021–03–03 13:55:55’) AS datetime;
Always useful when other sources for example display the date as string and you want to display it in BigQuery as standardized DATETIME.
Returns the last day from a DATETIME expression containing the date. This is often used to return the last day of the month. You have the option to specify the date part for which the last day should be returned.
SELECT LAST_DAY(DATETIME ‘2008–11–25’, MONTH) AS last_day
If this parameter is not used, the default value is MONTH. Especially in the area of evaluations, for example for a financial month statement interesting and often used.
Since I often find myself googling date formats within BigQuery because I forgot what the correct SQL expression was, I have provided you with my cheatsheet on the subject. These are the most common use cases in my opinion — feel free to let me know if I forgot anything.
basename - Unix, Linux Command

basename - Strips directory and suffix from filenames.
basename NAME [SUFFIX]
basename OPTION
basename prints NAME with any leading directory components removed. If Suffix is specified, it will also remove a trailing SUFFIX.
To get the name of the file present in test folder
$ basename test/sample.txt
sample.txt


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to implement Single Responsibility Principle using C#?

A class should have only one reason to change.
Definition − In this context, responsibility is considered to be one reason to change.
This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and if in the future we need to make one change we are going to make it in the class which handles it. When we need to make a change in a class having more responsibilities the change might affect the other functions related to the other responsibility of the class.
Code Before the Single Responsibility Principle
using System;
using System.Net.Mail;
namespace SolidPrinciples.Single.Responsibility.Principle.Before {
   class Program{
      public static void SendInvite(string email,string firstName,string lastname){
         if(String.IsNullOrWhiteSpace(firstName)|| String.IsNullOrWhiteSpace(lastname)){
            throw new Exception("Name is not valid");
         }
         if (!email.Contains("@") || !email.Contains(".")){
            throw new Exception("Email is not Valid!");
         }
         SmtpClient client = new SmtpClient();
         client.Send(new MailMessage("Test@gmail.com", email) { Subject="Please Join the Party!"})
      }
   }
}
Code After Single Responsibility Principle
using System;
using System.Net.Mail;
namespace SolidPrinciples.Single.Responsibility.Principle.After{
   internal class Program{
      public static void SendInvite(string email, string firstName, string lastname){
         UserNameService.Validate(firstName, lastname);
         EmailService.validate(email);
         SmtpClient client = new SmtpClient();
         client.Send(new MailMessage("Test@gmail.com", email) { Subject = "Please Join the Party!" });
      }
   }
   public static class UserNameService{
      public static void Validate(string firstname, string lastName){
         if (string.IsNullOrWhiteSpace(firstname) || string.IsNullOrWhiteSpace(lastName)){
            throw new Exception("Name is not valid");
         }
      }
   }
   public static class EmailService{
      public static void validate(string email){
         if (!email.Contains("@") || !email.Contains(".")){
            throw new Exception("Email is not Valid!");
         }
      }
   }
}
gets() is risky to use! - GeeksforGeeks

05 Nov, 2020
Consider the below program. 
C
void read(){   char str[20];   gets(str);   printf("%s", str);   return;}
The code looks simple, it reads string from standard input and prints the entered string, but it suffers from Buffer Overflow as gets() doesn’t do any array bound testing. gets() keeps on reading until it sees a newline character. To avoid Buffer Overflow, fgets() should be used instead of gets() as fgets() makes sure that not more than MAX_LIMIT characters are read.
C
#define MAX_LIMIT 20void read(){   char str[MAX_LIMIT];   fgets(str, MAX_LIMIT, stdin);   printf("%s", str);    getchar();   return;}
NOTE: fgets() stores the ‘\n’ character if it is read, so removing that has to be done explicitly by the programmer. It is hence, generally advised that your str can store at least (MAX_LIMIT + 1) characters if your intention is to keep the newline character. This is done so there is enough space for the null terminating character ‘\0’ to be added at the end of the string.
If keeping the newline character is not intended, then one can simply do the following-
C
int len = strlen(str); // Remove the '\n' character and replace it with '\0'str[len - 1] = '\0';
Please feel free to read more about gets() and fgets() here.
Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above.
priyanshulgovil
C Array and String
C-programming
gets
secure-coding
Articles
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Mutex vs Semaphore
Understanding "extern" keyword in C
Time Complexity and Space Complexity
SQL | Views
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Arrays in C/C++
Bitwise Operators in C/C++
std::sort() in C++ STL
Multidimensional Arrays in C / C++
Start Coding | Practice | GeeksforGeeks

When learning a new language, we first learn to output some message. Here, we'll start with the famous Hello World message. Now, here you are given a function to complete. Don't worry about the ins and outs of functions, just add the command (cout<<"Hello World") to print Hello World.
Input Format :No input
Output format :Hello World
Your Task:Your task is to complete the function below to print Hello World.
Explanation:Hello World is printed.
Video:
YouTubeGeeksforGeeks502K subscribersC++ Programming Language Tutorial | Writing first C++ program : Hello World example | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.Full screen is unavailable. Learn MoreYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:04•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=37GG-T6B7bc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
0
mathurpriyansh1519 hours ago
void printHello(){
    
    // Your code goes here
    
    cout<<"Hello World";
    
}
0
programmeramit4444 days ago
#include <iostream>using namespace std;
int main() {
cout << “hello world”;
return 0;
}
0
noboy254 weeks ago
#include<iostream>
using namespace std;
int main(){
cout<<"HELLO WORLD";
return 0;
}
0
itsriyakundu4 weeks ago
#include <iostream>
using namespace std; 
int main( )
{
     cout<<"Hello World";
     return 0;
}
0
me12110331 month ago
Error in driver code .NO need to put ; after function printhello().
0
ak21eeb0b062 months ago
#include <iostream>
using namespace std; 
int main( )
{
cout <<"Hello World"
return 0;
}
0
alekhya119129142 months ago
cant able to type code
0
sumitmaurya20152 months ago
#include <iostream>
using namespace std; 
int main( )
{
cout <<"Hello World"
return 0;
}
0
ritikakhatri578
This comment was deleted.
0
rohitkumar012 months ago
void printHello(){      cout<<"Hello World";   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
SaltStack - Installation

Before moving to installation, you need to have the following requirements −
A Linux server (latest Ubuntu server).
A Linux server (latest Ubuntu server).
sudo or root access to this server.
sudo or root access to this server.
Install all the updates using the following command −
sudo apt-get update

Install the SaltMaster from the repository with the following apt-get command.
sudo apt-get install salt-master

Install the Salt minion from the repository with the following apt-get command.
sudo apt-get install salt-minion 

Install the Salt syndic from the repository with the following apt-get command.
sudo apt-get install salt-syndic

Salt configuration is very simple. The default configuration for the master will work for most installations. The configuration files are installed in the ‘/etc/salt’ directory and are named after their respective components, such as − /etc/salt/master and /etc/salt/minion.
#interface: 0.0.0.0
interface: <local ip address>

After updating the configuration file, restart the Salt master using the following command.
sudo service salt-master restart

Configuring a Salt Minion is very simple. By default a Salt Minion will try to connect to the DNS name “salt”; if the Minion is able to resolve that name correctly, no configuration is required. Redefine the “master” directive in the minion configuration file, which is typically /etc/salt/minion, as shown in the code below −
#master: salt
master: <local ip address>

After updating the configuration file, restart the Salt minion using the command below.
sudo service salt-minion restart

Salt uses AES Encryption for all the communication between the Master and the Minion. The communication between Master and Minion is authenticated through trusted, accepted keys.
salt-key -L
It will produce the following output −
Accepted Keys:
Denied Keys:
Unaccepted Keys:
<local system name>
Rejected Keys:

Accept all keys by issuing the command below.
sudo salt-key -A
It will produce the following output −
The following keys are going to be accepted:
Unaccepted Keys:
<local system name>
Proceed? [n/Y] y
Key for minion bala-Inspiron-N4010 accepted.

Now again issue the salt key listing command,
salt-key -L
It will produce the following output −
Accepted Keys:
<local system name>
Denied Keys:
Unaccepted Keys:
Rejected Keys:

The communication between the Master and a Minion must be verified by running the test.ping command.
sudo salt '*' test.ping

It will produce the following output −
<local system name>
   True

Here, ‘*’ refers to all the minions. Since, we only have one minion – test.ping, it executes the ping command and returns whether the ping is successful or not.
 Print
 Add Notes
 Bookmark this page
How to edit values of an object inside an array in a class - JavaScript?

For this, use the “this” keyword.
Following is the code −
class Employee {
    constructor() {
        this.tempObject = [
            {
                firstName: "David",
                setTheAnotherFirstName() {
                    this.firstName = "Carol";
                },
            },
        ];
    }
} 
var empObject = new Employee(); 
empObject.tempObject[0].setTheAnotherFirstName(); 
console.log("The Change First Name is=" + empObject.tempObject[0].firstName);
To run the above program, you need to use the following command −
node fileName.js.

Here, my file name is demo220.js.
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo220.js
The Change First Name is=Carol
How to find the minimum value of an array in JavaScript?

Math.min() function usually takes all the elements in an array and scrutinize each and every value to get the minimum value.It's methodology is discussed in the below example.
 Live Demo
Example
<html>
<body>
<script>
   function minimum(value) {
      if (toString.call(value) !== "[object Array]")
      return false;
      return Math.min.apply(null, value);
   }
   document.write(minimum([6,39,55,1,44]));
</script>
</body>
</html>
1
Using sort() and compare functions we can write the elements in ascending or descending order, later on using length property we can find the minimum in the following way 
 Live Demo
<html>
<body>
<input type ="button" onclick="myFunction()" value = "clickme">
<p id="min"></p>
<script>
   var numbers = [6,39,55,1,44];
   document.getElementById("min").innerHTML = numbers;
   function myFunction() {
      numbers.sort(function(a, b){return b - a});
   document.getElementById("min").innerHTML = numbers;
   document.write(numbers[numbers.length-1]);
}
</script>
</body>
</html>
After running the program the out put will be shown as in  the following image
On clicking the click me button above the output would display as
1
SQLAlchemy Core - Using Aliases

The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name.
In case of a table, this allows the same table to be named in the FROM clause multiple times. It provides a parent name for the columns represented by the statement, allowing them to be referenced relative to this name.
In SQLAlchemy, any Table, select() construct, or other selectable object can be turned into an alias using the From Clause.alias() method, which produces an Alias construct. The alias() function in sqlalchemy.sql module represents an alias, as typically applied to any table or sub-select within a SQL statement using the AS keyword.
from sqlalchemy.sql import alias
st = students.alias("a")
This alias can now be used in select() construct to refer to students table −
s = select([st]).where(st.c.id>2)
This translates to SQL expression as follows −
SELECT a.id, a.name, a.lastname FROM students AS a WHERE a.id > 2
We can now execute this SQL query with the execute() method of connection object. The complete code is as follows −
from sqlalchemy.sql import alias, select
st = students.alias("a")
s = select([st]).where(st.c.id > 2)
conn.execute(s).fetchall()
When above line of code is executed, it generates the following output −
[(3, 'Komal', 'Bhandari'), (4, 'Abdul', 'Sattar'), (5, 'Priya', 'Rajhans')]


    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
Python 3 - List list() Method

The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list.
Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket. This function also converts characters in a string into a list.
Following is the syntax for list() method −
list( seq )

seq − This is a tuple or string to be converted into list.
This method returns the list.
The following example shows the usage of list() method.
#!/usr/bin/python3

aTuple = (123, 'C++', 'Java', 'Python')
list1 = list(aTuple)
print ("List elements : ", list1)

str = "Hello World"

list2 = list(str)
print ("List elements : ", list2)
When we run above program, it produces the following result −
List elements :  [123, 'C++', 'Java', 'Python']
List elements :  ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to setup cookies in  Python CGI Programming?

It is very easy to send cookies to browser. These cookies are sent along with HTTP Header before to Content-type field. Assuming you want to set UserID and Password as cookies. Setting the cookies is done as follows −
#!/usr/bin/python
print "Set-Cookie:UserID = XYZ;\r\n"
print "Set-Cookie:Password = XYZ123;\r\n"
print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT;\r\n"
print "Set-Cookie:Domain = www.tutorialspoint.com;\r\n"
print "Set-Cookie:Path = /perl;\n"
print "Content-type:text/html\r\n\r\n"
...........Rest of the HTML Content....
From this example, you must have understood how to set cookies. We use Set-Cookie HTTP header to set cookies.
It is optional to set cookies attributes like Expires, Domain, and Path. It is notable that cookies are set before sending magic line "Content-type:text/html\r\n\r\n.
Java Examples - Remove an element

How to remove an element of array?
Following example shows how to remove an element from array.
import java.util.ArrayList;

public class Main {
   public static void main(String[] args) {
      ArrayList objArray = new ArrayList();
      objArray.clear();
      objArray.add(0,"0th element");
      objArray.add(1,"1st element");
      objArray.add(2,"2nd element");
      System.out.println("Array before removing an element"+objArray);
      objArray.remove(1);
      objArray.remove("0th element");
      System.out.println("Array after removing an element"+objArray);
   }
}
The above code sample will produce the following result.
Array before removing an  element[0th element, 1st element, 2nd element]
Array after removing an element[2nd element]

Another sample example of Arrays Remove
import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {
      ArrayList<Integer> arr = new ArrayList<Integer>(5);
      arr.add(20);
      arr.add(15);
      arr.add(30);
      arr.add(45);
      
      System.out.println("Size of list: " + arr.size());
      for (Integer number : arr) {
         System.out.println("Number = " + number);
      } 
      arr.remove(2);
      System.out.println("Now, Size of list: " + arr.size());
      
      for (Integer number : arr) {
         System.out.println("Number = " + number);
      } 
   }
}   
The above code sample will produce the following result.
Size of list: 4
Number = 20
Number = 15
Number = 30
Number = 45
Now, Size of list: 3
Number = 20
Number = 15
Number = 45

 Print
 Add Notes
 Bookmark this page
d-*-block class in Bootstrap 4

Use the d-*block class in Bootstrap to create block on a specific screen width.
You can set it for small, medium, large, and extra large screen size −
<span class="d-sm-block bg-primary">
  d-sm-block
</span>
<span class="d-md-block bg-success">
  d-md-block
</span>
<span class="d-lg-block bg-info">
  d-lg-block
</span>
<span class="d-xl-block bg-warning">
  d-xl-block
</span>
You can try to run the following code to implement the d-*-block class −
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>

<div class="container mt-3">
  <h2>Blocks</h2>
  <p>Resize the browser to check the effect</p>
  <span class="d-block bg-info">block</span>
  <span class="d-sm-block bg-primary">Small Screen Size</span>
  <span class="d-md-block bg-success">Medium Screen Size</span>
  <span class="d-lg-block bg-info">Large Screen Size</span>
  <span class="d-xl-block bg-warning">Extra Large Screen Size</span>
</div>

</body>
</html>
Derive the string “abb” for leftmost and rightmost derivation

Let’s consider a grammar to derive “abb” string using LMD and RMD
   S->AB/ ε
   A-> aB
   B-> Sb
We have to use context free grammar.
Derivation is a sequence of production rules, which is used to get input strings.
During parsing, we have to take two decisions, which are as follows −
We have to decide which non-terminal has to be replaced.
We have to decide which non-terminal has to be replaced by using which production rule.
There are two options to decide which non-terminal has to be replaced with production rule −
Leftmost derivation
Rightmost derivation
The input is scanned and replaced with production rules from left to right.
The given production rules are:
   S->AB/ ε
   A-> aB
   B-> Sb
Let’s derive the string “abb” using LMD
   S->AB
   ->aBB {A->aB}
   ->aSbB {B->Sb}
   ->abB {S-> ε}
   ->abSb {B->Sb}
   ->abb {S-> ε}
Which is our final string
The input is scanned and replaced with a production rule from right to left.
The given production rules are:
   S->AB/ ε
   A-> aB
   B-> Sb
Let’s derive the string “abb” using RMD
   S -> AB
   ->ASb {B->Sb}
   ->Ab {S-> ε}
   ->aBb {A->aB}
   ->aSbb {B->Sb}
   ->abb {S-> ε}
Reached our final string
How to get content of entire page using Selenium?

We can get the content of the entire page using Selenium. There are more than one ways of achieving it. To get the text of the visible on the page we can use the method findElement(By.tagname()) method to get hold of . Next can then use the getText() method to extract text from the body tag.
Syntax −
WebElement l=driver.findElement(By.tagName("body"));
String t = l.getText();
The next approach to get the content of the entire page is to use the getPageSource() method.
Syntax −
String l = driver.getPageSource();
Code Implementation with <body> tag.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextContent{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.google.com/";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element and input text inside it
      WebElement l =driver.findElement(By.tagName("body"));
      System.out.println("Text content: "+ l.getText());
      driver.quit();
   }
}
Code Implementation with getPageSource().
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageSrc{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",  "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.google.com/";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // getPageSource() and print
      String l = driver.getPageSource();
      System.out.println("Page source: "+ l);
      driver.quit();
   }
}
C Program to list all files and sub-directories in a directory - GeeksforGeeks

20 May, 2017
#include <stdio.h>#include <dirent.h>  int main(void){    struct dirent *de;  // Pointer for directory entry      // opendir() returns a pointer of DIR type.     DIR *dr = opendir(".");      if (dr == NULL)  // opendir returns NULL if couldn't open directory    {        printf("Could not open current directory" );        return 0;    }      // Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html    // for readdir()    while ((de = readdir(dr)) != NULL)            printf("%s\n", de->d_name);      closedir(dr);        return 0;}
Output:
              All files and subdirectories 
              of current directory  
cpp-file-handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Arrow operator -> in C/C++ with Examples
Storage Classes in C
Ways to copy a vector in C++
Smart Pointers in C++ and How to Use Them
Switch Statement in C/C++
Detecting low contrast images with OpenCV, scikit-image, and Python - GeeksforGeeks

04 Jan, 2022
In this article, we are going to see how to detect low contrast images with OpenCV, scikit-image using Python
A low contrast image has the minimal distinction between light and dark parts, making it difficult to tell where an object’s boundary begins and the scene’s background begins. For example
The left one is low contrast and the right one is a high contrast image. Using low contrast image detection, you can programmatically detect images that are not sufficient for your image processing pipeline.
First Let’s see how we can manually see the contrast of a picture using histograms. The histogram for a high contrast image(Right) spans the entire dynamic range, but the histogram for a low contrast image(Left) just covers a narrow range, as seen below. 
Now let’s do it programmatically using the  is_low_contrast method of scikit-image library.
Import all the libraries needed.
Read the image in grayscale mode.
Check if image is low contrast image or high contrast image using some threshold value provided.
Syntax: is_low_contrast(img,”threshold value”)
Input Image: 
Code:
Python3
import cv2from skimage.exposure import is_low_contrast  img = cv2.imread("low_contrast_img(1).jpg")gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  if(is_low_contrast(gray,0.35)):    cv2.putText(img, "low contrast image", (5, 25),                cv2.FONT_HERSHEY_SIMPLEX, 0.8,    (0,0,0), 2)else:    cv2.putText(img, "high contrast image", (5, 25),                cv2.FONT_HERSHEY_SIMPLEX, 0.8,    (0,0,0), 2)      cv2.imshow("output",img)cv2.imwrite("output.jpg",img)cv2.waitKey(0)     # closing all open windows cv2.destroyAllWindows() 
Output:
Input:
Code:
Python3
import cv2from skimage.exposure import is_low_contrast  img = cv2.imread("high contrast image(2).jpg")gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)if(is_low_contrast(gray,0.35)):    cv2.putText(img, "low contrast image", (5, 25),                 cv2.FONT_HERSHEY_SIMPLEX, 0.8,    (0,0,0), 2)else:    cv2.putText(img, "high contrast image", (5, 25),                 cv2.FONT_HERSHEY_SIMPLEX, 0.8,    (0,0,0), 2)      cv2.imshow("output",img)cv2.imwrite("output.jpg",img)cv2.waitKey(0)     # closing all open windows cv2.destroyAllWindows() 
Output:
You can further find the contours on high contrast images for image preprocessing and extract the object from the image.
Image-Processing
Picked
Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
How to display most frequent value in a Pandas series? - GeeksforGeeks

18 Aug, 2020
In this article, our basic task is to print the most frequent value in a series. We can find the number of occurrences of elements using the value_counts() method. From that the most frequent element can be accessed by using the mode() method.
Example 1 :
# importing the moduleimport pandas as pd   # creating the seriesseries = pd.Series(['g', 'e', 'e', 'k', 's',                     'f', 'o', 'r',                     'g', 'e', 'e', 'k', 's'])print("Printing the Original Series:")display(series)  # counting the frequency of each elementfreq = series.value_counts()print("Printing the frequency")display(freq)  # printing the most frequent elementprint("Printing the most frequent element of series")display(series.mode());
Output :
Example 2 : Replacing the every element except the most frequent element with None.
# importing the moduleimport pandas as pd   # creating the seriesseries = pd.Series(['g', 'e', 'e', 'k', 's',                     'f', 'o', 'r',                     'g', 'e', 'e', 'k', 's'])  # counting the frequency of each elementfreq = series.value_counts()  # replacing everything else as Otherseries[~series.isin(freq .index[:1])] = Noneprint(series)
Output :
Python Pandas-exercise
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list