code-rag-bench/online-tutorials huggingface dataset:
8086 program to convert 8 bit ASCII to BCD number - GeeksforGeeks

10 Sep, 2018
Problem – Write a program to convert ASCII to BCD 8-bit number where starting address is 2000 and the number is stored at 2050 memory address and store result into 3050 memory address.
Example-
Input  : location: 2050
         Data   : 37
Output : location: 3050    
         Data   : 07        
Algorithm –
Move value at [2050] into ALPerform AND operation on AL with 0FMove content of accumulator AL into 3050Stop
Move value at [2050] into AL
Perform AND operation on AL with 0F
Move content of accumulator AL into 3050
Stop
Program –
Explanation – Registers AL is used for general purpose
MOV is used to transfer the dataAND is used for multiplication (logically)HLT is used to halt the program
MOV is used to transfer the data
AND is used for multiplication (logically)
HLT is used to halt the program
Ankit_Bisht
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Direct Access Media (DMA) Controller in Computer Architecture
Computer Organization and Architecture | Pipelining | Set 2 (Dependencies and Data Hazard)
Architecture of 8085 microprocessor
Pin diagram of 8086 microprocessor
Difference between Hardwired and Micro-programmed Control Unit | Set 2
I2C Communication Protocol
Memory mapped I/O and Isolated I/O
Computer Architecture | Flynn's taxonomy
Introduction to memory and memory units
Introduction of Control Unit and its Design
Find the factorial of a number in pl/sql - GeeksforGeeks

06 May, 2018
Given a number, your task to print the factorial of that number using pl/sql.
Examples:
Input : 5
Output : 120

Explanation:5! = 5 * 4 * 3 * 2 * 1 = 120
Input : 4
Output : 24

Basic structure of pl/sql block
declare
-- declare all the variables

begin  -- for start block
-- make a program here

end -- for end block

The program of factorial of a number in pl/sql is given below:
declare -- it gives the final answer after computationfac number :=1;     -- given number n-- taking input from usern number := &1;     -- start blockbegin           -- start while loop    while n > 0 loop    -- multiple with n and decrease n's valuefac:=n*fac;        n:=n-1;           end loop;         -- end loop  -- print result of facdbms_output.put_line(fac);    -- end the begin blockend;              
Output:(if given input as 5)
120

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Convert VARCHAR to INT
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
How to Select Data Between Two Dates and Times in SQL Server?
How to Write a SQL Query For a Specific Date Range and Date Time?
SQL Query to Compare Two Dates
Convert a String into Date Format in R Programming - as.Date() Function - GeeksforGeeks

30 Jun, 2020
as.Date() function in R Language is used to convert a string into date format.
Syntax: as.Date(x, format)
Parameters:x: string variableformat: Format in which string is declared(%m/%d/%y)
Example 1:
# R program to convert string into date  # Creating a string vectordates <- c("27 / 02 / 92")     # Conversion into date format result<-as.Date(dates, "% d/% m/% y")     # Print result print(result) 
Output:
[1] "1992-02-27"

