code-rag-bench/online-tutorials huggingface dataset:
How to create list of dictionary in Python

03 Feb, 2022
In this article, we are going to discuss ways in which we can create a list of dictionaries in Python. 
A list of dictionaries means, the dictionary is present as an element in the list. 
Syntax:
[{‘key’:element1,’key’:element2,......, ‘key’:element n}]
Example: Python code to create a list of dictionary for students data
Python3
# create a list of dictionary with student# id as key and name as valuedata = [{7058: 'sravan', 7059: 'jyothika',         7072: 'harsha', 7075: 'deepika'}] # display datadata
Output:
[{7058: ‘sravan’, 7059: ‘jyothika’, 7072: ‘harsha’, 7075: ‘deepika’}]
We can access by using index
Syntax:
data[index][key]
where index is the dictionary index and the key is the dictionary key-value
Example: Python code to access keys via index
Python3
# create a list of dictionary with student# id as key and name as valuedata = [{7058: 'sravan', 7059: 'jyothika',         7072: 'harsha', 7075: 'deepika'}] # display data of key 7058print(data[0][7058]) # display data of key 7059print(data[0][7059]) # display data of key 7072print(data[0][7072]) # display data of key 7075print(data[0][7075])
Output:
sravan
jyothika
harsha
deepika
This is similar to the above approach, except that multiple dictionaries are being passed to the list at once.
Example: Python program to create a list of multiple dictionaries 
Python3
# create a list of dictionaries with# student id as key and name as valuedata = [{7058: 'sravan', 7059: 'jyothika',         7072: 'harsha', 7075: 'deepika'},                 {7051: 'fathima', 7089: 'mounika',         7012: 'thanmai', 7115: 'vasavi'},                 {9001: 'ojaswi', 1289: 'daksha',         7045: 'parvathi', 9815: 'bhavani'}] print(data)
Output:
[{7058: ‘sravan’, 7059: ‘jyothika’, 7072: ‘harsha’, 7075: ‘deepika’}, {7051: ‘fathima’, 7089: ‘mounika’, 7012: ‘thanmai’, 7115: ‘vasavi’}, {9001: ‘ojaswi’, 1289: ‘daksha’, 7045: ‘parvathi’, 9815: ‘bhavani’}]
It can again access all the elements using index.
Example: Python code to access elements based on index and key
Python3
# create a list of dictionaries with# student id as key and name as valuedata = [{7058: 'sravan', 7059: 'jyothika',         7072: 'harsha', 7075: 'deepika'},                 {7051: 'fathima', 7089: 'mounika',         7012: 'thanmai', 7115: 'vasavi'},                 {9001: 'ojaswi', 1289: 'daksha',         7045: 'parvathi', 9815: 'bhavani'}] # access third dictionary with key 9001print(data[2][9001]) # access second dictionary with key 7012print(data[1][7012]) # access second dictionary with key 7115print(data[1][7115])
Output:
ojaswi
thanmai
vasavi
sumitgumber28
Picked
Python List-of-Dict
python-dict
python-list
Python
python-dict
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ispunct() function in C

16 Dec, 2021
The ispunct() function checks whether a character is a punctuation character or not.The term “punctuation” as defined by this function includes all printable characters that are neither alphanumeric nor a space. For example ‘@’, ‘$’, etc.This function is defined in ctype.h header file.
int ispunct(int ch);
ch: character to be checked.
Return Value  : function return nonzero
 if character is a punctuation character;
 otherwise zero is returned. 

CPP
// Program to check punctuation#include <stdio.h>#include <ctype.h>int main(){    // The punctuations in str are '!' and ','    char str[] = "welcome! to GeeksForGeeks, ";      int i = 0, count = 0;    while (str[i]) {        if (ispunct(str[i]))            count++;        i++;    }    printf("Sentence contains %d punctuation"           " characters.\n", count);    return 0;}

Sentence contains 2 punctuation characters.

CPP
// C program to print all Punctuations#include <stdio.h>#include <ctype.h>int main(){    int i;    printf("All punctuation characters in C"            " programming are: \n");    for (i = 0; i <= 255; ++i)        if (ispunct(i) != 0)            printf("%c ", i);    return 0;}
All punctuation characters in C programming are: 
! " # $ % & ' ( ) * +, - . / : ;  ? @ [ \ ] ^ _ ` { | } ~

This article is contributed by Shivani Ghughtyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
surinderdawra388
C-Library
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JSP - Auto Refresh

In this chapter, we will discuss Auto Refresh in JSP. Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such type of pages, you would need to refresh your Webpage regularly using refresh or reload button with your browser.
JSP makes this job easy by providing you a mechanism where you can make a webpage in such a way that it would refresh automatically after a given interval.
The simplest way of refreshing a Webpage is by using the setIntHeader() method of the response object. Following is the signature of this method −
public void setIntHeader(String header, int headerValue)

