code-rag-bench/online-tutorials huggingface dataset:
NPDA for accepting the language L = {am b(2m) | m>=1}

08 Jun, 2022
Prerequisite – Pushdown automata, Pushdown automata acceptance by final state 
Problem – Design a non deterministic PDA for accepting the language L = {[Tex]b^{2m}   [/Tex]: m>=1}, i.e.,
L = {abb, aabbbb, aaabbbbbb, aaaabbbbbbbb, ......} 
In each of the string, the number of a’s are followed by double number of b’s. 
Explanation – Here, we need to maintain the order of a’s and b’s.That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack.Here, the number of b’s are exactly double of the number of a’s. We will take 2 stack alphabets:
 = { a, z } 
Where, = set of all the stack alphabet z = stack start symbol 
Approach used in the construction of PDA – As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack. But we do this popping operation for alternate position of b’s, i.e., for two b’s we pop one ‘a’ and for four b’s we pop two ‘a’. So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA. 
Stack transition functions –
(q0, a, z)  (q0, az)(q0, a, a)  (q0, aa)[ Indicates no operation only state change ](q0, b, a)  (q1, a) [ Indicates pop operation for alternate 'b'] (q1, b, a)  (q2, ) [ Indicates no operation only state change ] (q2, b, a)  (q1, a) [ Indicates pop operation for alternate 'b'] (q1, b, a)  (q2, )  (q2, , z)  (qf, z)             
Where, q0 = Initial state qf = Final state = indicates pop operation  So, this is our required non deterministic PDA for accepting the language L = {[Tex]b^{2m}   [/Tex]: m>=1}.
simmytarika5
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
Difference between DFA and NFA
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Design 101 sequence detector (Mealy machine)
Post Correspondence Problem
Table Partitioning in Cassandra

31 Aug, 2020
In this article, we are going to cover how we can our data access on the basis of partitioning and how we can store our data uniquely in a cluster. Let’s discuss one by one.
Pre-requisite — Data Distribution
Table Partitioning :In table partitioning, data can be distributed on the basis of the partition key. If you did not specify any partitioning key then it might be the chance of losing data. And It will be difficult to access data as per requirement.
Example :Let’s consider if your requirement where you want to query user data by the first name. Now, first, you have to create a table where the role of the partitioning key is very important.
CREATE TABLE User_data_by_first_name
(
Usr_id UUID,
first_name text,
last_name text,
primary key (first_name)
);
Let’s insert some data for the above-created table.
Insert into User_data_by_id(Usr_id, first_name, last_name) 
values(uuid(), 'Ashish', 'A');
Insert into User_data_by_id(Usr_id, first_name, last_name) 
values(uuid(), 'Ashish', 'A');
Insert into User_data_by_id(Usr_id, first_name, last_name) 
values(uuid(), 'Ashish', 'B');
Now, if you want to read data then used the following cqlsh query.
select * from User_data_by_id;
Output :
In the above example, If you have specified it’s partitioning key by the first name then it is not the recommended way to specify the only first name as partitioning key. Otherwise, it might be a chance not uniquely identified your data and your data will be lost if you have multiple entries with same name.
Now, to resolve this issue specify Usr_id and first_name as the partitioning key.
CREATE TABLE User_data_by_first_name_modify
(
Usr_id UUID,
first_name text,
last_name text,
primary key (first_name, Usr_id)
);
Now, Insert the same data as you have to insert for User_data_by_first_name.
Insert into User_data_by_first_name_modify(Usr_id, first_name, last_name) 
values(uuid(), 'Ashish', 'A');
Insert into User_data_by_first_name_modify(Usr_id, first_name, last_name) 
values(uuid(), 'Ashish', 'A');
Insert into User_data_by_first_name_modify(Usr_id, first_name, last_name) 
values(uuid(), 'Ashish', 'B');
Now, If you will read your data then it will uniquely be identified and your data will be not lost.
select * from User_data_by_first_name_modify;
Output :
Apache
NoSQL
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
What is Temporary Table in SQL?
Difference between Where and Having Clause in SQL
SQL | DDL, DML, TCL and DCL
Introduction of Relational Algebra in DBMS
Relational Model in DBMS
Difference between Star Schema and Snowflake Schema
Difference between File System and DBMS
PREVIOUSMONTH function

Returns a table that contains a column of all dates from the previous month, based on the first date in the dates column, in the current context.
PREVIOUSMONTH (<dates>) 

dates
A column that contains dates.
A table containing a single column of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
Previous Month Sales: = CALCULATE ( 
   SUM (Sales[Sales Amount]), PREVIOUSMONTH (Sales[Date])
) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
C++ Map Library - lower_bound() Function

