code-rag-bench/online-tutorials huggingface dataset:
How to form a composite key to be unique in MySQL?

To form a composite key to be unique, you need to use ADD UNIQUE command. Following is the syntax −
alter table yourTableName add unique
yourUniqueName( yourColumnName1,yourColumnName2,.......N);
Let us first create a table. Following is the query −
mysql> create table makeCompositeKeyDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(40),
   -> StudentAge int,
   -> StudentGrade char(1)
   -> );
Query OK, 0 rows affected (2.34 sec)
Now check the description of the table using DESC command. Following is the query −
mysql> desc makeCompositeKeyDemo;
This will produce the following output −
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| Id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| StudentName  | varchar(40) | YES  |     | NULL    |                |
| StudentAge   | int(11)     | YES  |     | NULL    |                |
| StudentGrade | char(1)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (1.65 sec)
Following is the query to form a composite key to be unique −
mysql> alter table makeCompositeKeyDemo add unique
Name_Age_Grade( StudentName,StudentAge,StudentGrade);
Query OK, 0 rows affected (0.69 sec)
Records: 0 Duplicates: 0 Warnings: 0
Now check the table description once again. Following is the query −
mysql> desc makeCompositeKeyDemo;
This will produce the following output −
+--------------+-------------+------+-----+---------+----------------+
| Field        | Type        | Null | Key | Default | Extra          |
+--------------+-------------+------+-----+---------+----------------+
| Id           | int(11)     | NO   | PRI | NULL    | auto_increment |
| StudentName  | varchar(40) | YES  | MUL | NULL    |                |
| StudentAge   | int(11)     | YES  |     | NULL    |                |
| StudentGrade | char(1)     | YES  |     | NULL    |                |
+--------------+-------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
Python | Testing Output to stdout

12 Jun, 2019
Testing is a critical part of development as there is no compiler to analyze the code before Python executes it.Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to prove that, given the proper input, the proper output is displayed.
Using the unittest.mock module’s patch() function, it’s pretty simple to mock out sys.stdout for just a single test, and put it back again, without messy temporary variables or leaking mocked-out state between test cases.
def urlprint(protocol, host, domain):    url = '{}://{}.{}'.format(protocol, host, domain)    print(url)
The built-in print function, by default, sends output to sys.stdout. In order to test that output is actually getting there, it is to be mocked out using a stand-in object, and then make assertions about what happened.
Using the unittest.mock module’s patch() method makes it convenient to replace objects only within the context of a running test, returning things to their original state immediately after the test is complete.
 Code #2 : Test code for the above code
from io import StringIOfrom unittest import TestCasefrom unittest.mock import patchimport mymodule  class TestURLPrint(TestCase):          def test_url_gets_to_stdout(self):        protocol = 'http'        host = 'www'        domain = 'example.com'        expected_url = '{}://{}.{}\n'.format(protocol, host, domain)                  with patch('sys.stdout', new = StringIO()) as fake_out:            mymodule.urlprint(protocol, host, domain)            self.assertEqual(fake_out.getvalue(), expected_url)
 
The urlprint() function takes three arguments, and the test starts by setting up dummy arguments for each one. The expected_url variable is set to a string containing the expected output.
To run the test, the unittest.mock.patch() function is used as a context manager to replace the value of sys.stdout with a StringIO object as a substitute.
The fake_out variable is the mock object that’s created in this process. This can be used inside the body of the with statement to perform various checks. When the with statement completes, patch conveniently puts everything back the way it was before the test ever ran.
It’s worth noting that certain C extensions to Python may write directly to standard output, bypassing the setting of sys.stdout.
Python-ctype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create Vertical Menu using HTML and CSS ?

16 Nov, 2021
Vertical Menu: We can create a vertical menu in form of buttons and a scrollable menu. Vertical Menu is the buttons arranged in the vertical menu bar/navbar.
How to create a vertical menu using buttons: We can create it simply by using HTML and CSS. We will create a simple structure of the web page by using <div>,<li>, and <a> tags.
Syntax:
<div class="vertical-menu">
  <a href="#" class="active">Home</a>
  <a href="#">1</a>
  ...
  <a href="#">n</a>
</div>
Example:
 