This method sends back the header "Refresh" to the browser along with an integer value which indicates time interval in seconds.
In the following example, we will use the setIntHeader() method to set Refresh header. This will help simulate a digital clock −
<%@ page import = "java.io.*,java.util.*" %>

<html>
   <head>
      <title>Auto Refresh Header Example</title>
   </head>
   
   <body>
      <center>
         <h2>Auto Refresh Header Example</h2>
         <%
            // Set refresh, autoload time as 5 seconds
            response.setIntHeader("Refresh", 5);
            
            // Get current time
            Calendar calendar = new GregorianCalendar();
            String am_pm;
            
            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            
            if(calendar.get(Calendar.AM_PM) == 0)
               am_pm = "AM";
            else
               am_pm = "PM";
            String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
            out.println("Crrent Time: " + CT + "\n");
         %>
      </center>
   
   </body>
</html>
Now put the above code in main.jsp and try to access it. This will display the current system time after every 5 seconds as follows. Just run the JSP and wait to see the result −

Auto Refresh Header Example
Current Time is: 9:44:50 PM


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Dynamically creating keys in JavaScript associative array

Javascript's associative arrays are nothing but javascript object
literals. You can add keys to these objects dynamically if the key is a
string using the square brackets notation. For example,
let a = {
   name: 'Ayush'
};
let key = 'age';
// Add the non existing key
a[key] = 35;
console.log(a)
This will give the output −
{ name: 'Ayush', age: 35 }
Sorting an array according to another array using pair in STL in C++