Example 2:
# R program to convert string into date  # Creating a string vectordates <- c("02 / 27 / 92", "02 / 27 / 92",             "01 / 14 / 92", "02 / 28 / 92",             "02 / 01 / 92")     # Conversion into date format result<-as.Date(dates, "% m/% d/% y")     # Print result print(result) 
Output:
[1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28" "1992-02-01"

R Date-Function
R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
Thread get_id() function in C++ - GeeksforGeeks

16 Jun, 2021
Thread::get_id() is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the value of std::thread::id thus identifying the thread associated with *this.Syntax:  
thread_name.get_id();
Parameters: This function does not accept any parameters.Return Value: This method returns a value of type std::thread::id identifying the thread associated with *this i.e. the thread which was used to call the get_id function is returned. The default constructed std::thread::id is returned when no such thread is identified.Below examples demonstrates the use of std::thread::get_id() method:Note: On the online IDE this program will show error. To compile this, use the flag “-pthread” on g++ compilers compilation with the help of command “g++ –std=c++14 -pthread file.cpp”. 
CPP
// C++ program to demonstrate the use of// std::thread::get_id #include <chrono>#include <iostream>#include <thread>using namespace std; // util function for thread creationvoid sleepThread(){    this_thread::sleep_for(chrono::seconds(1));} int main(){    // creating thread1 and thread2     thread thread1(sleepThread);    thread thread2(sleepThread);     thread::id t1_id = thread1.get_id();    thread::id t2_id = thread2.get_id();     cout << "ID associated with thread1= "         << t1_id << endl;    cout << "ID associated with thread2= "         << t2_id << endl;     thread1.join();    thread2.join();     return 0;}
Possible Output:  
ID associated with thread1= 139858743162624
ID associated with thread2= 139858734769920
 
adnanirshad158
CPP-Functions
Processes & Threads
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Sorting a Map by value in C++ STL
Java - toDegrees() Method

The method converts the argument value to degrees.
double toDegrees(double d)

Here is the detail of parameters −
d − A double data type.
d − A double data type.
This method returns a double value.
public class Test { 

   public static void main(String args[]) {
      double x = 45.0;
      double y = 30.0;

      System.out.println( Math.toDegrees(x) );
      System.out.println( Math.toDegrees(y) );
   }
}
This will produce the following result −
2578.3100780887044
1718.8733853924698


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to change the position of the legend in a PieChart in JavaFX?

In the pie chart, we represent the data values as slices of a circle. Each slice is differentiated from other (typically by color). In JavaFX, you can create a pie chart by instantiating the javafx.scene.chart.PieChart class.
By default, a JavaFX pie chart contains labels of the slices and a legend − a bar with colors specifying the category represented by each color.
The PieChart class has a property named legendSide (inherited from the Chart class). This specifies the position of the legend in the chart (left, right, top-bottom). You can set the value to this property using the setLegendSide() method. This method accepts one of the following values as a parameter −
Side.BOTTOM
Side.BOTTOM
Side.TOP
Side.TOP
Side.LEFT
Side.LEFT
Side.RIGHT
Side.RIGHT
You can change the position of the legend in a chart, by invoking the setLegendSide() method by passing the appropriate value as a parameter.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Side;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.StackPane;
public class PieChart_LegendPosition extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a Pie chart
      PieChart pieChart = new PieChart();
      //Setting data
      ObservableList data = FXCollections.observableArrayList(
      new PieChart.Data("Work", 10),
      new PieChart.Data("Chores", 2),
      new PieChart.Data("Sleep", 8),
      new PieChart.Data("Others", 4));
      pieChart.setData(data);
      //Setting the legend on the left side of the chart
      pieChart.setLegendSide(Side.LEFT);
      //Creating a stack pane to hold the pie chart
      StackPane pane = new StackPane(pieChart);
      pane.setStyle("-fx-background-color: BEIGE");
      //Setting the Scene
      Scene scene = new Scene(pane, 595, 300);
      stage.setTitle("Pie Chart");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
PyQt5 – How to add padding to a Label ? - GeeksforGeeks

26 Mar, 2020
In this article, we will see how to add padding to our Label. Padding is just the space between the border and the content. Below is image of label this will helps in better understanding of the padding.
In order to add padding to our label, we will use setStyleSheet() method, below is how without padding label vs padded label looks like.
Syntax : label.setStyleSheet(“padding :15px”)
Argument : It takes string as argument.
Action performed : It adds padding to the label.
Code :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          # setting  the geometry of window        self.setGeometry(60, 60, 600, 400)            # creating a label widget        self.label_1 = QLabel("===============", self)          # moving position        self.label_1.move(100, 100)          # setting up the border        self.label_1.setStyleSheet("border :3px solid blue;")          # resizing label        self.label_1.resize(100, 100)        # creating a label widget        self.label_2 = QLabel("==================", self)          # setting up the border and adding padding        self.label_2.setStyleSheet("border :3px solid blue;padding :15px")          # moving position        self.label_2.move(230, 200)          # resizing the label        self.label_2.resize(100, 100)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
PHP - hash() Function

The hash() function returns a hash value for the given data based on the algorithm like (md5, sha256). The return value is a string with hexits (hexadecimal values).
hash ( string $algo , string $data [, bool $raw_output = FALSE ] ) : string

algo
Name of the hashing algorithm. There is a big list of algorithm available with hash, some important ones are md5, sha256, etc. To get the full list of algorithms supported use the hashing function hash_algos()
data
The data you want the hash to be generated. Please note once the hash is generated it cannot be reversed.
raw_output
By default, the value is false and hence it returns lowercase hexits values. If the value is true, it will return raw binary data.
PHP hash() function returns a string with lowercase hexits. If the raw_output is set to true, it will return raw binary data.
This function will work from PHP Version greater than 5.1.2.
To generate hash value using md5 Algorithm −
<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint');
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - 8ab923b97822bd258bf882e41de6ebff

To generate hash value using sha256 Algorithm −
<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('sha256', 'Welcome to Tutorialspoint');
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e

To generate hash using crc32b Algorithm −
<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('crc32b', 'Welcome to Tutorialspoint');
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - cd12151c

To generate hash with raw_output as true −
<?php
   echo "The hash of Welcome to Tutorialspoint is - ". hash('md5', 'Welcome to Tutorialspoint', true);
?>
This will produce the following result −
The hash of Welcome to Tutorialspoint is - ��#�x"�%����u001d���


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
HTML | <th> width Attribute - GeeksforGeeks

26 Jun, 2019
The HTML <th> width Attribute is used to specify the width of a table header cell. If width attribute is not set then it takes default width according to content. It is not supported by HTML 5.
Syntax:
<th width="pixels | %">
Attribute Values:
pixels: It sets the width of table header cell in terms of pixels.
%: It sets the width of table header cell in terms of percentage (%).
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML th width Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML th width Attribute</h2>      <table border="1" width="500">        <tr>            <th width="50%">NAME</th>            <th width="20%">AGE</th>            <th width="30%">BRANCH</th>        </tr>          <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>          <tr>            <td>RAKESH</td>            <td>25</td>            <td>EC</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <th> width attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
LASTNONBLANK function

Returns the last value in the column filtered by the current context, where the expression is not blank.
LASTNONBLANK (<column>, <expression>) 

column
A column expression.
expression
An expression evaluated for blanks for each value of column.
A table containing a single column and single row with the computed last non-blank value.
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.
= LASTNONBLANK (Sales [Sales Amount], MIN (Sales [Date])>3/31/2015) 

    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
MariaDB - Select Database

After connecting to MariaDB, you must select a database to work with because many databases may exist. There are two ways to perform this task: from the command prompt or through a PHP script.
In choosing a database at the command prompt, simply utilize the SQL command ‘use’ −
[root@host]# mysql -u root -p

Enter password:******

mysql> use PRODUCTS;

Database changed

mysql> SELECT database();  
+-------------------------+ 
| Database                | 
+-------------------------+ 
| PRODUCTS                | 
+-------------------------+ 

Once you select a database, all subsequent commands will operate on the chosen database.
Note − All names (e.g., database, table, fields) are case sensitive. Ensure commands conform to the proper case.
PHP provides the mysql_select_db function for database selection. The function uses two parameters, one optional, and returns a value of “true” on successful selection, or false on failure.
Review the following select database script syntax.
bool mysql_select_db( db_name, connection );

The description of the parameters is given below −
db_name
This required parameter specifies the name of the database to use.
connection
When not specified, this optional parameter uses the most recent connection used.
Try the following example code for selecting a database −
<html>
   <head>
      <title>Select a MariaDB Database</title>
   </head>

   <body>
      <?php
         $dbhost = 'localhost:3036';
         $dbuser = 'guest1';
         $dbpass = 'guest1a';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);
      
         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         echo 'Connected successfully';
         
         mysql_select_db( 'PRODUCTS' );
         mysql_close($conn);
      ?>
   </body>