HTML
<!DOCTYPE html><html>  <head>    <meta name="viewport" content=        "width=device-width,initial-scale=1">      <style>        .vertical-menu {            width: 200px;        }          .vertical-menu a {            background-color: #eee;            color: black;            display: block;            padding: 12px;            text-decoration: none;        }          .vertical-menu a:hover {            background-color: #ccc;        }          .vertical-menu a.active {            background-color: #04AA6D;            color: white;        }    </style></head>  <body>    <h1 style="color:green;">        GeeksforGeeks    </h1>          <h3>Vertical Menu</h3>      <div class="vertical-menu">        <a href="#" class="active">Home</a>        <a href="#">About Us </a>        <a href="#">Contact Us</a>        <a href="#">Login </a>        <a href="#">Sign Up</a>    </div></body>  </html>
Output:
How to create a vertical menu using scrollable: Here, we will see how to create a vertical menu using scrollable. To make this, we will use simple HTML and CSS.
Syntax:
<div class="vertical-menu">
    <a href="#" class="active">Home</a>
    <a href="#">1</a>
    ...
    <a href="#">n</a>
</div>
Example:
HTML
<!DOCTYPE html><html>  <head>    <meta name="viewport" content=        "width=device-width,initial-scale=1">      <style>        .vertical-menu {            width: 200px;            height: 150px;            overflow-y: auto;        }          .vertical-menu a {            background-color: #eee;            color: black;            display: block;            padding: 12px;            text-decoration: none;        }          .vertical-menu a:hover {            background-color: #ccc;        }          .vertical-menu a.active {            background-color: #04AA6D;            color: white;        }    </style></head>  <body>    <h1 style="color:green; text-align: center;">        GeeksforGeeks    </h1>      <h3>Vertical Menu</h3>      <div class="vertical-menu">        <a href="#" class="active">Home</a>        <a href="#">About Us </a>        <a href="#">Contact Us</a>        <a href="#">Login </a>        <a href="#">Sign Up</a>    </div></body>  </html>
Output:
CSS-Properties
CSS-Questions
HTML-Questions
HTML-Tags
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – QDateTimeEdit

10 Jul, 2020
QDateTimeEdit allows the user to edit dates by using the keyboard or the arrow keys to increase and decrease date and time values. The arrow keys can be used to move from section to section within the QDateTimeEdit box. Dates and times appear in accordance with the format set. Below is how the QDateTimeEdit looks like
Example :A window having a QDateTimeEdit widget and the label and every time the value in date-time widget changes labels will show the current date-time.
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for components    def UiComponents(self):          # creating a QDateTimeEdit widget        datetime = QDateTimeEdit(self)          # setting geometry        datetime.setGeometry(100, 100, 150, 35)          # creating a label        label = QLabel("GeeksforGeeks", self)          # setting geometry to the label        label.setGeometry(100, 160, 200, 60)          # making label multi line        label.setWordWrap(True)          # adding action to the datetime        datetime.dateTimeChanged.connect(lambda: dt_method())          # method called by the datetime        def dt_method():              # getting current datetime            value = datetime.dateTime()              # setting text to the label            label.setText("Current date time : " + str(value))        # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Media error: Format(s) not supported or source(s) not found
Python PyQt-QDateTimeEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON
Node.js Readable Stream data Event

12 Oct, 2021
The ‘data’ Event in a Readable Stream is emitted when readable.pipe() and readable.resume() method is called for switching the stream into the flowing mode or by adding a listener callback to the data event. This event can also be emitted by calling readable.read() method and returning the chunk of data available.
Syntax:
Event: 'data'
Below examples illustrate the use of data event in Node.js:
Example 1:
// Node.js program to demonstrate the     // readable data event  // Including fs moduleconst fs = require('fs');  // Constructing readable streamconst readable = fs.createReadStream("input.txt");  // Instructions to read datareadable.on('readable', () => {  let chunk;    // Using while loop and calling  // read method  while (null !== (chunk = readable.read())) {      // Displaying the chunk    console.log(`read: ${chunk}`);  }});  // Handling the data eventreadable.on('data', (chunk) => {  console.log(`chunk length is: ${chunk.length}`);});  console.log("Done...");
Output:
Done...
chunk length is: 13
read: GeeksforGeeks

Example 2:
// Node.js program to demonstrate the     // readable data event  // Including fs moduleconst fs = require('fs');  // Constructing readable streamconst readable = fs.createReadStream("input.txt");   // Calling pause methodreadable.pause();  // Handling the data eventreadable.on('data', (chunk) => {  console.log(`chunk length is: ${chunk.length}`);});  console.log("Done...");
Output:
Done...

Reference: https://nodejs.org/api/stream.html#stream_event_data.
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.groupBy() Method

02 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.groupBy() method creates an object composed of keys generated from the results of running each element of collection through the iteratee function. The order of the grouped values is determined by the order they occur in the collection. Also the corresponding value of each key is an array of elements responsible for generating the key.
Syntax:
_.groupBy( collection, iteratee )
Parameters: This method accepts two parameters as mentioned above and described below:
collection: It is the collection that the method iterates over.
iteratee: It is the function that is invoked for every element in the array.
Return Value: This method returns the composed aggregate object.
Example 1:
// Requiring the lodash library const _ = require("lodash");        // Original array var users = ([6.5, 4.12, 6.8, 5.4]);  // Using the _.groupBy() methodlet grouped_data = _.groupBy(users, Math.floor )  console.log(grouped_data);
Output:
{ '4': [ 4.12 ], '5': [ 5.4 ], '6':[ 6.5, 6.8 ] }
Example 2:
// Requiring the lodash library const _ = require("lodash");        // Original array var users = (['eight', 'nine', 'four', 'seven']);   // Using of _.groupBy() method// with the `_.property` iteratee shorthand let grouped_data = _.groupBy(users, 'length')  console.log(grouped_data);
Output:
{ '4': [ 'nine', 'four' ], '5': [ 'eight', 'seven' ]}
Example 3:
// Requiring the lodash library const _ = require("lodash");        // Original array var users = (['one', 'two', 'three', 'four']);var obj = ([ 3.1, 1.2, 3.3 ]);   // Using the _.groupBy() method// with the `_.property` iteratee shorthand let grouped_data = _.groupBy(users, 'length')let grouped_data2 = _.groupBy(obj, Math.floor)  // Printing the output console.log(grouped_data, grouped_data2);
Output:
{ '3': [ 'one', 'two' ], '4': [ 'four' ], '5': [ 'three' ] } 
{ '1': [ 1.2 ], '3': [ 3.1, 3.3 ] }
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Check if the elements of a Vector are Finite, Infinite or NaN values in R Programming – is.finite(), is.infinite() and is.nan() Function

04 Jun, 2020
is.finite() function in R Language is used to check if the elements of a vector are Finite values or not. It returns a boolean value for all the elements of the vector.
Syntax: is.finite(x)
Parameters:x: Vector to be checked
Example:
# R program to illustrate# the use of is.finite() function  # Creating a vectorx <- c(1, 2, 3, 4, 5, NA, 6, 7)  # Calling is.finite() functionis.finite(x)
Output:
[1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE

is.infinite() Function in R Language is used to check if the vector contains infinite values as elements. It returns a boolean value for all the elements of the vector.
Syntax: is.infinite(x)
Parameters:x: Vector to be checked
Example:
# R program to illustrate# the use of is.infinite() function  # Creating a vectorx <- c(1, 2, Inf, 4, -Inf, 6)  # Calling is.infinite() functionis.infinite(x)
Output:
[1] FALSE FALSE  TRUE FALSE  TRUE FALSE

is.nan() Function in R Language is used to check if the vector contains any NaN(Not a Number) value as element. It returns a boolean value for all the elements of the vector.
Syntax: is.nan(x)
Parameters:x: Vector to be checked
Example:
# R program to illustrate# the use of is.nan() function  # Creating a vectorx <- c(1, 2, -Inf, NaN, NaN, NaN)  # Calling is.nan() functionis.nan(x)
Output:
[1] FALSE FALSE FALSE  TRUE  TRUE  TRUE

R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between join and merge in Pandas?

28 Mar, 2022
Pandas provide various facilities for easily combining Series or DataFrame with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations. 
Both join and merge can be used to combines two dataframes but the join method combines two dataframes on the basis of their indexes whereas the merge method is more versatile and allows us to specify columns beside the index to join on for both dataframes.
Let’s first create two dataframes to show the effect of the two methods.
Python3
import pandas as pd # Creating the two dataframesleft = pd.DataFrame([['a', 1], ['b', 2]], list('XY'), list('PQ'))right = pd.DataFrame([['c', 3], ['d', 4]], list('XY'), list('PR'))
Output:
Now let’s see the effect of the two methods on the dataframes one by one.
The join method takes two dataframes and joins them on their indexes (technically, you can pick the column to join on for the left dataframe). If there are overlapping columns, the join will want you to add a suffix to the overlapping column name from the left dataframe. Our two dataframes do have an overlapping column name P.
Example :
Python3
joined_df = left.join(right, lsuffix='_')print(joined_df)
Output :
Notice the index is preserved and we have four columns.We can also separately specify a specific column of the left dataframe with a parameter on to use as the join key, but it will still use the index from the right.
Example :
Python3
joined_df2 = left.reset_index().join(right, on='index', lsuffix='_')print(joined_df2)
Output :
At a basic level, merge more or less does the same thing as join. Both methods are used to combine two dataframes together, but merge is more versatile, it requires specifying the columns as a merge key. We can specify the overlapping columns with parameter on, or can separately specify it with left_on and right_on parameters.
Example :
Python3
merged_df = left.merge(right, on='P', how='outer')print(merged_df)
Output :
Here, notice that the merge method destroyed the index. 
We can explicitly specify that we are merging on the basis of index with the left_index or right_index parameter.
Example :
Python3
merged_df = left.merge(right, left_index=True,                       right_index=True, suffixes=['_', ''])print(merged_df)
Output :
varshagumber28
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Pivot Table Conditional Formatting in Excel

27 May, 2021
One of the most useful ways to customize the pivot table formatting is using Conditional Formats. Conditional formatting rules can be applied to Pivot tables just like they can be applied to normal data ranges. So by using conditional formatting, we can highlight the cells with a certain color depending on the cell’s value.
HOME -> Conditional formatting
There are many conditional formats that we can use on our data. Some of them are given below: 
1. Text or value-based formats: In this particular formatting, we have two options available.
Firstly, we can highlight the cells that are greater or less than a particular number, or are between a particular range, or are equal to a particular number.
Conditional formatting -> Highlight cell rules
For example, if we take the data on the average temperatures experienced month-wise (in F) and if we want to highlight the cells having temperature greater than 50 F (basically we want to visualize on the months having average temperature greater than 50 F), then we can use conditional formatting.
All the months having temperature > 50 F
Secondly, we can highlight the cells that are the top 10 items or the bottom 10 items or occur in the top 10% or bottom 10% of that particular column.
2. Data bars: It is also a great way to visualize relative values. Given below is the same example of average temperature displayed month-wise having the visualization of data bars. 
We see that August has the maximum average temperature
We can also edit this formatting rule by going to the Manage rules option and then select the option of “Show only data bar” if we want only the data bars to be displayed and not the numbers. 
Here only the data bars are shown and not the numbers. 
3. Color scales: A great way to create some heat maps for our data. So we will take the same example of displaying month-wise average temperatures. In this formatting, we will use a Red – White – Blue color scale in which maximum temperatures will be colored red and minimum will be colored blue. 
So we can see that August was the hottest month and January was the coolest one. 
4. Icon sets: In this type of formatting, we use directional arrows, shapes, and various indicators to visualize our data. 
We use green arrow for values > 67 and red arrow for values < 47.
5. Formula-based rules: We can also create our own rule and apply conditional formatting to them. 
These were basically the 5 types of conditional formats that we can use to visualize our data in a more convenient and simpler way.
If we want to clear any rule or edit any rule, we can simply go to the option of Clear rules and Manage rules respectively. We can clear any rule that we applied or edit it according to our choice.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extract Matplotlib colormap in hex-format

To extract matplotlib colormap in hex-format, we can take the following steps −
Get the rainbow color map.
Get the rainbow color map.
Iterate in the range of rainbow colormap length.
Iterate in the range of rainbow colormap length.
Using rgb2hex method, convert rgba tuple to a hexadecimal representation of a color.
Using rgb2hex method, convert rgba tuple to a hexadecimal representation of a color.
from matplotlib import cm
import matplotlib

cmap = cm.rainbow
for i in range(cmap.N):
   rgba = cmap(i)
   print("Hexadecimal representation of rgba:{} is {}".format(rgba, matplotlib.colors.rgb2hex(rgba)))
...............
........................
....................................
Hexadecimal representation of rgba:(1.0, 0.3954512068705424, 0.2018824091570102,
1.0) is #ff6533
Hexadecimal representation of rgba:(1.0, 0.38410574917192575, 0.1958454670071669,
1.0) is #ff6232
Hexadecimal representation of rgba:(1.0, 0.37270199199091436,
0.18980109344182594, 1.0) is #ff5f30
.........................................................
fread() function in PHP

The fread() function reads from an open file. The fread() function halts at the end of the file or when it reaches the specified length whichever comes first. It returns the read string on success. On failure, it returns FALSE.
fread(file_pointer, length)
file_pointer − A file system pointer resource created using fopen(). Required.
file_pointer − A file system pointer resource created using fopen(). Required.
length − The maximum number of bytes to read. Required.
length − The maximum number of bytes to read. Required.
The fread() function returns the read string on success. On failure, it returns FALSE.
Let’s say we have a file “one.txt” with the following line.
Cricket and Football are popular sports.
The following is an example that reads 7 bytes from a file.
<?php
   $file_pointer = fopen("one.txt", "r");
   // fread() function
   echo fread($file_pointer, "7");
   fclose($file_pointer);
?>
Cricket
Let us see another example that reads all the bytes from the same file “one.txt”.
<?php
   $file_pointer = fopen("one.txt", "r");
   // fread() function
   echo fread($file_pointer, filesize("one.txt"));
   fclose($file_pointer);
?>
Cricket and Football are popular sports.
C++ Complex Library - Abs

It is an absolute value of complex and returns the absolute value of the complex number x.
Following is the declaration for std::abs.
x It is a complex value.
It returns the absolute value of the complex number x.
none
In below example for std::abs.
#include <iostream>     
#include <complex>      

int main () {
   std::complex<double> mycomplex (1.0,4.0);

   std::cout << "The absolute value of " << mycomplex << " is " << std::abs(mycomplex) 
      << '\n';
   return 0;
}
The sample output should be like this −
The absolute value of (1,4) is 4.12311

 Print
 Add Notes
 Bookmark this page
How to use XmlSerializer in C#?

Serialization/ De-serialization allow communication with another application by sending and receiving data. With XmlSerializer, you can control how objects are encoded into XML.
To perform XML Serialization, you need the following two classes −
StreamWriter class
XmlSerializer class
Call the Serialize method with the parameters of the StreamWriter and object to serialize.
string myPath = "new.xml";
XmlSerializer s = new XmlSerializer(settings.GetType());
StreamWriter streamWriter = new StreamWriter(myPath);
s.Serialize(streamWriter, settings);    

An XML file is visible with the name “new.xml”.
Now to deserialize.
MySettings mySettings = new MySettings();
string myPath = "new.xml";
XmlSerializer  s = new XmlSerializer(typeof(mySettings));

Use StreamReader class.
StreamReader streamReader = new StreamReader(myPath);
mySettings = (TVSettings)x.Deserialize(streamReader);
MySQL query to search record with apostrophe?

Let us first create a table −
mysql> create table DemoTable
-> (
-> Name varchar(100)
-> );
Query OK, 0 rows affected (2.23 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('Sam\\''s');
Query OK, 1 row affected (0.28 sec)

mysql> insert into DemoTable values('David\\''s');
Query OK, 1 row affected (0.36 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| Name     |
+----------+
| John     |
| Sam\'s   |
| David\'s |
+----------+
3 rows in set (0.00 sec)
Following is the query to search record with apostrophe in MySQL −
mysql> select *from DemoTable WHERE Name = 'Sam\\''s';
This will produce the following output −
+--------+
| Name   |
+--------+
| Sam\'s |
+--------+
1 row in set (0.00 sec)
Python - Columns to Dictionary Conversion in Matrix - GeeksforGeeks

29 Aug, 2020
Given a Matrix, Convert to Dictionary with elements in 1st row being keys, and subsequent rows acting as values list.
Input : test_list = [[4, 5, 7], [10, 8, 4], [19, 4, 6], [9, 3, 6]]Output : {4: [10, 19, 9], 5: [8, 4, 3], 7: [4, 6, 6]}Explanation : All columns mapped with 1st row elements. Eg. 4 -> 10, 19, 9.
Input : test_list = [[4, 5, 7], [10, 8, 4], [19, 4, 6], [9, 3, 7]]Output : {4: [10, 19, 9], 5: [8, 4, 3], 7: [4, 6, 7]}Explanation : All columns mapped with 1st row elements. Eg. 7 -> 4, 6, 7.
Method #1 : Using list comprehension + dictionary comprehension
This is one of the ways in which this task can be performed. In this, list comprehension is responsible for construction of values and mapping and dictionary conversion is done using dictionary comprehension.
Python3
# Python3 code to demonstrate working of # Columns to Dictionary Conversion in Matrix# Using dictionary comprehension + list comprehension  # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]  # printing original listprint("The original list : " + str(test_list))  # dictionary comprehension performing re making of result # dictionaryres = {test_list[0][idx]: [test_list[ele][idx]      for ele in range(1, len(test_list))]      for idx in range(len(test_list[0]))}  # printing result print("Reformed dictionary : " + str(res))
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
Reformed dictionary : {4: [10, 19, 9], 5: [8, 4, 3], 7: [3, 6, 6]}

Method #2 : Using dictionary comprehension + zip()
This is yet another way to solve this problem. In this, we map all column elements with each other using zip() and dictionary comprehension is used to perform remaking of dictionary.
Python3
# Python3 code to demonstrate working of # Columns to Dictionary Conversion in Matrix# Using dictionary comprehension + zip()  # initializing listtest_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]  # printing original listprint("The original list : " + str(test_list))  # appropriate slicing before zip function res = {ele[0]: list(ele[1:]) for ele in zip(*test_list)}  # printing result print("Reformed dictionary : " + str(res))
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
Reformed dictionary : {4: [10, 19, 9], 5: [8, 4, 3], 7: [3, 6, 6]}

Python dictionary-programs
Python
Python Programs
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 ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to draw polylines in OpenCV using Java?

The org.opencv.imgproc package of Java OpenCV library contains a class named Imgproc this class provides various methods to process an input image such as resize(), filter2D, etc.. In addition to these It also provides a set of method to draw geometrical shapes on images.
Among them to draw a polylines you need to invoke the polylines() method of this class. This method accepts the following parameters −
A Mat object representing the image on which the polygon is to be drawn.
A Mat object representing the image on which the polygon is to be drawn.
A-List object holding the objects of the type MatOfPoint.
A-List object holding the objects of the type MatOfPoint.
A parameter of the type boolean specifying whether the poly-lines are
closed.
A parameter of the type boolean specifying whether the poly-lines are
closed.
A Scalar object representing the color of the polygon.
A Scalar object representing the color of the polygon.
An integer representing the thickness of the polygon(default:1).
An integer representing the thickness of the polygon(default:1).
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class DrawingPolyines {
   Mat matrix = null;
   public static void main(String args[]) {
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Loading the OpenCV core library
      System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
      //Reading the source image in to a Mat object
      Mat src = Imgcodecs.imread("D:\\images\\blank.jpg");
      //Drawing an polygon
      List<MatOfPoint> list = new ArrayList<MatOfPoint>();
      list.add( new MatOfPoint (
         new Point(208, 71), new Point(421, 161),
         new Point(226, 232), new Point(332, 52),
         new Point(363, 250)));
      boolean isClosed = true;
      Scalar color = new Scalar(64, 64, 64);
      int thickness = 10;
      Imgproc.polylines (src, list, isClosed, color, thickness);
      //Saving and displaying the image
      Imgcodecs.imwrite("arrowed_line.jpg", src);
      HighGui.imshow("Drawing a polylines", src);
      HighGui.waitKey();
   }
}
On executing, the above program generates the following window −
Ionic - Cordova AdMob

The Cordova AdMob plugin is used for integrating ads natively. We will use the admobpro plugin in this chapter, since the admob is deprecated.
To be able to use ads in your app, you need to sign up to admob and create a banner. When you do this, you will get an Ad Publisher ID. Since these steps are not a part of the Ionic framework, we will not explain it here. You can follow the steps by Google support team here.
You will also need to have android or iOS platform installed, since the cordova plugins work only on native platforms. We have already discussed how to do this in our environment setup chapter.
The AdMob plugin can be installed in the command prompt window.
C:\Users\Username\Desktop\MyApp> cordova plugin add cordova-plugin-admobpro

Now that we have installed the plugin, we need to check if the device is ready before we are able to use it. This is why we need to add the following code in the $ionicPlatform.ready function inside the app.js.
if( ionic.Platform.isAndroid() )  { 
   admobid = { // for Android
      banner: 'ca-app-pub-xxx/xxx' // Change this to your Ad Unit Id for banner...
   };

   if(AdMob) 
      AdMob.createBanner( {
         adId:admobid.banner, 
         position:AdMob.AD_POSITION.BOTTOM_CENTER, 
         autoShow:true
      } );
}
The output will look as shown in the following screenshot.
The same code can be applied for iOS or a Windows Phone. You will only use a different id for these platforms. Instead of a banner, you can use interstitial ads that will cover entire screen.
The following table shows methods that can be used with admob.
The following table shows the events that can be used with admob.
You can handle these events by following the example below.
document.addEventListener('onAdLoaded', function(e){
   // Handle the event...
});

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
numpy.ma.mask_or() function | Python - GeeksforGeeks

22 Apr, 2020
numpy.ma.mask_or() function combine two masks with the logical_or operator. The result may be a view on m1 or m2 if the other is nomask (i.e. False).
Syntax : numpy.ma.mask_or(m1, m2, copy = False, shrink = True)
Parameters :m1, m2 : [ array_like] Input masks.copy : [bool, optional] If copy is False and one of the inputs is nomask, return a view of the other input mask. Defaults to Falseshrink : [bool, optional] Whether to shrink the output to nomask if all its values are False. Defaults to True.
Return : The result masks values that are masked in either m1 or m2.
Code #1 :
# Python program explaining# numpy.ma.mask_or() function  # importing numpy as geek  # and numpy.ma module as ma import numpy as geek import numpy.ma as ma   m1 = geek.ma.make_mask([1, 1, 0, 1])m2 = geek.ma.make_mask([1, 0, 0, 0])  gfg = geek.ma.mask_or(m1, m2)  print (gfg)
Output :
[ True  True False  True]

 Code #2 :
# Python program explaining# numpy.ma.mask_or() function  # importing numpy as geek  # and numpy.ma module as ma import numpy as geek import numpy.ma as ma   m1 = geek.ma.make_mask([1, 0, 0, 0])m2 = geek.ma.make_mask([1, 1, 0, 1])  gfg = geek.ma.mask_or(m1, m2)  print (gfg)
Output :
[ True  True False  True]

Python Numpy-Masked Array
Python-numpy
Python
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
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to disable checkbutton Tkinter (grey out)?

The state property in Tkinter is used to change the state of any specific widget. We can make a widget either active or disabled whenever required. To disable the Checkbuttons widget, we have to set the state property as readonly or disabled. Changing the state will make all the checkbuttons inactive during the execution of the program.
#Import the required Libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of Tkinter Frame
win.geometry("750x250")

#Add a Top widget
Label(win,text= "Select an Option from the Menu", font=('Aerial', 15, 'bold')).pack(pady=15)

#Define CheckButtons
option_dict={}
values=["C++", "Python", "JavaScript", "Ruby","GoLang"]
for i in values:
   cb= ttk.Checkbutton(win, text=i,state= "disabled")
   cb.pack()
#Create a Button widget
win.mainloop()
In the above code snippet, we have disabled all the Checkbuttons Options by disabling its state. To make the Checkbuttons fully functional, we can change the state to state=‘normal’.
Python | Pandas PeriodIndex.week - GeeksforGeeks

06 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas PeriodIndex.week attribute return an Index object containing the ordinal value of week of each period element for the given PeriodIndex object.
Syntax : PeriodIndex.week
Parameters : None
Return : Index object
Example #1: Use PeriodIndex.week attribute to find out the ordinal value of week of each period element contained in the given PeriodIndex object.
# importing pandas as pdimport pandas as pd  # Create the PeriodIndex objectpidx = pd.PeriodIndex(start ='2004-11-11 02:45:21 ',                end ='2004-11-21 8:45:29', freq ='D')  # Print the PeriodIndex objectprint(pidx)
Output :
Now we will use the PeriodIndex.week attribute to find out the week’s ordinal value in the year for the given PeriodIndex object.
# return the week's ordinal valuepidx.week
Output :
As we can see in the output, the PeriodIndex.week attribute has returned an Index object containing the ordinal value of the week for each period element contained in the given PeriodIndex object. Example #2: Use PeriodIndex.week attribute to find out the ordinal value of week of each period element contained in the given PeriodIndex object.
# importing pandas as pdimport pandas as pd  # Create the PeriodIndex objectpidx = pd.PeriodIndex(start ='2016-2-12 11:12:02',            end ='2016-09-12 11:32:12', freq ='M')  # Print the PeriodIndex objectprint(pidx)
Output :
Now we will use the PeriodIndex.week attribute to find out the week’s ordinal value in the year for the given PeriodIndex object.
# return the week's ordinal valuepidx.week
Output :
As we can see in the output, the PeriodIndex.week attribute has returned an Index object containing the ordinal value of the week for each period element contained in the given PeriodIndex object.
Pandas periodIndex
Python-pandas
Python
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Loop through ArrayList in Java

The elements of the ArrayList can be accessed one by one by using a for loop. A program that demonstrates this is given as follows
 Live Demo
import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String> aList = new ArrayList<String>();
      aList.add("Sun");
      aList.add("Moon");
      aList.add("Star");
      aList.add("Planet");
      aList.add("Comet");
      System.out.println("The ArrayList elements are:");
      for (String s : aList) {
         System.out.println(s);
      }
   }
}
The output of the above program is as follows
The ArrayList elements are:
Sun
Moon
Star
Planet
Comet
Now let us understand the above program.
The ArrayList aList is created. Then ArrayList.add() is used to add the elements to this ArrayList. Then the ArrayList elements are displayed using a for loop. A code snippet which demonstrates this is as follows
ArrayList<String> aList = new ArrayList<String>();
aList.add("Sun");
aList.add("Moon");
aList.add("Star");
aList.add("Planet");
aList.add("Comet");
System.out.println("The ArrayList elements are:");
for (String s : aList) {
   System.out.println(s);
}
How to use use an array of pointers (Jagged) in C/C++?

Let us consider the following example, which uses an array of 3 integers −
 Live Demo
#include <stdio.h>
const int MAX = 3;
int main () {
   int var[] = {10, 100, 200};
   int i;
   for (i = 0; i < MAX; i++) {
      printf("Value of var[%d] = %d\n", i, var[i] );
   }
   return 0;
}
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
 Live Demo
#include <iostream>
using namespace std;
const int MAX = 3;
int main () {
   int var[] = {10, 100, 200};
   int i;
   for (i = 0; i < MAX; i++) {
      cout<<"Value of var"<<i<<"="<<var[i]<<"\n";
   }
   return 0;
}
Value of var0=10
Value of var1=100
Value of var2=200
There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer −
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int value. The following example uses three integers, which are stored in an array of pointers, as follows −
 Live Demo
#include <stdio.h>
const int MAX = 3;
int main () {
   int var[] = {10, 100, 200};
   int i, *ptr[MAX];
   for ( i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; /* assign the address of integer. */
   }
   for ( i = 0; i < MAX; i++) {
      printf("Value of var[%d] = %d\n", i, *ptr[i] );
   }
   return 0;
}
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
 Live Demo
#include <iostream>
using namespace std;
const int MAX=3;
int main () {
   int var[] = {10, 100, 200};
   int i, *ptr[MAX];
   for ( i = 0; i < MAX; i++) {
      ptr[i] = &var[i]; /* assign the address of integer. */
   }
   for ( i = 0; i < MAX; i++) {
      cout<<"Value of var" << i<<"="<<*ptr[i] <<"\n";
   }
}
Value of var0=10
Value of var1=100
Value of var2=200
You can also use an array of pointers to character to store a list of strings as follows −
 Live Demo
#include <stdio.h>
const int MAX = 4;
int main () {
   char *names[] = {
      "Zara Ali",
      "Hina Ali",
      "Nuha Ali",
      "Sara Ali"
   };
   int i = 0;
   for ( i = 0; i < MAX; i++) {
      printf("Value of names[%d] = %s\n", i, names[i] );
   }
   return 0;
}
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
 Live Demo
#include <iostream>
using namespace std;
const int MAX=4;
int main () {
   char *names[] = {
      "Zara Ali",
      "Hina Ali",
      "Nuha Ali",
      "Sara Ali"
   };
   int i = 0;
   for ( i = 0; i < MAX; i++) {
      cout<<"Value of names"<< i<<"="<< names[i]<<"\n";
   }
   return 0;
}
Value of names0=Zara Ali
Value of names1=Hina Ali
Value of names2=Nuha Ali
Value of names3=Sara Ali
p5.js | size() Function - GeeksforGeeks

20 Aug, 2019
The size() function is an inbuilt function which is used to set the width and height of the element. The AUTO is used to set one dimension at a time. If the arguments of size() function are not given then it returns the width and height of the element in an object.
This function requires p5.dom library. So add the following line in the head section of the index.html file.
<script language="javascript"    type="text/javascript" src="path/to/p5.dom.js"></script>
Syntax:
size()
or
size( w, h )
Parameters: This function accepts two parameters as mentioned above and described below:
w: This parameter holds the width of the element, either AUTO, or a number.
h: This parameter holds the height of the element, either AUTO, or a number.
Return Value: This function returns the width and height of the element in an object.
Below example illustrates the size() function in p5.js:
Example:
function setup() {           // Create Canvas of given size     var cvs = createCanvas(600, 250);}  function draw() {      // Set the background color  background('green');       // Use createDiv() function to  // create a div element  var myDiv = createDiv('Welcome to GeeksforGeeks');      // Set the position of div element  myDiv.position(180, 80);        // Set the div size  myDiv.size(200, 100);      // Set the font-size of text  myDiv.style('font-size', '24px');      // Set the font-size of text  myDiv.style('border', '1px solid black');      // Set the font-size of text  myDiv.style('text-align', 'center');      // Set the font color  myDiv.style('color', 'white');    }
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Find in a dictionary like structure by value with MongoDB?

You can use find() for this. Let us first create a collection with documents −
> db.findInDictionaryDemo.insertOne(
...    {
...       "_id":101,
...       "AllCustomerDetails":
...       {
...          "SomeCustomerDetail1":
...          {
...             "CustomerName1":"John Doe",
...             "CustomerName2":"John Smith"
...          },
...          "SomeCustomerDetail2":
...          {
...             "CustomerName1":"Carol Taylor",
...             "CustomerName2":"David Miller"
...          }
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }

> db.findInDictionaryDemo.insertOne(
...    {
...       "_id":102,
...       "AllCustomerDetails":
...       {
...          "SomeCustomerDetail1":
...          {
...             "CustomerName1":"Sam Wiliams",
...             "CustomerName2":"Bob Johnson"
...          },
...          "SomeCustomerDetail2":
...          {
...             "CustomerName1":"Chris Brown",
...             "CustomerName2":"Mike Wilson"
...          }
...       }
...    }
... );
{ "acknowledged" : true, "insertedId" : 102 }
Following is the query to display all documents from a collection with the help of find() method −
> db.findInDictionaryDemo.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "AllCustomerDetails" : {
      "SomeCustomerDetail1" : {
         "CustomerName1" : "John Doe",
         "CustomerName2" : "John Smith"
      },
      "SomeCustomerDetail2" : {
         "CustomerName1" : "Carol Taylor",
         "CustomerName2" : "David Miller"
      }
   }
}
{
   "_id" : 102,
   "AllCustomerDetails" : {
      "SomeCustomerDetail1" : {
         "CustomerName1" : "Sam Wiliams",
         "CustomerName2" : "Bob Johnson"
      },
      "SomeCustomerDetail2" : {
         "CustomerName1" : "Chris Brown",
         "CustomerName2" : "Mike Wilson"
      }
   }
}
Following is the query to find in dictionary by value in MongoDB −
>db.findInDictionaryDemo.find({"AllCustomerDetails.SomeCustomerDetail2.CustomerName2":"Mike Wilson"}).pretty();
This will produce the following output −
{
   "_id" : 102,
   "AllCustomerDetails" : {
      "SomeCustomerDetail1" : {
         "CustomerName1" : "Sam Wiliams",
         "CustomerName2" : "Bob Johnson"
      },
      "SomeCustomerDetail2" : {
         "CustomerName1" : "Chris Brown",
         "CustomerName2" : "Mike Wilson"
      }
   }
}