Suppose we have two different arrays. We have to sort one array based on the other array using C++ STL pair class. Consider two arrays are like A1 = [2, 1, 5, 4, 9, 3, 6, 7, 10, 8], and another array is like A2 = [A, B, C, D, E, F, G, H, I, J], The output will be like: A1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], A2 = [B, A, F, D, C, G, H, J, E, I]
Here we are using the pairs of C++ STL. The pair is formed by taking one element from A1, another element from A2. Then simply use the sorting function. One thing we have taken under consideration, that the first element in the pair, should form the array, according to which the sorting is performed.
 Live Demo
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;
template <class T>
void display(T arr[], int n) {
   for (int i = 0; i < n; i++)
   cout << arr[i] << " ";
}
void sortUsingSecondArr(int A1[], char A2[], int n){
   pair<int, char> pair_arr[n];
   for (int i = 0; i < n; i++) {
      pair_arr[i].first = A1[i];
      pair_arr[i].second = A2[i];
   }
   sort(pair_arr, pair_arr + n);
   for (int i = 0; i < n; i++) {
      A1[i] = pair_arr[i].first;
      A2[i] = pair_arr[i].second;
   }
}
int main() {
   int n = 10;
   int A1[] = {2, 1, 5, 4, 9, 3, 6, 7, 10, 8};
   char A2[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
   cout << "Before Sorting: "<<endl;
   cout << "First Array : "; display(A1, n);
   cout << "\nSecond Array: "; display(A2, n);
   sortUsingSecondArr(A1, A2, n);
   cout << "\n\nAfter Sorting: "<<endl;
   cout << "First Array : "; display(A1, n);
   cout << "\nSecond Array: "; display(A2, n);
}
Before Sorting:
First Array : 2 1 5 4 9 3 6 7 10 8
Second Array: A B C D E F G H I J
After Sorting:
First Array : 1 2 3 4 5 6 7 8 9 10
Second Array: B A F D C G H J E I
Java Program to get day of week as string

To get day of week as string, first let us display the current date −
LocalDate currentDate = LocalDate.now();
Now, use DayOfWeek to get the day of week from the current date −
DayOfWeek day = currentDate.getDayOfWeek();
Get the day of week as string −
String weekName = day.name();
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Demo {
   public static void main(String[] args) {
      LocalDate currentDate = LocalDate.now();
      System.out.println("Current Date = "+currentDate);
      DayOfWeek day = currentDate.getDayOfWeek();
      int weekVal = day.getValue();
      String weekName = day.name();
      System.out.println("Week Number = "+weekVal);
      System.out.println("Week Name = "+weekName);
   }
}
Current Date = 2019-04-12
Week Number = 5
Week Name = FRIDAY
sizeof and ternary operators in C

Besides the operators discussed above, there are few a other important operators including sizeof and ? :  supported by the C Language.
Try following example to understand all the miscellaneous operators available in C −
#include <stdio.h>

main() {

   int a = 4;
   short b;
   double c;
   int* ptr;

   /* example of sizeof operator */
   printf("Line 1 - Size of variable a = %d\n", sizeof(a) );
   printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
   printf("Line 3 - Size of variable c= %d\n", sizeof(c) );

   /* example of & and * operators */
   ptr = &a;	/* 'ptr' now contains the address of 'a'*/
   printf("value of a is  %d\n", a);
   printf("*ptr is %d.\n", *ptr);

   /* example of ternary operator */
   a = 10;
   b = (a == 1) ? 20: 30;
   printf( "Value of b is %d\n", b );

   b = (a == 10) ? 20: 30;
   printf( "Value of b is %d\n", b );
}
When you compile and execute the above program, it produces the following result −
Line 1 - Size of variable a = 4
Line 2 - Size of variable b = 2
Line 3 - Size of variable c= 8
value of a is  4
*ptr is 4.
Value of b is 30
Value of b is 20

 Print
 Add Notes
 Bookmark this page
PWM in Arduino

PWM refers to Pulse Width Modulation. In very simple terms, we can output a square wave from certain pins of the Arduino board, and we can control the fraction of time for which the wave will be at the HIGH state (known as the duty cycle).
PWM finds several applications. An important application is running motors. The RPM of the motor can be controlled by the PWM output. PWM can also be used in general for generating voltages between HIGH and LOW. So, if your HIGH level is at 5V and LOW level is at 0V, and you need 3.5V output, if you generate a square wave which stays at the HIGH state for 70% of the cycle, or, in technical terms, has a duty cycle of 70%, and if its time period is very less (in milliseconds), then the node receiving this square wave will experience a voltage of 3.5V. With this application in mind, it shouldn’t be a surprise that the function used to perform PWM in Arduino is called analogWrite(). After all, we are essentially outputting analog voltage, instead of reading it.
Not all pins of Arduino support PWM. On the Uno board, the pins are specifically marked with a ~ symbol. For other boards, please refer to the datasheet of the board.
As can be seen from the above picture, only pins 3,5,6,9,10 and 11 can support PWM. The frequency of the square wave is 490 Hz (about 2 ms time period) on all pins except 5 and 6, on which it is 980 Hz (about 1s time period).
We will consider the LED brightening followed by dimming example. We will connect an LED to a PWM pin, and keep increasing the duty cycle on that pin, thereby increasing the voltage on that pin. Thus, the LED will keep getting brighter, till the max duty cycle (100) is reached.
Now, note that an 8-bit number is used to represent the duty cycle. Thus, the duty cycle can vary from 0 to 255. Thus, the value of 255 corresponds to duty cycle of 100%. 127 represents ~50% duty cycle, and so on.
The syntax for analogWrite is −
analogWrite(pin_number, duty_cycle)
The circuit diagram is shown below −
Note: The longer leg (+ve) of the LED is connected to pin 9, the shorter leg (-ve) is connected to GND via a resistor (the resistor value can be of the order of 100 Ohms. We chose 220 Ohms).
The code is given below −
int led_pwm_pin = 9;
void setup() {
   pinMode(led_pwm_pin, OUTPUT);
}
void loop() {
   //Brightening the LED
   for(int i=0; i < 255; i++){
      analogWrite(led_pwm_pin, i);
      delay(10);
   }
   //Dimming the LED
   for(int i=255; i>0; i--){
      analogWrite(led_pwm_pin, i);
      delay(10);
   }
}
As you can see from the code, we increase the duty cycle gradually from 0% to 100%, and then reduce it from 100% to 0%. You should see brightening followed by dimming on the LED.
How can I remove the ANSI escape sequences from a string in python?

You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re.sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]'.
For example,
import re
def escape_ansi(line):
    ansi_escape =re.compile(r'(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]')
    return ansi_escape.sub('', line)
print escape_ansi(line = '\t\u001b[0;35mSomeText\u001b[0m\u001b[0;36m172.18.0.2\u001b[0m')
                                 
 This will give the output:
 '\tSomeText                                  172.18.0.2'
Python program to sort a tuple by its float element

In this problem, our task to sort a tuple (consisting of float elements) using its float elements. Here we use built-in method sorted () and how can this be done using in place method of sorting.
Input:
tuple = [('AAA', '10.265'), ('BBB', '24.107'), ('CCC', '26.541'), ('DDD', '14.256'), ('EEE', '11.365')]
Output:
[('CCC', '26.541'), ('BBB', '24.107'), ('DDD', '14.256'), ('EEE', '11.365'), ('AAA', '10.265')]
Step 1: Given a list.
Step 2: To sort using sorted ().
Step 3: Sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
Step 4: Key(optional) is a function that would serve as a key or a basis of sort comparison.
Step 5: If Reverse (optional) is true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.
# Python code to sort a tuples by its float element
def tuplesort(A):
   return(sorted(A, key = lambda x: float(x[1]), reverse = True))
   # Driver Code
   A = [('Adwaita', '19.215'), ('Aadrika', '10.117'), ('Babai', '14.589'), ('Mona', '14.216'), ('Sanj', '8.365')]