</html>
On successful selection, you will see the following output −
mysql> Connected successfully 

 Print
 Add Notes
 Bookmark this page
Nth Digit in C++

Suppose we have one infinite integer sequence, we have to find the nth digit of this sequence. So if the input is 11, then the output will be 0 as if we place the numbers like 123456789101112, so the 11th digit is 0.
To solve this, we will follow these steps −
len := 0 and cnt := 9 and start := 1
len := 0 and cnt := 9 and start := 1
while n > len * cntn := n – (len * cnt)cnt := cnt * 10, start := start * 10increase len by 1
while n > len * cnt
n := n – (len * cnt)
n := n – (len * cnt)
cnt := cnt * 10, start := start * 10
cnt := cnt * 10, start := start * 10
increase len by 1
increase len by 1
start := start +(n - 1) / len
start := start +(n - 1) / len
s := start as string
s := start as string
return s[(n – 1) mod len]
return s[(n – 1) mod len]
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
   int findNthDigit(int n) {
      lli len = 1;
      lli cnt = 9;
      lli start = 1;
      while(n > len * cnt){
         n -= len * cnt;
         cnt *= 10;
         start *= 10;
         len++;
      }
      start += (n - 1) / len;
      string s = to_string(start);
      return s[(n - 1) % len] - '0';
   }
};
main(){
   Solution ob;
   cout << (ob.findNthDigit(11));
}
11
0
Notebook widget in Tkinter

Notebook widget is an inbuilt widget of ttk library in tkinter. It enables the user to create Tabs in the window application. Tabs are generally used to separate the workspace and specialize the group of operations in applications at the same time.
In this example, we will create two tabs using Notebook widget and then will add some context to it.
#Import the required library
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win = Tk()
win.geometry("750x250")
#Create a Notebook widget
my_notebook= ttk.Notebook(win)
my_notebook.pack(expand=1,fill=BOTH)
#Create Tabs
tab1= ttk.Frame(my_notebook)
my_notebook.add(tab1, text= "Tab 1")
tab2= ttk.Frame(my_notebook)
my_notebook.add(tab2, text= "Tab2")
#Create a Label in Tabs
Label(tab1, text= "Hello, Howdy?", font= ('Helvetica 20 bold')).pack()
Label(tab2, text= "This is a New Tab Context", font=('Helvetica
20 bold')).pack()
win.mainloop()
Running the above code will display a window containing two tabs, tab1 and tab2 respectively. Tabs contain some Text Labels in it.
Now, switch to "tab1" and then "tab2" to see the changes between the two tabs.
String compareTo() Method

Returns a new string by removing all leading and trailing spaces. However, this method doesn’t discard spaces between two strings.
compareTo(String other)

Returns an integer representing the relationship between two strings.
0 − when the strings are equal.
0 − when the strings are equal.
1 − when the first string is greater than the second
1 − when the first string is greater than the second
-1 − when the first string is smaller than the second
-1 − when the first string is smaller than the second
void main() { 
   String str1 = "A"; 
   String str2 = "A"; 
   String str3 = "B"; 
   
   print("str1.compareTo(str2): ${str1.compareTo(str2)}"); 
   print("str1.compareTo(str3): ${str1.compareTo(str3)}"); 
   print("str3.compareTo(str2): ${str3.compareTo(str2)}"); 
} 
It will produce the following output −.
str1.compareTo(str2): 0 
str1.compareTo(str3): -1 
str3.compareTo(str2): 1 


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
C - if statement

An if statement consists of a Boolean expression followed by one or more statements.
The syntax of an 'if' statement in C programming language is −
if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

If the Boolean expression evaluates to true, then the block of code inside the 'if' statement will be executed. If the  Boolean expression evaluates to false, then the first set of code after the end of the 'if' statement (after the closing curly brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is either zero or null, then it is assumed as false value.
#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 10;
 
   /* check the boolean condition using if statement */
	
   if( a < 20 ) {
      /* if condition is true then print the following */
      printf("a is less than 20\n" );
   }
   
   printf("value of a is : %d\n", a);
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
a is less than 20;
value of a is : 10

 Print
 Add Notes
 Bookmark this page
Like Operator in SAS Programming - GeeksforGeeks

23 Jul, 2019
LIKE Operator: Pattern Matching
The LIKE operator used to select data by comparing the values of a character variable to a specified pattern. It is case sensitive.
Task 1: To select all students with a name that starts with the letter S.
There are two special characters patterns available for specifying a pattern:
percent sign (%) – Wildcard Character
percent sign (%) – Wildcard Character
underscore ( _ ) – Fill in the blanks
underscore ( _ ) – Fill in the blanks
data readin;input name $ Section $ Score;cards;Raj  A 80Atul . 77Priya . 45Sandy A 67David B 39Rahul . 95Sahil C 84Savitri B 65;run;  data readin1;set readin;where name like 'S%';run;
Output:
In a given dataset, the above statements would produce the same result in both cases.
Examples:
where name like '%ul';Output:It contains all the data where the name ends with ‘ul’.where name like '_ah%';Output:It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place.where name like '_a___';Output:It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place.
where name like '%ul';Output:It contains all the data where the name ends with ‘ul’.
where name like '%ul';
Output:
It contains all the data where the name ends with ‘ul’.
where name like '_ah%';Output:It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place.
where name like '_ah%';
Output:
It contains all the data where the name contains atleast 3 characters, which must contain ‘ah’ at second place.
where name like '_a___';Output:It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place.
where name like '_a___';
Output:
It contains all the data where the name contains atleast 5 characters, which must contain ‘a’ at second place.
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
All forms of formatted scanf() in C
Difference Between Imperative and Declarative Programming
Difference between while and do-while loop in C, C++, Java
Top 10 Programming Languages to Learn in 2022
Prolog | An Introduction
Header Guard in C++
Lists in Prolog
Scope of Variable in R
DataFrame Operations in R
Top 10 Fastest Programming Languages
Sort an array of dates in PHP

To sort an array of dates in PHP, the code is as follows−
 Live Demo
<?php
   function compareDates($date1, $date2){
      return strtotime($date1) - strtotime($date2);
   }
   $dateArr = array("2019-11-11", "2019-10-10","2019-08-10", "2019-09-08");
   usort($dateArr, "compareDates");
   print_r($dateArr);
?>
This will produce the following output−
Array
(
   [0] => 2019-08-10
   [1] => 2019-09-08
   [2] => 2019-10-10
   [3] => 2019-11-11
)
Let us now see another example −
 Live Demo
<?php
   function compareDates($date1, $date2){
      if (strtotime($date1) < strtotime($date2))
         return 1;
      else if (strtotime($date1) > strtotime($date2))
         return -1;
      else
         return 0;
   }
   $dateArr = array("2019-11-11", "2019-10-10","2019-11-11", "2019-09-08","2019-05-11", "2019-01-01");
   usort($dateArr, "compareDates");
   print_r($dateArr);
?>
This will produce the following output−
Array
(
   [0] => 2019-11-11
   [1] => 2019-11-11
   [2] => 2019-10-10
   [3] => 2019-09-08
   [4] => 2019-05-11
   [5] => 2019-01-01
)
Recursive program to find an element in an array linearly.

Following is a Java program to find an element in an array linearly.
 Live Demo
import java.util.Scanner;
public class SearchingRecursively {
   public static boolean searchArray(int[] myArray, int element, int size){
      if (size == 0){
         return false;
      }
      if (myArray[size-1] == element){
         return true;
      }
      return searchArray(myArray, element, size-1);
   }
   public static void main(String args[]){
      System.out.println("Enter the required size of the array: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      System.out.println("Enter the elements of the array one by one ");
      for(int i=0; i<size; i++){
         myArray[i] = s.nextInt();
      }
      System.out.println("Enter the element to be searched: ");
      int target = s.nextInt();
      boolean bool = searchArray(myArray, target ,size);
      if(bool){
         System.out.println("Element found");
      }else{
         System.out.println("Element not found");
      }
   }
}
Enter the required size of the array:
5
Enter the elements of the array one by one
14
632
88
98
75
Enter the element to be searched:
632
Element found
MongoDB - Insert Multiple Document Using MongoShell - GeeksforGeeks

27 Feb, 2020
In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to insert multiple documents in the collection by using db.collection.insertMany() method.
insertMany() is a mongo shell method, which can insert multiple documents. This method can be used in the multi-document transactions. In this method, you can add documents in the collection with or without _id field. If you add documents without _id field, then mongodb will automatically add _id fields for each documents and assign them with a unique ObjectId. This method by default insert documents in order.
Syntax:
db.collection.insertMany(
   [  <Document1>, <Document2>, <Document3> ... ],
   {
      writeConcern: <Document>,
      order: <Boolean> 
   }
)
Parameters:
Document: It represents the array of the documents that will insert in the collection.Optional Parameters:
writeConcern: It is only used when you do not want to use the default write concern,
order: It specifies whether the mongodb instance performs an ordered or unordered insert, the default value of this parameter is true.
Return: This method will return a document that contains a boolean acknowledged as true (if the write concern is enabled) or false (if the write concern is disabled) and insertedId represents the _id field of the inserted document.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: student
In this example, we are inserting multiple documents in the student collection without _id field using db.collection.insertMany() method.
In this example, we are inserting multiple documents in the student collection with _id field using db.collection.insertMany() method.
MongoDB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Copying Files to and from Docker Containers
Principal Component Analysis with Python
OpenCV - Overview
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
Mounting a Volume Inside Docker Container
Getting Started with System Design
How to create a REST API using Java Spring Boot
Basics of API Testing Using Postman
Q-Learning in Python
Break a list into chunks of size N in Python - GeeksforGeeks

24 Apr, 2020
Method 1: Using yieldThe yield keyword enables a function to comeback where it left off when it is called again. This is the critical difference from a regular function. A regular function cannot comes back where it left off. The yield keyword helps a function to remember its state. The yield enables a function to suspend and resume while it turns in a value at the time of the suspension of the execution.
my_list = ['geeks', 'for', 'geeks', 'like',           'geeky','nerdy', 'geek', 'love',               'questions','words', 'life']  # Yield successive n-sized# chunks from l.def divide_chunks(l, n):          # looping till length l    for i in range(0, len(l), n):         yield l[i:i + n]  # How many elements each# list should haven = 5  x = list(divide_chunks(my_list, n))print (x)
Output:
[['geeks', 'for', 'geeks', 'like', 'geeky'], 
 ['nerdy', 'geek', 'love', 'questions', 'words'], 
 ['life']]

Method 2: Using List comprehensionList comprehension is an elegant way to break a list in one line of code.
my_list = [1, 2, 3, 4, 5,              6, 7, 8, 9]  # How many elements each# list should haven = 4   # using list comprehensionfinal = [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] print (final)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

Alternate Implementation :
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]    # How many elements each # list should have n = 4   # using list comprehension x = [l[i:i + n] for i in range(0, len(l), n)] print(x)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]

sloanlancegeeksforgeeksorg
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
sum() function in Python
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Print lists in Python (4 Different Ways)
How to create Python dictionary from the value of another dictionary?

You can do this by merging the other dictionary to the first dictionary. In Python 3.5+, you can use the ** operator to unpack a dictionary and combine multiple dictionaries using the following syntax −
a = {'foo': 125}
b = {'bar': "hello"}
c = {**a, **b}
print(c)
This will give the output −
{'foo': 125, 'bar': 'hello'}
This is not supported in older versions. You can however replace it using the following similar syntax −
a = {'foo': 125}
b = {'bar': "hello"}
c = dict(a, **b)
print(c)
This will give the output −
{'foo': 125, 'bar': 'hello'}
Another thing you can do is using copy and update functions to merge the dictionaries. 
def merge_dicts(x, y):
   z = x.copy() # start with x's keys and values
   z.update(y) # modify z with y's keys and values
   return z
a = {'foo': 125}
b = {'bar': "hello"}
c = merge_dicts(a, b)
print(c)
This will give the output −
{'foo': 125, 'bar': 'hello'}
C | Dynamic Memory Allocation | Question 8 - GeeksforGeeks

08 Aug, 2018
Consider the following program, where are i, j and k are stored in memory?
int i;int main(){    int j;    int *k = (int *) malloc (sizeof(int));}
(A) i, j and *k are stored in stack segment(B) i and j are stored in stack segment. *k is stored on heap.(C) i is stored in BSS part of data segment, j is stored in stack segment. *k is stored on heap.(D) j is stored in BSS part of data segment, i is stored in stack segment. *k is stored on heap.Answer: (C)Explanation: i is global variable and it is uninitialized so it is stored on BSS part of Data Segment (http://en.wikipedia.org/wiki/.bss)
j is local in main() so it is stored in stack frame (http://en.wikipedia.org/wiki/Call_stack)
*k is dynamically allocated so it is stored on Heap Segment.
See following article for more details.
Memory Layout of C ProgramsQuiz of this Question
C-Dynamic Memory Allocation
Dynamic Memory Allocation
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1
Can we use “LIKE concat()” in a MySQL query?

Yes, we can do that. Let us first create a table −
mysql> create table DemoTable
(
   Name varchar(50)
);
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Bob');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('Mike');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+
| Name |
+------+
| John |
| Adam |
| Bob  |
| Mike |
+------+
4 rows in set (0.00 sec)
Following is the query to use “LIKE concat()” in MySQL −
mysql> select Name from DemoTable where Name LIKE concat('%','o','%');
This will produce the following output −
+------+
| Name |
+------+
| John |
| Bob  |
+------+
2 rows in set (0.03 sec)
How to move an element of an array to a specific position (swap)?

To move an element from one position to other (swap) you need to –
Create a temp variable and assign the value of the original position to it.
Now, assign the value in the new position to original position.
Finally, assign the value in the temp to the new position.
Live Demo
import java.util.Arrays;
public class ChangingPositions {
   public static void main(String args[]) {
      int originalPosition = 1;
      int newPosition = 1;
      int [] myArray = {23, 93, 56, 92, 39};
      int temp = myArray[originalPosition];
     
      myArray[originalPosition] = myArray[newPosition];
      myArray[newPosition] = temp;
      System.out.println(Arrays.toString(myArray));
   }
}
[23, 39, 56, 92, 93]
Remove Vowels from a String in Python

Suppose we have a string, we have to remove all vowels from that string. So if the string is like “iloveprogramming”, then after removing vowels, the result will be − "lvprgrmmng"
To solve this, we will follow these steps −
create one array vowel, that is holding [a,e,i,o,u]
for v in a vowelreplace v using blank string
replace v using blank string
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def removeVowels(self, s):
      s = s.replace("a","")
      s = s.replace("e","")
      s = s.replace("i","")
      s = s.replace("o","")
      s = s.replace("u","")
      return s
ob1 = Solution()
print(ob1.removeVowels("iloveprogramming"))
"iloveprogramming"
lvprgrmmng
Solidity - First Application

We're using Remix IDE to Compile and Run our Solidity Code base.
Step 1 − Copy the given code in Remix IDE Code Section.
pragma solidity ^0.5.0;
contract SolidityTest {
   constructor() public{
   }
   function getResult() public view returns(uint){
      uint a = 1;
      uint b = 2;
      uint result = a + b;
      return result;
   }
}
Step 2 − Under Compile Tab, click Start to Compile button.
Step 3 − Under Run Tab, click Deploy button.
Step 4 − Under Run Tab, Select SolidityTest at 0x... in drop-down.
Step 5 − Click getResult Button to display the result.
0: uint256: 3


    38 Lectures 
     4.5 hours 

 Abhilash Nelson

    62 Lectures 
     8.5 hours 

 Frahaan Hussain

    31 Lectures 
     3.5 hours 

 Swapnil Kole
 Print
 Add Notes
 Bookmark this page
How do I format a string using a dictionary in Python 3?

You can use dictionaries to interpolate strings. They have a syntax in which you need to provide the key in the parentheses between the % and the conversion character. For example, if you have a float stored in a key 'cost' and want to format it as '$xxxx.xx', then you'll place '$%(cost).2f' at the place you want to display it.
Here is an example of using string formatting in dictionaries to interpolate a string and format a number:
>>>print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2})
Python has 002 quote types.
You can read up more about string formatting and their operators here: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
How to check the PowerShell version installed in local and remote systems?

To check the PowerShell version installed in your system, you can use either $PSVersionTable or $host command.
Check if $host command available in remote servers.
Check if $host command available in remote servers.
Open the PowerShell console in the system and run the command $PSVersionTable.
$PSVersionTable
PS C:\WINDOWS\system32> $PSVersionTable
Name                             Value
----                             -----
PSVersion                        5.1.18362.628
PSEdition                        Desktop
PSCompatibleVersions             {1.0, 2.0, 3.0, 4.0...}
BuildVersion                     10.0.18362.628
CLRVersion                       4.0.30319.42000
WSManStackVersion                3.0
PSRemotingProtocolVersion        2.3
SerializationVersion             1.1.0.1
So here, we have an output of the $PSVersionTable. You can see the output property $PSVersion, which indicates the version information of the PowerShell.
$PSVersionTable.PSVersion
Major    Minor    Build    Revision
-----    -----    -----    --------
5       1         18362    628
In the Major property, it indicates the PowerShell version is 5 and Build is 18362.
Similarly, you can get the above output with the $Host command in PowerShell.
PS C:\WINDOWS\system32> $Host
Name :                       ConsoleHost
Version                      : 5.1.18362.628
InstanceId                   : f6d2bf19-db26-403b-9749-afede37ea56f
UI                           : System.Management.Automation.Internal.Host.InternalHostUserInterface CurrentCulture               :en-IN
CurrentUICulture             : en-US
PrivateData                  : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled              : True
IsRunspacePushed             : False
Runspace                     : System.Management.Automation.Runspaces.LocalRunspace
You can get the PowerShell version from version property.
$Host.Version
PS C:\WINDOWS\system32> $Host.Version
Major    Minor    Build    Revision
 -----   -----    -----    --------
 5       1        18362    628
To get the output on the remote computer, you need to use Invoke-Command or PSRemote session command as the $PSverionTable and $Host doesn’t support the − ComputerName Parameter.
Invoke-Command -ComputerName Test-PC -ScriptBlock{$PSVersionTable.PSVersion}
If you have multiple computers and if you need the Hostname and the PS version against the hostname then you can use the Pipeline or the PSCustomObject command.
Invoke-Command -ComputerName Test-PC,DC1 -ScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N="PS Version";E={$_.Major}}
If you have a list of servers then you can add all the servers into the text file and run the above command.
For example, We have servers list stored in D:\Temp\Servers.txt and we need to get the PS version on them.
Invoke-Command -ComputerName (Get-Content D:\Temp\Servers.txt) -
ScriptBlock{$PSVersionTable.PSVersion} | Select PSComputerName, @{N="PS Version";E={$_.Major}}
Node.js Buffer.toJSON() Method - GeeksforGeeks

13 Oct, 2021
Buffer is a temporary memory storage which stores the data when it is being moved from one place to another. It is like the array of integers.
The Buffer.toJSON() method returns the buffer in JSON format.
Note: The JSON.Stringify() is the method which can also be used to return the data in JSON format. When we call the JSON.Stringify() method, it directly in the background calls the buffer.toJSON() Method.
Syntax:
buffer.toJSON()
Return Value: It returns the buffer in JSON format.
Below examples illustrate the use of Buffer.toJSON() method in Node.js:
Example 1:
// Node.js program to demonstrate the  // Buffer.toJSON() Method  var buffer = Buffer.from('GeeksforGeeks');   // Prints: the ascii values of each// character of 'GeeksforGeeks'console.log(buffer.toJSON());
Output:
{
  type: 'Buffer',
  data: [
     71, 101, 101, 107,
    115, 102, 111, 114,
     71, 101, 101, 107,
    115
  ]
}

Example 2: This example implements the use of JSON.Stringify() method.
// Node.js program to demonstrate the  // Buffer.toJSON() Method  const buffer = Buffer.from([1, 2, 3, 4]);  const output = JSON.stringify(buffer);  // Prints: {"type":"Buffer", "data":[1, 2, 3, 4]}console.log(output);
Output:
{"type":"Buffer", "data":[1, 2, 3, 4]}
Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_buf_tojson
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to create a dynamic 2D array inside a class in C++ ? - GeeksforGeeks

29 May, 2017
Suppose we want to create a class for Graph. The class stores adjacency matrix representation of the graph. Therefore, our class structure would be something like below.
class Graph {  int V;   int adj[V][V];  // This line doesn't work      /* Rest of the members */};  int main(){}
Output :
error: invalid use of non-static data
       member 'Graph::V'.

Even if we make V static, we get error “array bound is not an integer constant”
C++ doesn’t allow to create an stack allocated array in a class whose size is not constant. So we need to dynamically allocate memory. Below is a simple program to show how to dynamically allocate 2D array in a C++ class using a class for Graph with adjacency matrix representation.
// C++ program to show how to allocate dynamic 2D// array in a class using a Graph example.#include<bits/stdc++.h>using namespace std;  // A Class to represent directed graphclass Graph{    int V;    // No. of vertices      // adj[u][v] would be true if there is an edge    // from u to v, else false    bool **adj;  public:    Graph(int V);   // Constructor      // function to add an edge to graph    void addEdge(int u, int v)  { adj[u][v] = true; }    void print();};  Graph::Graph(int V){    this->V = V;      // Create a dynamic array of pointers    adj = new bool* [V];      // Create a row for every pointer    for (int i=0; i<V; i++)    {       // Note : Rows may not be contiguous       adj[i] = new bool[V];         // Initialize all entries as false to indicate       // that there are no edges initially       memset(adj[i], false, V*sizeof(bool));    }}  // Utility method to print adjacency matrixvoid Graph::print(){   for (int u=0; u<V; u++)   {      for (int v=0; v<V; v++)         cout << adj[u][v] << " ";      cout << endl;   }}  // Driver methodint main(){    // Create a graph given in the above diagram    Graph g(4);    g.addEdge(0, 1);    g.addEdge(0, 2);    g.addEdge(1, 2);    g.addEdge(2, 0);    g.addEdge(2, 3);    g.addEdge(3, 3);      g.print();      return 0;}
Output :
0 1 1 0 
0 0 1 0 
1 0 0 1 
0 0 0 1 

A note on call of memset():memset() is used separately for individual rows. We can’t replace these calls with one call because rows are allocated at different addresses and making a memset call like below would be disastrous.
       // Wrong!! (Rows of matrix at different addresses)
       memset(adj, false, V*V*sizeof(bool));
This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
cpp-array
cpp-class
cpp-pointer
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function Pointer in C
Substring in C++
rand() and srand() in C/C++
fork() in C
std::string class in C++
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
Virtual Function in C++