The C++ function std::map::lower_bound() returns an iterator pointing to the first element which is not less than key k.
Following is the declaration for std::map::lower_bound() function form std::map header.
iterator lower_bound (const key_type& k);
const_iterator lower_bound (const key_type& k) const;

k − Key to be searched.
If object is constant qualified then method returns a constant iterator otherwise non-constant iterator.
This member function doesn't throw exception.
Logarithmic i.e. O(log n)
The following example shows the usage of std::map::lower_bound() function.
#include <iostream>
#include <map>

using namespace std;

int main(void) {
   map<char, int> m = {
            {'a', 1},
            {'b', 2},
            {'c', 3},
            {'d', 4},
            {'e', 5},
            };

   auto it = m.lower_bound('b');

   cout << "Lower bound is " << it->first << 
      " = " << it->second << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Lower bound is b = 2

 Print
 Add Notes
 Bookmark this page
How to cover legend in a box using ggplot2 in R?

To cover legend in a box using ggplot2 in R, we can use theme function with
legend.box.background and legend.box.margin argument. The legend.box.background
will have a rectangular element with the help of element_rect and margin values will be
set in legend.box.margin.
Check out the Example given below to understand how it can be done.
Following snippet creates a sample data frame −
Score<-sample(1:100,20)
Rank<-sample(1:10,20,replace=TRUE)
Gender<-sample(c("Male","Female"),20,replace=TRUE)
df<-data.frame(Score,Rank,Gender)
df
The following dataframe is created
 Score Rank Gender
 1 80     9 Male
 2 82     1 Female
 3 13     5 Male
 4 91     1 Female
 5 62     6 Male
 6 52     2 Female
 7 72     7 Male
 8 15     2 Male
 9 44     2 Male 
10 78     5 Male
11 5     10 Male
12 22     1 Female
13 92     8 Female
14 94     2 Male
15 40     3 Male
16 73     8 Female
17 66     6 Male
18 70     6 Male
19 69     6 Male
20 47     7 Male
To load ggplot2 package and create scatterplot between Score and Rank with points
colored by Gender on the above created data frame, add the following code to the above
snippet −
Score<-sample(1:100,20)
Rank<-sample(1:10,20,replace=TRUE)
Gender<-sample(c("Male","Female"),20,replace=TRUE)
df<-data.frame(Score,Rank,Gender)
library(ggplot2)
ggplot(df,aes(Score,Rank))+geom_point(aes(colour=factor(Gender)))
If you execute all the above given snippets as a single program, it generates the following Output −
To create scatterplot between Score and Rank with points colored by Gender having
legend covered in a box on the above created data frame, add the following code to the
above snippet −
Score<-sample(1:100,20)
Rank<-sample(1:10,20,replace=TRUE)
Gender<-sample(c("Male","Female"),20,replace=TRUE)
df<-data.frame(Score,Rank,Gender)
library(ggplot2)
ggplot(df,aes(Score,Rank))+geom_point(aes(colour=factor(Gender)))+theme(legend.
box.background=element_rect(),legend.box.margin=margin(5,5,5,5))
If you execute all the above given snippets as a single program, it generates the following Output −
How can I round down a number in JavaScript?

The Math.floor() method returns the value of a number rounded downwards to the nearest integer.
You can try to run the following code to round down numbers −
Live Demo
<html>
   <head>
      <title>JavaScript Math floor() Method</title>
   </head>
   <body>
      <script>
         var value = Math.floor( 2.7 );
         document.write("First Test Value : " + value );

         var value = Math.floor( 20.9 );
         document.write("<br />Second Test Value : " + value );

         var value = Math.floor( 15.4 );
         document.write("<br />Third Test Value : " + value );
      </script>
   </body>
</html>
First Test Value : 2
Second Test Value : 20
Third Test Value : 15
numpy.isreal() in Python - GeeksforGeeks

28 Mar, 2022
numpy.isreal(array) : Test element-wise whether it is a real number or not(not infinity or not Not a Number) and return the result as a boolean array. Parameters :  
array : [array_like] Input array whose element we want to test
Return :  
boolean array containing the result
Code 1 : 
Python
# Python Program illustrating# numpy.isreal() method  import numpy as geek print("Is Real : ", geek.isreal([1+1j, 0j]), "\n") print("Is Real : ", geek.isreal([1, 0]), "\n")
Output :  
Is Real :  [False  True] 

Is Real :  [ True  True] 
Code 2 :  
Python
# Python Program illustrating# numpy.isreal() method   import numpy as geek  # Returns True/False value for each elementa = geek.arange(20).reshape(5, 4)print("Is Real : \n", geek.isreal(a), "\n")  # Returns True/False value as ans# because we have mentioned dtype in the beginninga = geek.arange(20).reshape(5, 4).dtype = floatprint("\nIs Real : ", geek.isreal(a))
Output :  
Is Real : 
 [[ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]] 


Is Real :  True
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.isreal.html#numpy.isrealNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Akanksha_Rai
surinderdawra388
vinayedula
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
Rename column name in MySQL?

To rename column name in MySQL, you need to use the ALTER and CHANGE commands.
Let us first create a table −
mysql> create table DemoTable796 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(100),
   StudentAge int
);
Query OK, 0 rows affected (0.56 sec)
Let us check the description of table −
mysql> desc DemoTable796;
This will produce the following output -
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| StudentId  | int(11)      | NO   | PRI | NULL    | auto_increment |
| Name       | varchar(100) | YES  |     | NULL    |                |
| StudentAge | int(11)      | YES  |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
Following is the query to rename column name in MySQL −
mysql> alter table DemoTable796 change Name StudentName varchar(100);
Query OK, 0 rows affected (0.29 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us check the description of table once again −
mysql> desc DemoTable796;
This will produce the following output -
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| StudentId   | int(11)      | NO   | PRI | NULL    | auto_increment |
| StudentName | varchar(100) | YES  |     | NULL    |                |
| StudentAge  | int(11)      | YES  |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
How to read data from user using the Console class in Java?

This class is used to write/read data from the console (keyboard/screen) devices. It provides a readLine() method which reads a line from the key-board. You can get an object of the Console class using the console() method.
Note − If you try to execute this program in a non-interactive environment like IDE it doesn’t work.
Following Java program reads data from user using the Console class.
 Live Demo
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
class Student {
   String name;
   int age;
   float percent;
   boolean isLocal;
   char grade;
   Student(String name, int age, float percent, boolean isLocal, char grade) {
      this.name = name;
      this.age = age;
      this.percent = percent;
      this.isLocal = isLocal;
      this.grade = grade;
   }
   public void displayDetails() {
      System.out.println("Details..............");
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Percent: "+this.percent);
      if(this.isLocal) {
         System.out.println("Nationality: Indian");
      } else {
         System.out.println("Nationality: Foreigner");
      }
      System.out.println("Grade: "+this.grade);
   }
}
public class ReadData {
   public static void main(String args[]) throws IOException {
      Console console = System.console();
      if (console == null) {
         System.out.println("Console is not supported");
         System.exit(1);
      }
      System.out.println("Enter your name: ");
      String name = console.readLine();
      System.out.println("Enter your age: ");
      int age = Integer.parseInt(console.readLine());
      System.out.println("Enter your percent: ");
      float percent = Float.parseFloat(console.readLine());
      System.out.println("Are you local (enter true or false): ");
      boolean isLocal = Boolean.parseBoolean(console.readLine());
      System.out.println("Enter your grade(enter A, or, B or, C or, D): ");
      char grade = console.readLine().toCharArray()[0];
      Student std = new Student(name, age, percent, isLocal, grade);
      std.displayDetails();
   }
}
Enter your name:
Krishna
Enter your age:
26
Enter your percent:
86
Are you local (enter true or false):
true
Enter your grade(enter A, or, B or, C or, D):
A
Details..............
Name: Krishna
Age: 26
Percent: 86.0
Nationality: Indian
Grade: A
C Program to Reverse Array of Strings

In this problem, we are given an array of string. Our task is to create a c program to reverse array of strings.
We will reverse the array elements i.e. last element to the first value and so on.
Let’s take an example to understand the problem,
strarr[] = {"learn", "programming", "at", "tutorialspoint"}
strarr[] = {"tutorialspoint", "at", "programming", "learn"}
To solve this problem, we will create an array of pointers and use two pointers from start and end. then move the pointers towards the opposite side, and keep on swapping the pointer values.
//c program to reverse array of strings.
 Live Demo
#include <stdio.h>
#include <string.h>
void ReverseStringArray(char* strarr[], int n) {
   char* temp;
   int end = n - 1;
   for (int start = 0; start < end; start++) {
      temp = strarr[start];
      strarr[start] = strarr[end];
      strarr[end] = temp;
      end--;
   }
}
int main() {
   char* strarr[] = {"learn", "programming", "at", "tutorialspoint"};
   int n = sizeof(strarr) / sizeof(strarr[0]);
   for (int i = 0; i < n; i++)
      printf("%s ", strarr[i]);
   printf("\n");
   ReverseStringArray(strarr, n);
   for (int i = 0; i < n; i++)
      printf("%s ", strarr[i]);
   return 0;
}
learn programming at tutorialspoint
tutorialspoint at programming learn
How to make an existing field Unique in MySQL?

To make an existing field unique in MySQL, we can use the ALTER command and set UNIQUE constraint for the field. Let us see an example. First, we will create a table.
mysql> create table AddingUnique
   -> (
   -> Id int,
   -> name varchar(100)
   -> );
Query OK, 0 rows affected (0.44 sec)
Syntax to add UNIQUE to an existing field.
alter table yourTableName add UNIQUE(yourColumnName);
Applying the above syntax in order to add UNIQUE to column ‘name’.
mysql> alter table AddingUnique add UNIQUE(name);
Query OK, 0 rows affected (0.60 sec)
Records: 0  Duplicates: 0  Warnings: 0
Now we cannot insert duplicate records into the table, since we have set the field to be unique. If we try to add duplicate records then it raises an error.
mysql> alter table AddingUnique add UNIQUE(name);
Query OK, 0 rows affected (0.60 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> insert into AddingUnique values(1,'John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into AddingUnique values(1,'John');
ERROR 1062 (23000): Duplicate entry 'John' for key 'name'

mysql> insert into AddingUnique values(2,'Carol');
Query OK, 1 row affected (0.18 sec)

mysql> insert into AddingUnique values(3,'John');
ERROR 1062 (23000): Duplicate entry 'John' for key 'name'

mysql> insert into AddingUnique values(4,'Smith');
Query OK, 1 row affected (0.18 sec)
To display all records.
mysql> select *from AddingUnique;
The following is the output.
+------+-------+
| Id   | name  |
+------+-------+
|    1 | John  |
|    2 | Carol |
|    4 | Smith |
+------+-------+
3 rows in set (0.00 sec)
What is the correct way to use printf to print a size_t in C/C++?

We should use “%zu” to print the variables of size_t length. We can use “%d” also to print size_t variables, it will not show any error. The correct way to print size_t variables is use of “%zu”.
In “%zu” format, z is a length modifier and u stand for unsigned type.
The following is an example to print size_t variable.
 Live Demo
#include <stdio.h>
int main() {
   size_t a = 20;
   printf("The value of a : %zu", a);
   return 0;
}
The value of a : 20
In the above program, a variable of size_t length is declared and initialized with a value.
size_t a = 20;
The variables of size_t length is printed as follows −
printf("The value of a : %zu", a);
HTML5 MathML framespacing Attribute - GeeksforGeeks

20 Nov, 2020
This attribute defines the space between the table and the frame. This attribute is accepted by <mtable> tag only.
Syntax:
<element framespacing="number">
Attributes Value:
number: This attribute defines the space between  the table and the frame.
Below example illustrate the framespacing attribute in HTML5 MathML:
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML5 MathML framespacing Attribute    </title></head>  <body>    <center>        <h1 style="color:green">            GeeksforGeeks        </h1>          <h3>HTML5 MathML framespacing Attribute</h3>          <math>            <mi>GeeksforGeeks</mi>            <mo>=</mo>            <mtable frame="solid" columnlines="dashed"                framespacing="2" align="axis 1">                                  <mtr mathbackground="green;">                    <mtd>Course</mtd>                    <mtd>Fee</mtd>                </mtr>                <mtr>                    <mtd>                        <mi>C++ STL</mi>                    </mtd>                    <mtd>                        <mi> 1499</mi>                    </mtd>                </mtr>                <mtr>                    <mtd>                        <mi>Placement 100 </mi>                    </mtd>                    <mtd>                        <mi>9999 </mi>                    </mtd>                </mtr>                <mtr>                    <mtd>                        <mi>DSA Foundation </mi>                    </mtd>                    <mtd>                        <mi>7999</mi>                    </mtd>                </mtr>            </mtable>        </math>    </center></body>  </html>
Output:
Supported Browsers: The browsers supported by HTML5 MathML framespacing attribute are listed below:
Firefox
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-MathML
HTML5
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Defining Custom Suffix Rules in Makefile

Make can automatically create a.o file, using cc -c on the corresponding .c file. These rules are built-in the make, and you can take this advantage to shorten your Makefile. If you indicate just the .h files in the dependency line of the Makefile on which the current target is dependent on, make will know that the corresponding .cfile is already required. You do not have to include the command for the compiler.
This reduces the Makefile further, as shown below −
OBJECTS = main.o hello.o factorial.o
hello: $(OBJECTS)
   cc $(OBJECTS) -o hello
hellp.o: functions.h

main.o: functions.h 
factorial.o: functions.h 

Make uses a special target, named .SUFFIXES to allow you to define your own suffixes. For example, refer the dependency line given below −
.SUFFIXES: .foo .bar

It informs make that you will be using these special suffixes to make your own rules.
Similar to how make already knows how to make a .o file from a .c file, you can define rules in the following manner −
.foo.bar:
   tr '[A-Z][a-z]' '[N-Z][A-M][n-z][a-m]' < $< > $@
.c.o:
   $(CC) $(CFLAGS) -c $<

The first rule allows you to create a .bar file from a .foo file. It basically scrambles the file. The second rule is the default rule used by make to create a .o file from a .c file.
 Print
 Add Notes
 Bookmark this page
Defining generic method inside Non-generic class in Java

You can write a single generic method declaration that can be called with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately. Following are the rules to define Generic Methods −
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).
All generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
Each type parameter section contains one or more type parameters separated by commas. A type parameter, also known as a type variable, is an identifier that specifies a generic type name.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).
A generic method's body is declared like that of any other method. Note that type parameters can represent only reference types, not primitive types (like int, double and char).
Yes, you can define a generic method in a non-generic class in Java.
 Live Demo
public class GenericMethod {
   <T>void sampleMethod(T[] array) {
      for(int i=0; i<array.length; i++) {
         System.out.println(array[i]);
      }
   }
   public static void main(String args[]) {
      GenericMethod obj = new GenericMethod();
      Integer intArray[] = {45, 26, 89, 96};
      obj.sampleMethod(intArray);
      String stringArray[] = {"Krishna", "Raju", "Seema", "Geeta"};
      obj.sampleMethod(stringArray);
   }
}
45
26
89
96
Krishna
Raju
Seema
Geeta
Elasticsearch - Rollup Data

A rollup job is a periodic task that summarizes data from indices specified by an index pattern and rolls it into a new index. In the following example, we create an index named sensor with different date time stamps. Then we create a rollup job to rollup the data from these indices periodically using cron job.
PUT /sensor/_doc/1
{
   "timestamp": 1516729294000,
   "temperature": 200,
   "voltage": 5.2,
   "node": "a"
}
On running the above code, we get the following result −
{
   "_index" : "sensor",
   "_type" : "_doc",
   "_id" : "1",
   "_version" : 1,
   "result" : "created",
   "_shards" : {
      "total" : 2,
      "successful" : 1,
      "failed" : 0
   },
   "_seq_no" : 0,
   "_primary_term" : 1
}

Now, add a second document and so on for other documents as well.
PUT /sensor-2018-01-01/_doc/2
{
   "timestamp": 1413729294000,
   "temperature": 201,
   "voltage": 5.9,
   "node": "a"
}
PUT _rollup/job/sensor
{
   "index_pattern": "sensor-*",
   "rollup_index": "sensor_rollup",
   "cron": "*/30 * * * * ?",
   "page_size" :1000,
   "groups" : {
      "date_histogram": {
         "field": "timestamp",
         "interval": "60m"
      },
      "terms": {
         "fields": ["node"]
      }
   },
   "metrics": [
      {
         "field": "temperature",
         "metrics": ["min", "max", "sum"]
      },
      {
         "field": "voltage",
         "metrics": ["avg"]
      }
   ]
}

The cron parameter controls when and how often the job activates. When a rollup job’s cron schedule triggers, it will begin rolling up from where it left off after the last activation
After the job has run and processed some data, we can use the DSL Query to do some searching.
GET /sensor_rollup/_rollup_search
{
   "size": 0,
   "aggregations": {
      "max_temperature": {
         "max": {
            "field": "temperature"
         }
      }
   }
}


    14 Lectures 
     5 hours 

 Manuj Aggarwal

    20 Lectures 
     1 hours 

 Faizan Tayyab
 Print
 Add Notes
 Bookmark this page
Count number of times value appears in particular column in MySQL?

You can use aggregate function count() with group by. The syntax is as follows.
select yourColumnName,count(*) as anyVariableName from yourtableName group by yourColumnName;
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table CountSameValue
-> (
-> Id int,
-> Name varchar(100),
-> Marks int
-> );
Query OK, 0 rows affected (0.70 sec)
Insert records in the table using insert command. The query is as follows.
mysql> insert into CountSameValue values(1,'Sam',67);
Query OK, 1 row affected (0.17 sec)

mysql> insert into CountSameValue values(2,'Mike',87);
Query OK, 1 row affected (0.19 sec)

mysql> insert into CountSameValue values(3,'Carol',67);
Query OK, 1 row affected (0.24 sec)

mysql> insert into CountSameValue values(4,'Bob',87);
Query OK, 1 row affected (0.18 sec)

mysql> insert into CountSameValue values(5,'John',71);
Query OK, 1 row affected (0.17 sec)

mysql> insert into CountSameValue values(6,'Adam',66);
Query OK, 1 row affected (0.18 sec)

mysql> insert into CountSameValue values(7,'David',71);
Query OK, 1 row affected (0.20 sec)

mysql> insert into CountSameValue values(8,'Maria',67);
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from CountSameValue;
The following is the output.
+------+-------+-------+
| Id   | Name  | Marks |
+------+-------+-------+
| 1    | Sam   | 67    |
| 2    | Mike  | 87    |
| 3    | Carol | 67    |
| 4    | Bob   | 87    |
| 5    | John  | 71    |
| 6    | Adam  | 66    |
| 7    | David | 71    |
| 8    | Maria | 67    |
+------+-------+-------+
8 rows in set (0.00 sec)
Here is the query to count the number of times value (marks) appears in a column. The query is as follows.
mysql> select Marks,count(*) as Total from CountSameValue group by Marks;
The following is the output.
+-------+-------+
| Marks | Total |
+-------+-------+
| 67    | 3     |
| 87    | 2     |
| 71    | 2     |
| 66    | 1     |
+-------+-------+
4 rows in set (0.00 sec)
Convert an Object to a String in R Programming - toString() Function - GeeksforGeeks

17 Jun, 2020
toString() function in R Language is used to convert an object into a single character string.
Syntax: toString(x, width)
Parameters:x: Objectwidth: maximum string width
Example 1:
# R program to convert an object to string  # Creating a vectorx <- c("Geeks", "for", "geeks")   # Calling toString() FunctiontoString(x)toString(x, width = 12)
Output:
[1] "Geeks, for, geeks"
[1] "Geeks, f...."

Example 2:
# R program to convert an object to string  # Creating a matrixx <- matrix(c(1:9), 3, 3)  # Calling toString() FunctiontoString(x)
Output:
[1] "1, 2, 3, 4, 5, 6, 7, 8, 9"

R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
K-Means Clustering in R Programming
R Programming Language - Introduction
Remove rows with NA in one column of R DataFrame
Introduction of Stack based CPU Organization - GeeksforGeeks

13 Jan, 2022
The computers which use Stack-based CPU Organization are based on a data structure called a stack. The stack is a list of data words. It uses the Last In First Out (LIFO) access method which is the most popular access method in most of the CPU. A register is used to store the address of the topmost element of the stack which is known as Stack pointer (SP). In this organization, ALU operations are performed on stack data. It means both the operands are always required on the stack. After manipulation, the result is placed in the stack. 
The main two operations that are performed on the operators of the stack are Push and Pop. These two operations are performed from one end only. 
1. Push – This operation results in inserting one operand at the top of the stack and it decreases the stack pointer register. The format of the PUSH instruction is: 
PUSH 
It inserts the data word at a specified address to the top of the stack. It can be implemented as: 
//decrement SP by 1
SP <-- SP - 1 

//store the content of specified memory address 
//into SP; i.e, at top of stack
SP <-- (memory address) 
2. Pop – This operation results in deleting one operand from the top of the stack and increasing the stack pointer register. The format of the POP instruction is: 
POP 
It deletes the data word at the top of the stack to the specified address. It can be implemented as: 
//transfer the content of  SP (i.e, at top most data) 
//into specified memory location                   
(memory address) <-- SP

//increment SP by 1
SP <-- SP + 1 
Operation type instruction does not need the address field in this CPU organization. This is because the operation is performed on the two operands that are on the top of the stack. For example: 
SUB 
This instruction contains the opcode only with no address field. It pops the two top data from the stack, subtracting the data, and pushing the result into the stack at the top. 
PDP-11, Intel’s 8085, and HP 3000 are some examples of stack-organized computers. 
The advantages of Stack-based CPU organization – 
Efficient computation of complex arithmetic expressions. 
Execution of instructions is fast because operand data are stored in consecutive memory locations. 
The length of instruction is short as they do not have an address field. 
The disadvantages of Stack-based CPU organization –
The size of the program increases. 
Note: Stack-based CPU organization uses zero address instruction.
VaibhavRai3
TanyaGautam2
tanwarsinghvaibhav
Computer Organization & Architecture
Stack
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Program for Decimal to Binary Conversion
Flag register of 8086 microprocessor
Direct Access Media (DMA) Controller in Computer Architecture
Interrupts
Stack Data Structure (Introduction and Program)
Stack Class in Java
Stack in Python
Check for Balanced Brackets in an expression (well-formedness) using Stack
Stack | Set 2 (Infix to Postfix)
Python | Geographical plotting using plotly - GeeksforGeeks

26 Jun, 2018
Geographical plotting is used for world map as well as states under a country. Mainly used by data analysts to check the agriculture exports or to visualize such data.
plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
cufflink connects plotly with pandas to create graphs and charts of dataframes directly. choropleth is used to describe geographical plotting of USA. choropleth is used in the plotting of world maps and many more.
Command to install plotly:
pip install plotly 
 
Below is the implementation:
# Python program to plot # geographical data using plotly  # importing all necessary librariesimport plotly.plotly as pyimport plotly.graph_objs as goimport pandas as pd  # some more libraries to plot graphfrom plotly.offline import download_plotlyjs, init_notebook_mode, iplot, plot  # To establish connectioninit_notebook_mode(connected = True)    # type defined is choropleth to# plot geographical plotsdata = dict(type = 'choropleth',              # location: Arizoana, California, Newyork            locations = ['AZ', 'CA', 'NY'],                          # States of USA            locationmode = 'USA-states',                          # colorscale can be added as per requirement            colorscale = 'Portland',                          # text can be given anything you like            text = ['text 1', 'text 2', 'text 3'],            z = [1.0, 2.0, 3.0],            colorbar = {'title': 'Colorbar Title Goes Here'})              layout = dict(geo ={'scope': 'usa'})  # passing data dictionary as a list choromap = go.Figure(data = [data], layout = layout)  # plotting graphiplot(choromap)
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Java program to print all duplicate characters in a string - GeeksforGeeks

13 Jul, 2020
Given a string, the task is to write Java program to print all the duplicate characters with their frequency
Example: 
Input: str = “geeksforgeeks”Output:s : 2e : 4g : 2k : 2
Input: str = “java”Output:a : 2
Approach: The idea is to do hashing using HashMap.
Create a hashMap of type {char, int}.
Traverse the string, check if the hashMap already contains the traversed character or not.
If it is present, then increment the count or else insert the character in the hashmap with frequency = 1.
Now traverse through the hashmap and look for the characters with frequency more than 1. Print these characters with their respective frequencies.
Below is the implementation of the above approach:
Java
// Java program for the above approachimport java.util.*;class GFG {      // Function to print all duplicate    // characters in string using HashMap    public static void    countDuplicateCharacters(String str)    {          // Creating a HashMap containing char        // as a key and occurrences as a value        Map<Character, Integer> map            = new HashMap<Character, Integer>();          // Converting given string into        // a char array        char[] charArray = str.toCharArray();          // Checking each character        // of charArray        for (char c : charArray) {              if (map.containsKey(c)) {                  // If character is present                // in map incrementing it's                // count by 1                map.put(c, map.get(c) + 1);            }            else {                  // If character is not present                // in map putting this                // character into map with                // 1 as it's value.                map.put(c, 1);            }        }          // Traverse the HashMap, check        // if the count of the character        // is greater than 1 then print        // the character and its frequency        for (Map.Entry<Character, Integer> entry :             map.entrySet()) {              if (entry.getValue() > 1) {                System.out.println(entry.getKey()                                   + " : "                                   + entry.getValue());            }        }    }      // Driver Code    public static void    main(String args[])    {        // Given String str        String str = "geeksforgeeks";          // Function Call        countDuplicateCharacters(str);    }}
s : 2
e : 4
g : 2
k : 2

Time Complexity: O(N)Auxiliary Space: O(1)
Hash
Java-HashMap
Hash
Java Programs
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Quadratic Probing in Hashing
Hashing in Java
Rearrange an array such that arr[i] = i
Load Factor and Rehashing
Advantages of BST over Hash Table
Initializing a List in Java
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
Find elements within range in numpy in Python

Sometime while processing data using the numpy library, we may need to filter out certain numbers in a specific range. This can be achieved by using some in-built methods available in numpy.
In this approach we take an numpy array then apply the logical_and function to it. The where clause in numpy is also used to apply the and condition. The result is an array showing the position of the elements satisfying the required range conditions.
import numpy as np

A = np.array([5, 9, 11, 4, 31, 27,8])

# printing initial array
print("Given Array : ", A)

# Range 6 to 15
res = np.where(np.logical_and(A >= 6, A <= 15))

# Result
print("Array with condition : ", res)
Running the above code gives us the following result −
Given Array : [ 5 9 11 4 31 27 8]
Array with condition : (array([1, 2, 6], dtype=int32),)
In this approach we use the * operator. It gives the result as actual values instead of the position of the values in the array.
import numpy as np

A = np.array([5, 9, 11, 4, 31, 27,8])

# printing initial array
print("Given Array : ", A)

# Range 6 to 15
res = A [ (A >=6) * (A <= 15)]

# Result
print("Array with condition : ", res)
Running the above code gives us the following result −
Given Array : [ 5 9 11 4 31 27 8]
Array with condition : [ 9 11 8]
How to make a broken horizontal bar plot in Matplotlib?

We can take the following steps to make a broken bar plot,
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots.
Plot a horizontal sequence of rectangles.
Set x and y axes scale, X-axis label, Y ticks and Y tick labels.
Configure the grid lines.
Use annotate() method to show text that can refer to a specific position.
To display the figure, use show() method.
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()

ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors='tab:blue')
ax.broken_barh([(10, 50), (100, 20), (130, 10)], (20, 9),
               facecolors=('tab:orange', 'tab:green', 'tab:red'))