print("Sort of Tuples By Its Float Number ::",tuplesort(A))
Sort of Tuples By Its Float Number :: [('Adwaita', '19.215'), ('Babai', '14.589'), ('Mona', '14.216'), ('Aadrika', '10.117'), ('Sanj', '8.365')]
Different Ways to Empty or Delete a Large File Content in Linux - GeeksforGeeks

11 May, 2021
In this article, we will learn different methods to empty or delete large file content in the Linux/Unix system by overwriting the existing target file with a newly created empty file.  Before we proceed with the given various ways, please make sure that the file we’re emptying or deleting content is not important or system file because once the content of the file is deleted by means of the given ways, recovery of the file is not possible. 
These are the following method to empty or delete a large file content in the Linux/Unix system. 
Using the truncate command.Using the echo command.Using the redirection ( >) operator.Using the true redirection ( : > ).Using /dev/null.
Using the truncate command.
Using the echo command.
Using the redirection ( >) operator.
Using the true redirection ( : > ).
Using /dev/null.
1. Empty or delete the contents of a large file using the truncate command in the Linux/Unix system. 
The truncate command is used to shrink or extend the size of a file to a specified size in the Linux system. It is also used to empty large file contents by using the -s option followed by 0 (zero) specified size. 
In the below example, we will empty the contents of a large file using the truncate command as shown below. 
truncate -s 0 file.txt
2. Empty or delete the contents of a large file using the echo command in the Linux/Unix system. 
Basically, the echo command is used to display lines of text. It is also used to empty the contents of a large file as shown below example. 
echo > file.txt
3. Empty or delete the contents of a large file using the > (redirection operator) in the Linux/Unix system.
To empty the contents of a large, we can just put > (redirection operator) before a file name as shown below example. 
>file.txt
4. Empty or delete the contents of a large file using the :> (true redirection) in the Linux/Unix system.
A symbol : is a shell-built command which is equivalent to a true command. To empty or delete the contents of a large, we can also use :> or true > followed by file name as shown below example. 
:>file.txt
5. Empty or delete the contents of a large file using the /dev/null device file in the Linux/Unix system.
In Linux/Unix system a /dev/null is a special device file that removes the contents of a file and outputs an empty file. In the below example, we will make empty the contents of a file. 
cat /dev/null > file.txt
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
GATE | GATE-CS-2014-(Set-3) | Question 65 - GeeksforGeeks

19 Nov, 2018
Consider the following combinational function block involving four Boolean variables x, y, a, b where x, a, b are inputs and y is the output.
f (x, y, a, b){   if (x is 1) y = a;   else y = b;}
Which one of the following digital logic blocks is the most suitable for implementing this function?(A) Full adder(B) Priority encoder(C) Multiplexer(D) Flip-flopAnswer: (C)Explanation: This function can be interpreted as having two inputs a, b and select signal x. Output y will depend on the select signal x.
Function will be like (ax+bx’)
Its implementation will be like
 
 
 
 
So ans is ( C) part.Quiz of this Question
GATE-CS-2014-(Set-3)
GATE-GATE-CS-2014-(Set-3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
How to implement isolation levels CS, RR, UR and RS in a DB2 program?

The isolation level defines the degree to which the DB2 data which is being accessed in the COBOL-DB2 program is isolated with another parallelly executing COBOL- DB2 program. There are 4 main types of Isolation levels in DB2.
Cursor stability (CS) - The cursor stability isolation level locks only the current row which the program is accessing. As soon as the program shifts to the next row, the lock in the previous row gets released. The cursor stability fetches only committed rows for the program to access. This is a default isolation level.
Read stability (RS) - This isolation level places a lock on all the rows which qualifies the SQL statement’s predicate (eg: WHERE clause). The lock is retained until the entire processing is completed.
Uncommitted read (UR) - The uncommitted read isolation level is used in the SQL statements meant for read-only purpose. There is no lock placed on a row/record and it fetches the committed as well as uncommitted rows (from the other programs/transactions).
Repeatable read (RR) - This isolation level is used when we need to retain the locks until a commit.
To define an isolation level for a COBOL-DB2 program, we need to use the corresponding parameter in the ISOLATION option of the BIND step. Below is the JCL step using which isolation level can be defined.
//BIND EXEC PGM=IKJEFT01
//STEPLIB DD DSN=DIS.TEST.LOADLIB,DISP=SHR
//SYSOUT DD SYSOUT=*
//SYSTSIN DD *
DSN SYSTEM(TB3)
BIND PLAN(PLANA) -
PKLIST(PACKA) -
ACQUIRE(ALLOCATE) -
ISOLATION (RS)
/*
In the above step, we have used the ISOLATION option with RS parameter, which corresponds to read stability. Similarly, we have parameter CS for cursor stability, RR for repeatable read and UR for uncommitted read.
How to extract images from PDF in Python? - GeeksforGeeks

03 Jan, 2021
In this article, the task is to extract images from PDF in Python. We will extract the images from PDF files and save them using PyMuPDF library. First, we would have to install the PyMuPDF library using Pillow.
pip install PyMuPDF Pillow
PyMuPDF is used to access PDF files. To extract images from PDF file, we need to follow the steps mentioned below-
Import necessary libraries
Specify the path of the file from which you want to extract images and open it
Iterate through all the pages of PDF and get all images objects present on every page
Use getImageList() method to get all image objects as a list of tuples
To get the image in bytes and along with the additional information about the image, use extractImage()
Note: To download the PDF file click here.
Below is the implementation.
Python3
# STEP 1# import librariesimport fitzimport iofrom PIL import Image  # STEP 2# file path you want to extract images fromfile = "/content/pdf_file.pdf"  # open the filepdf_file = fitz.open(file)  # STEP 3# iterate over PDF pagesfor page_index in range(len(pdf_file)):        # get the page itself    page = pdf_file[page_index]    image_list = page.getImageList()          # printing number of images found in this page    if image_list:        print(f"[+] Found a total of {len(image_list)} images in page {page_index}")    else:        print("[!] No images found on page", page_index)    for image_index, img in enumerate(page.getImageList(), start=1):                # get the XREF of the image        xref = img[0]                  # extract the image bytes        base_image = pdf_file.extractImage(xref)        image_bytes = base_image["image"]                  # get the image extension        image_ext = base_image["ext"]
Output:
Picked
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby()
Tryit Editor v3.7

Tryit: An HTML form styled with CSS
Batch Script - Left String

This is used to extract characters from the beginning of a string.
set str=Helloworld
echo.%str%
set str=%str:~0,5%
echo.%str%
The key thing to note about the above program is, ~0,5 is used to specify the characters which needs to be displayed. In this case, we are saying character 0 to 5 should be displayed.
The above command produces the following output.
Helloworld 
Hello

 Print
 Add Notes
 Bookmark this page
C# - Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.
You can declare the reference parameters using the ref keyword. The following example demonstrates this −
using System;

namespace CalculatorApplication {
   class NumberManipulator {
      public void swap(ref int x, ref int y) {
         int temp;

         temp = x; /* save the value of x */
         x = y;    /* put y into x */
         y = temp; /* put temp into y */
      }
      static void Main(string[] args) {
         NumberManipulator n = new NumberManipulator();
         
         /* local variable definition */
         int a = 100;
         int b = 200;

         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);

         /* calling a function to swap the values */
         n.swap(ref a, ref b);

         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);
 
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

It shows that the values have changed inside the swap function and this change reflects in the Main function.

    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Convert a Numeric Object to Character in R Programming - as.character() Function - GeeksforGeeks

16 Jun, 2020
as.character() function in R Language is used to convert a numeric object to character object.
Syntax: as.character(x)
Parameters:x: Numeric Object
Example 1:
# R program to convert a numeric object# to character object  # Calling as.character() functionas.character(1)as.character(2 + 3)as.character(1.5)
Output:
[1] "1"
[1] "5"
[1] "1.5"

Example 2:
# R program to convert a numeric object# to character object  # Creating a vectorx1 <- c(1, 2, 3, 4)x2 <- c(-1, 2, 1.5, -3)  # Calling as.character() functionas.character(x1)as.character(x2)
Output:
[1] "1" "2" "3" "4"
[1] "-1"  "2"   "1.5" "-3" 

R Math-Function
R String-Functions
R Vector-Function
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)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Remove rows with NA in one column of R DataFrame
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to match word boundaries using Java RegEx?

You can match the word boundaries using the meta character “\\b”.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\b";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of word boundaries: "+count);
   }
}
Enter a String
this is a sample text
Number of word boundaries: 10
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FirstLetterExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter sample text: ");
      String data = sc.nextLine();
      String regex = "\\b[a-zA-Z]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(data);
      System.out.println("First letter of each word from the given string: ");
      while(matcher.find()) {
         System.out.print(matcher.group()+" ");
      }
   }
}
Enter sample text:
National Intelligence Agency Research & Analysis Wing
First letter of each word from the given string:
N I A R A W
How to find prime factors of a number in R?