ax.set_ylim(5, 35)
ax.set_xlim(0, 200)
ax.set_xlabel('seconds since start')
ax.set_yticks([15, 25])
ax.set_yticklabels(['Bill', 'Jim'])
ax.grid(True)

ax.annotate('race interrupted', (61, 25),
            xytext=(0.8, 0.9), textcoords='axes fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),
            fontsize=16,
            horizontalalignment='right', verticalalignment='top')

plt.show()
Tryit Editor v3.7

Tryit: no end tag
How to get MySQL random integer range?

To get the random integer range, use the rand() function. The query to create a table −
mysql> create table RandomIntegerDemo
−> (
   −> Number int
−> );
Query OK, 0 rows affected (0.61 sec)
Inserting records into table. The query is as follows −
mysql> insert into RandomIntegerDemo values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14);
Query OK, 14 rows affected (0.14 sec)
Records: 14 Duplicates: 0 Warnings: 0
Now you can display all records with the help of select statement. The query is as follows −
mysql> select *from RandomIntegerDemo;
The following is the output displaying integers −
+--------+
| Number |
+--------+
| 1      |
| 2      |
| 3      |
| 4      |
| 5      |
| 6      |
| 7      |
| 8      |
| 9      |
| 10     |
| 11     |
| 12     |
| 13     |
| 14     |
+--------+
14 rows in set (0.00 sec)
The query to generate the random integer range is as follows −
mysql> select Number, (FLOOR( 1 + RAND( ) *14 )) AS RandomValue
−> from RandomIntegerDemo
−> limit 0,14;
The output displays random integer range in the same table −
+--------+-------------+
| Number | RandomValue |
+--------+-------------+
|      1 | 9           |
|      2 | 8           |
|      3 | 13          |
|      4 | 13          |
|      5 | 10          |
|      6 | 10          |
|      7 | 7           |
|      8 | 3           |
|      9 | 8           |
|     10 | 2           |
|     11 | 14          |
|     12 | 6           |
|     13 | 3           |
|     14 | 9           |
+--------+-------------+
14 rows in set (0.00 sec)
Wrapper Class in Python - GeeksforGeeks