A prime number is the number that is only divisible by itself and one. These prime numbers can also divide other numbers hence they become a factor of those numbers. For example, 5 is a prime number and it also divides 20. To find the prime factors of a number, we can use primeFactors function of numbers package.
library(numbers)
primeFactors(100)
[1] 2 2 5 5
primeFactors(1000)
[1] 2 2 2 5 5 5

primeFactors(32547)
[1] 3 19 571
primeFactors(12354767)
[1] 17 726751

primeFactors(21457)
[1] 43 499
primeFactors(99)
[1] 3 3 11

primeFactors(365748)
[1] 2 2 3 29 1051
primeFactors(214687)
[1] 11 29 673

primeFactors(3587497)
[1] 3587497
primeFactors(35874)
[1] 2 3 3 1993

primeFactors(268713)
[1] 3 3 73 409
primeFactors(298473)
[1] 3 7 61 233

primeFactors(236571)
[1] 3 78857
primeFactors(98753)
[1] 17 37 157

primeFactors(547821)
[1] 3 3 60869
primeFactors(3652147)
[1] 23 97 1637

primeFactors(6985147)
[1] 13 17 31607
primeFactors(1236587469)
[1] 3 13 19 131 12739

primeFactors(65214693)
[1] 3 3 3 2415359
primeFactors(326579)
[1] 11 11 2699

primeFactors(1236574)
[1] 2 618287
primeFactors(1500)
[1] 2 2 3 5 5 5

primeFactors(1521)
[1] 3 3 13 13
primeFactors(36254761235)
[1] 5 7 11 113 833347

primeFactors(25896321)
[1] 3 3 3 11 17 23 223
primeFactors(25821469)
[1] 25821469

primeFactors(36952147)
[1] 2447 15101
primeFactors(23621576)
[1] 2 2 2 11 41 6547

primeFactors(6985314)
[1] 2 3 3 7 55439
primeFactors(87452)
[1] 2 2 21863

primeFactors(326987125)
[1] 5 5 5 2615897
primeFactors(36582314)
[1] 2 18291157

primeFactors(96325741)
[1] 131 735311
primeFactors(121)
[1] 11 11

primeFactors(109)
[1] 109
primeFactors(136)
[1] 2 2 2 17

primeFactors(136672)
[1] 2 2 2 2 2 4271
primeFactors(137)
[1] 137

primeFactors(368742)
[1] 2 3 11 37 151
primeFactors(36)
[1] 2 2 3 3

primeFactors(49)
[1] 7 7
primeFactors(80)
[1] 2 2 2 2 5

primeFactors(23687111)
[1] 7 1297 2609
primeFactors(11111)
[1] 41 271

primeFactors(22222222)
[1] 2 11 73 101 137
Java Program to get Milliseconds between two time instants

At first, create two time instants −
Instant time1 = Instant.now();
Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(50, ChronoUnit.SECONDS);
Use between() to get the milliseconds between two time instants −
Duration duration = Duration.ofSeconds(13);
Instant i = time1.plus(duration);
System.out.println("Milliseconds between two time instants = "+ChronoUnit.MILLIS.between(time1, time2));
 Live Demo
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class Demo {
   public static void main(String[] args) {
      Instant time1 = Instant.now();
      Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(50, ChronoUnit.SECONDS);
      Duration duration = Duration.ofSeconds(13);
      Instant i = time1.plus(duration);
      System.out.println("Milliseconds between two time instants =
         "+ChronoUnit.MILLIS.between(time1, time2));
   }
}
Milliseconds between two time instants = 18050000
Creating Clickable Tkinter labels

Tkinter Label widgets provide a way to display text and images in the Tkinter application window. We can configure the properties of the label widget by defining the attributes and properties in it. The Label widget can be converted into a clickable object by defining a function that contains some operation which can later be bound with a key.
In this example, we will create a Label widget. Clicking over the Label widget will redirect the user to a specified webpage. So, the label will act as a hyperlink.
#Import the required libraries
from tkinter import *
import webbrowser

#Create an instance of tkinter frame
win = Tk()
win.geometry("750x250")

#Define a callback function
def callback(url):
   webbrowser.open_new_tab(url)

#Create a Label to display the link
link = Label(win, text="www.tutorialspoint.com",font=('Helvetica', 15), fg="blue", cursor="hand2")
link.pack()
link.bind("<Button-1>", lambda e: callback("http://www.tutorialspoint.com"))
win.mainloop()
Running the above code will display a window containing a Label widget. Clicking over the label will redirect the user to the website "www.tutorialspoint.com"
Recursion - Sum Nested Array in JavaScript

We are required to write a JavaScript function that takes in a nested array of Numbers and returns the sum of all the numbers present in the array.
Let’s say the following is our nested array −
const arr = [2, 5, 7, [
   4, 5, 4, 7, [
       5, 7, 5
   ], 5
], 2];
Following is the code −
const arr = [2, 5, 7, [
   4, 5, 4, 7, [
      5, 7, 5
   ], 5
], 2];
const calculateSum = (arr, query) => {
   let count = 0;
   for(let i = 0; i < arr.length; i++){
      if(Array.isArray(arr[i])){
         count += calculateSum(arr[i], query);
         continue;
      };
      count += arr[i];
   };
   return count;
};
console.log(calculateSum(arr));
This will produce the following output in console −
58
Neo4j - Create Unique Constraint

In Neo4j database, CQL CREATE command always creates a new node or relationship which means even though you use the same values, it inserts a new row. As per our application requirements for some nodes or relationships, we have to avoid this duplication. For this, we should use some database constraints to create a rule on one or more properties of a node or relationship.
Like SQL, Neo4j database also supports UNIQUE constraint on node or relationship properties. UNIQUE constraint is used to avoid duplicate records and to enforce data integrity rule.
Neo4j CQL provides "CREATE CONSTRAINT" command to create unique constraints on node or relationship properties.
Following is the syntax to create a UNIQUE constraint in Neo4j.
MATCH (root {name: "Dhawan"}) 
CREATE UNIQUE (root)-[:LOVES]-(someone) 
RETURN someone 

Before proceeding with the example, create 4 nodes as shown below.
CREATE(Dhawan:player{id:001, name: "shikar Dhawan", YOB: 1995, POB: "Delhi"}) 
CREATE(Jonathan:player {id:002, name: "Jonathan Trott", YOB: 1981, POB: "CapeTown"}) 
CREATE(Sangakkara:player {id:003, name: "Kumar Sangakkara", YOB: 1977, POB: "Matale"}) 
CREATE(Rohit:player {id:004, name: "Rohit Sharma", YOB: 1987, POB: "Nagpur"}) 
CREATE(Virat:player {id:005, name: "Virat Kohli", YOB: 1988, POB: "Delhi"}) 
Following is a sample Cypher Query to create a UNIQUE constraint on the property id using Neo4j.
CREATE CONSTRAINT ON (n:player) ASSERT n.id IS UNIQUE
To execute the above query, carry out the following steps −
Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot.
Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot.
On executing, you will get the following result.
Now, try to add another node with a redundant id value. Here, we are trying to create a node with id 002.
CREATE (Jadeja:player {id:002, name: "Ravindra Jadeja", YOB: 1988, POB: "NavagamGhed"}) 
If you execute this query, you will get an error message as shown in the following screenshot.
 Print
 Add Notes
 Bookmark this page
How to use JavaScript to show a confirm message?

A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: Cancel.
If the user clicks on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button, then confirm() returns false.
You can try to run the following code to implement confirmation dialog box in JavaScript:
Live Demo
<html>
   <head>
      <script>
         <!--
            function getConfirmation(){
               var retVal = confirm("Do you want to continue ?");
               if( retVal == true ){
                  document.write ("User wants to continue!");
                  return true;
               }
               else{
                  document.write ("User does not want to continue!");
                  return false;
               }
            }
         //-->
      </script>
   </head>
   <body>
      <p>Click the following button to see the result: </p>
      <form>
         <input type="button" value="Click Me" onclick="getConfirmation();" />
      </form>
   </body>
</html>
Finding an element in a sub-element in Selenium Webdriver.

We can find an element in a sub-element with Selenium webdriver. First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css. Then we have to identify the sub-element with the findElements(By.xpath()) method.
We can identify the sub-element from the element, by localizing it with the element and then passing the expression (./child::*) as a parameter to the findElements(By.xpath())
element.findElements(By.xpath("./child::*"))
Let us identify the tagname of the sub-elements of element ul in below html code−
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class SubElement{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // identify element
      WebElement t=driver.findElement(By.xpath("//ul[@class='toc chapters']"));
      //identify sub-elements with ./child::* expression in xpath
      List c = t.findElements(By.xpath("./child::*"));
      // iterate sub-elements
      for ( WebElement i : c ) {
         //getTagName() to get tag of sub-elements
         System.out.println(i.getTagName());
      }
      driver.close();
   }
}
C++ Program to Implement Sieve of eratosthenes to Generate Prime Numbers Between Given Range

This is C++ program to implement Sieve of Eratosthenes to Generate Prime Numbers Between Given Range. In this method, an integer array with all elements initializes to zero.
It follows where each non-prime element’s index is marked as 1 inside the nested loops. The prime numbers are those whose index is marked as 0.
Begin
   Declare an array of size n and initialize it to zero
   Declare length, i, j
   Read length
   For i = 2 to n-1 do
      For j = i*i to n-1 do
         Arr[j-1]=1
      Done
   Done
   For i =1 to n do
      If(arr[i-1]==0)
         Print i
   Done
End
#include <iostream>
const int len = 30;
int main() {
   int arr[30] = {0};
   for (int i = 2; i < 30; i++) {
      for (int j = i * i; j < 30; j+=i) {
         arr[j - 1] = 1;
      }
   }
   for (int i = 1; i < 30; i++) {
      if (arr[i - 1] == 0)
         std::cout << i << "\t";
   }
}
1 2 3 5 7 11 13 17 19 23 29
C++ Multi-dimensional Arrays

C++ allows multidimensional arrays. Here is the general form of a multidimensional array declaration −
type name[size1][size2]...[sizeN];

For example, the following declaration creates a three dimensional 5 . 10 . 4 integer array −
int threedim[5][10][4];

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size x,y, you would write something as follows −
type arrayName [ x ][ y ];

Where type can be any valid C++ data type and arrayName will be a valid C++ identifier.
A two-dimensional array can be think as a table, which will have x number of rows and y number of columns. A 2-dimensional array a, which contains three rows and four columns can be shown as below −
Thus, every element in array a is identified  by an element name of the form a[ i ][ j ], where a is the name of the array, and i and j are the subscripts that uniquely identify each element in a.
Multidimensioned arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row have 4 columns.
int a[3][4] = {  
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

An element in 2-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −
int val = a[2][3];

The above statement will take 4th element from the 3rd row of the array. You can verify it in the above digram.
#include <iostream>
using namespace std;
 
int main () {
   // an array with 5 rows and 2 columns.
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
 
   // output each array element's value                      
   for ( int i = 0; i < 5; i++ )
      for ( int j = 0; j < 2; j++ ) {
      
         cout << "a[" << i << "][" << j << "]: ";
         cout << a[i][j]<< endl;
      }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
MySQL query to fetch date with year and month?

For year and month date fetching, you can use YEAR() and MONTH() function in MySQL. Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ShippingDate datetime
   );
Query OK, 0 rows affected (0.48 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(ShippingDate) values('2019-01-31');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(ShippingDate) values('2018-12-01');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(ShippingDate) values('2019-06-02');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(ShippingDate) values('2019-11-18');
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+-----------------------+
| Id | ShippingDate          |
+----+-----------------------+
| 1  | 2019-01-31 00 :00 :00 |
| 2  | 2018-12-01 00 :00 :00 |
| 3  | 2019-06-02 00 :00 :00 |
| 4  | 2019-11-18 00 :00 :00 |
+----+-----------------------+
4 rows in set (0.00 sec)
Following is the query to fetch date on the basis of a specific year and month −
mysql> select *from DemoTable where ( year(ShippingDate)='2019') and (month(ShippingDate)='06');
+----+-----------------------+
| Id | ShippingDate          |
+----+-----------------------+
| 3  | 2019-06-02 00 :00 :00 |
+----+-----------------------+
1 row in set (0.07 sec)
What is the purpose of private constructor in Java?

The private constructor is useful in case we want to restrict the object creation. For example, Singleton pattern can be implemented using a private constructor.
Live Demo
public class Tester {
   private static Tester instance;
   private Tester(){}
 
   public static Tester getInstance(){
      if(instance == null){
         instance = new Tester();
      }
      return instance;
   }
 
   public static void main(String[] args) {
      Tester tester = Tester.getInstance();
      Tester tester1 = Tester.getInstance();
      System.out.println(tester.equals(tester1));
   }  
}
It will print the output as
true
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider a software program that is artificially seeded with 100 faults. While testing this program, 159 faults are detected, out of which 75 faults are from those artificially seeded faults. Assuming that both real and seeded faults are of same nature and have same distribution, the estimated number of undetected real faults is ____________.(A) 28(B) 175(C) 56(D) 84Answer: (A)Explanation:
Total faults detected = 159
Real faults detected among all detected faults = 159 - 75 
                                               = 84
Since probability distribution is same, total number of real
faults is (100/75)*84 = 112

Undetected real faults = 112- 84 = 28 
Another Solution :
75% of faults are detected because 75 artificially seeded faults are detected out of 100.Given that the total faults detected = 159=> Real faults detected among all detected faults = 159 – 75= 84Since probability distribution is same, total number of real faults is (100/75)*84 = 112Therefore undetected real faults = 112-84 = 28.So, option (A) is correct one.
This solution is contributed by Nitika Bansal.Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2012 | Question 54
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2004 | Question 69