21 Apr, 2020
Decoration is a way to specify management code for functions and classes. Decorators themselves take the form of callable objects that process other callable objects. A Class Decorator is similar to function decorators, but they are run at the end of a class statement to rebind a class name to a callable (e.g functions). As such, they can be used to either manage classes just after they are created or insert a layer of wrapper logic to manage instances when they are later created. Class decorator can be used to manage class object directly, instead of instance calls – to increase/modify a class with new methods. Class decorators are strongly related to function decorators, in fact, they use nearly the same syntax and very similar coding pattern but somewhere logic differs.
Note: For more information, refer to Decorators in Python
Syntax:Syntactically, class decorators appear just before class statements.
@decorator
class Class_Name:       
      ...

inst = Class_Name(50)

This piece of code is equivalent to

class Class_Name:
      ...

Class_Name = decorator(Class_Name)
inst = Class_Name(50);

Let’s understand the syntax, and how its works with an example:
Example:
# decorator accepts a class as # a parameterdef decorator(cls):          class Wrapper:                  def __init__(self, x):                          self.wrap = cls(x)                      def get_name(self):                          # fetches the name attribute            return self.wrap.name              return Wrapper  @decoratorclass C:    def __init__(self, y):        self.name = y  # its equivalent to saying# C = decorator(C)x = C("Geeks")print(x.get_name())   
OUTPUT:
Geeks

In this example, the decorator rebinds the class C to another class Wrapper, which retains the original class in an enclosing scope and creates and embeds an instance (wrap) of the original class when it’s called. In more easy language, @decorator is equivalent to C = decorator(C) which is executed at the end of the definition of class C. In the decorator body, wrapper class modifies the class C maintaining the originality or without changing C. cls(x) return an object of class C (with its name attribute initialized with the value of x). The method get_name return the name attribute for the wrap object. And finally in the output “Geeks” gets printed.
So, this was an overview of the decorator or wrapper for the class. The class decorators are used to add additional functionality to the class without changing the original class to use as required in any situation.
Python Decorators
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions