code-rag-bench/online-tutorials huggingface dataset:
Lodash _.transform() Method

27 Jul, 2021
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc. The _.transform() method is an alternative to _.reduce() method transforms object to a new accumulator object which is the result of running each of its own enumerable string keyed properties through iteratee with each invocation potentially mutating the accumulator object. A new object with the same prototype will be used if an accumulator is not provided. Syntax:  
_.transform(object, iteratee, accumulator)
Parameters: This method accepts three parameters as mentioned above and described below: 
object: It holds the object to iterate over.
iteratee: It is the function that the method invoked per iteration for every element.
accumulator: It holds the custom accumulator value.
Return Value: This method returns the accumulated value.Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. 
javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arrayvar object = [12, 13, 14];     // Using the _.transform() methodlet st_elem = _.transform(object,            function(result, n) {  result.push(n *= n);  return n % 2 == 0;}, []);  // Printing the outputconsole.log(st_elem);
Output:  
144, 169
Example 2:
javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arrayvar object = { 'p': 3, 'q': 6, 'r': 3 };     // Using the _.transform() methodlet st_elem = _.transform(object,    function(result, value, key) {  (result[value] || (result[value] = [])).push(key);}, {});  // Printing the outputconsole.log(st_elem);
Output: 
{ '3': ['p', 'r'], '6': ['q'] }
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
kapoorsagar226
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Shell Script to Split a String

20 Jun, 2021
Shell Scripting or Shell Programming is just like any other programming language. A shell is a special program that provides an interface between the user and the operating system.
In Linux/Unix the default shell used is bash and in windows, it is cmd(command prompt). We use the terminal to run a shell command. Shell scripts are saved with .sh file extension, and we can run the script with the help of the following command.
bash path/to/the/filename.sh
Example:
A simple shell program to print Hello Geeks!!.
#! /bin/bash

# echo is used to print
echo "Hello Geeks!!"
Here, #! /bin/bash is used to let know the Linux/Unix that it is a Bash Script and use the bash interpreter which resides in /bin to execute it.
Output:
First Shell Program
Let’s discuss how we can split a string take the following string for an example:
string  = “Lelouch,Akame,Kakashi,Wrath”
And we would like to split the string by “,” delimiter  so that we have :
name=”Lelouch”
name =”Akame”
name=”Kakashi”
name=”Wrath”
Approach 1: Using IFS (Input Field Separator).
IFS stands for Internal Field Separator or Input Field separator variable is used to separate a string into tokens.
Original String : 
string=”Lelouch,Akame,Kakashi,Wrath”
After Splitting :
name = Lelouch
name = Akame
name = Kakashi
name = Wrath
 String holds the input string value and IFS variable the delimiter on that we are going to separate the string. read -ra arr <<< “$string” convert the separated strings into an array, after that we are using for loop to traverse the array and print the value.“@” in arr subscript shows that we are going through the whole array.
Script :
#! /bin/bash

# Given string 
string="Lelouch,Akame,Kakashi,Wrath"

# Setting IFS (input field separator) value as ","
IFS=','

# Reading the split string into array
read -ra arr <<< "$string"

# Print each value of the array by using the loop
for val in "${arr[@]}";
do
  printf "name = $val\n"
done
To run the script use the following command :
bash path/to/the/filename.sh
Output:
Script Output
Approach 2: Without using the IFS
 Suppose input string is containing a particular word “anime” and we want to split the string on seeing “anime”
string = “anime Bleach anime Naruto anime Pokemon anime Monster anime Dororo”
Output :
Anime name is = Bleach
Anime name is = Naruto
Anime name is = Pokemon
Anime name is = Monster
Anime name is = Dororo
We can do this using Parameter Expansion.
Script :
#! /bin/bash

# Given string 
string="anime Bleach anime Naruto anime Pokemon anime Monster anime Dororo"

# Syntax to replace all occurrences of "anime" with " "
arr=(${string//"anime"/ })

# Print each value of the array by using the loop
for val in "${arr[@]}";
do

  printf "Anime name is = $val\n"
done
Output:
Script Output
simranarora5sos
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python calendar module | setfirstweekday() method

22 Oct, 2018
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions.
In Python, calendar.setfirstweekday(weekday) is a function provided in calendar module for simple text calendars.
setfirstweekday() method sets the weekday (0 is Monday, 6 is Sunday) to start each week. The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience.For example, to set the first weekday to Sunday.
Syntax: setfirstweekday()
Parameter: no parameter
Returns: None
Code #1:
# Python program to explain working of setfirstweekday() method  # importing calendar moduleimport calendar  # calling setfirstweekday() functionval = calendar.setfirstweekday(calendar.SUNDAY)  # returns Noneprint(val)
Output:
None
 Code #2: Explaining working of setfirstweekday() method with prmonth() method
# Python code to demonstrate the working of # setfirstweekday() with prmonth() method  # importing calendar module for calendar operations import calendar   # using prmonth() to print calendar of 1997 print ("The 4th month of 1997 is : ") calendar.prmonth(1997, 4, 2, 1)     # using setfirstweekday() to set first week day number calendar.setfirstweekday(4)   print ("\r")   # using firstweekday() to check the changed day print ("The new week day number is : ", end ="") print (calendar.firstweekday()) 
Output:
The 4th month of 1997 is : 
     April 1997
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
 
The new week day number is : 4
Python Calander-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Introduction To PYTHON
Python OOPs Concepts
Convert integer to string in Python
Remove border from IFrame using CSS

04 Dec, 2018
The Iframe is used to display a web page on the webpage. Remove border from iframe tag in the webpage could be done by using one of the CSS properties of the iframe tag called frameBorder and set its value to “0”.
Syntax:
frameBorder = "value";
Note: In the frameBorder property the B letter must be in capital otherwise it will not be recognized by the browser. The value taken by the frameBorder property are 0 and 1, where 0 is used to disable the border and 1 is used for enabling the border property. By default, the value is set to 1.
Example 1:
<!DOCTYPE html><html>    <head>        <title>Disable Iframe Border</title>        <style>            iframe {                height:200px;                width:400px;                background-color:lightgreen;            }            h1 {                color:green;            }            body {                text-align:center;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>iframe border property</h2>          <!-- We do not use border by specifying value 0 -->        <iframe src=# frameBorder="0"></iframe>     </body></html>                    
Output:
Example 2:
<!DOCTYPE html><html>    <head>        <title>Disable Iframe Border</title>        <style>            iframe {                height:200px;                width:400px;                background-color:green;            }            h1 {                color:green;            }            body {                text-align:center;            }        </style>    </head>    <body>        <h1>GeeksforGeeks</h1>        <h2>iframe border property</h2>          <!-- We use border by specifying a non-zero value -->        <iframe src=# frameBorder="1"></iframe>     </body></html>                    
Output:
CSS-Misc
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream anyMatch() in Java with examples

06 Dec, 2018
Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time.Syntax :
boolean anyMatch(Predicate<? super T> predicate)

Where, T is the type of the input to the predicate
and the function returns true if any elements of
the stream match the provided predicate, 
otherwise false.

Note : If the stream is empty then false is returned and the predicate is not evaluated.Below given are some examples to understand the implementation of the function in a better way.
Example 1 : anyMatch() function to check whether any element in list satisfy given condition.
// Java code for Stream anyMatch// (Predicate predicate) to check whether // any element of this stream match // the provided predicate.import java.util.*;  class GFG {          // Driver code    public static void main(String[] args) {              // Creating a list of Integers    List<Integer> list = Arrays.asList(3, 4, 6, 12, 20);       // Stream anyMatch(Predicate predicate)     boolean answer = list.stream().anyMatch(n                     -> (n * (n + 1)) / 4 == 5);          // Displaying the result    System.out.println(answer);}}
Output :
true

Example 2 : anyMatch() function to check whether any element in list having UpperCase at 1st index.
// Java code for  Stream anyMatch// (Predicate predicate) to check whether// any element of this stream match// the provided predicate.import java.util.stream.Stream;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a Stream of Strings        Stream<String> stream = Stream.of("Geeks", "fOr",                                          "GEEKSQUIZ", "GeeksforGeeks");          // Check if Character at 1st index is        // UpperCase in any string or not using        // Stream anyMatch(Predicate predicate)        boolean answer = stream.anyMatch(str -> Character.isUpperCase(str.charAt(1)));          // Displaying the result        System.out.println(answer);    }}
Output :
true

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Private bytes, Virtual bytes, Working set

31 Aug, 2021
In this article, we are going to understand private bytes, virtual bytes, and working sets.
Private Bytes :As a result of completely paging out the process’s private memory footprint to swap, Private Bytes summarizes the amount of RAM allocated to the process (though not necessarily used).
Process executables use Private Bytes only to request memory. It doesn’t mean that they are actually using the memory they have requested. Private Bytes are considered “private” since they (usually) exclude memory-mapped files (e.g. shared DLLs). They do exclude some memory, however, but not all memory allocated by those files. Neither the executable nor the linked library is able to determine when private bytes change. In addition, private bytes are not just restricted to physical memory. They can also be paged to disk or listed in the standby page list (not in use yet, but not yet paged either).
Private Bytes are the actual bytes allocated by your app, including pagefile usage. in general, private bytes are the overall committed memory. while the working set refers to the memory that is backed by RAM.
Private Bytes [Committed Memory] =  Private Bytes + Page File 
Virtual Bytes :Virtual Bytes are the total amount of virtual address space that a process occupies. Similar to the working set, this set includes memory-mapped files (shared DLLs), as well as data that has already been paged out and resides on a disk somewhere. When a system is under heavy load, the total virtual memory used by all processes is significantly greater than actually available memory.
virtual bytes=working set+private bytes+standby list.
Working Set :It refers to the amount of physical memory (RAM) the process uses. The measurement is less accurate since it also includes memory-mapped files and other resources, unlike private bytes. In recent years, Task Manager’s “Mem Usage” also reports the same value that has caused endless amounts of confusion. The Working Set runs on physical memory. However, the standby page list does not appear in the Working Set as it is still in memory, so when you minimize an application, the “Mem Usage” might suddenly drop.
It includes non-paged Private Bytes as well as memory-mapped files;
Under any process, By default Task Manager displays the Working Set:
and Process Explorer shows all Private Bytes, Working Set, and Virtual Bytes.
Blogathon-2021
Picked
Blogathon
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How do we use Python in script mode?

It is possible to execute Python script from command line. Python program can be written by any text editor (preferably a Python aware text editor) and saved with .py extension. To write basic Hello World program using IDLE, the Python IDE shipped with standard Python distribution, open the editor choosing File->New.
Type following lines and save as test.py
#!/usr/bin/python
 Print (“Hello World”)
Execute the script using following command line 
C:\users>python test.py
You can also run the script from Run Menu of IDLE file editor
Time and Space Complexity in Data Structure

Analysis of efficiency of an algorithm can be performed at two different stages, before implementation and after implementation, as
A priori analysis − This is defined as theoretical analysis of an algorithm. Efficiency of algorithm is measured by assuming that all other factors e.g. speed of processor, are constant and have no effect on implementation.
A posterior analysis − This is defined as empirical analysis of an algorithm. The chosen algorithm is implemented using programming language. Next the chosen algorithm is executed on target computer machine. In this analysis, actual statistics like running time and space needed are collected.
Algorithm analysis is dealt with the execution or running time of various operations involved. Running time of an operation can be defined as number of computer instructions executed per operation.
Suppose X is treated as an algorithm and N is treated as the size of input data, the time and space implemented by the Algorithm X are the two main factors which determine the efficiency of X.
Time Factor − The time is calculated or measured by counting the number of key operations such as comparisons in sorting algorithm.
Space Factor − The space is calculated or measured by counting the maximum memory space required by the algorithm.
The complexity of an algorithm f(N) provides the running time and / or storage space needed by the algorithm with respect of N as the size of input data.
Space complexity of an algorithm represents the amount of memory space needed the algorithm in its life cycle.
Space needed by an algorithm is equal to the sum of the following two components
A fixed part that is a space required to store certain data and variables (i.e. simple variables and constants, program size etc.), that are not dependent of the size of the problem.
A variable part is a space required by variables, whose size is totally dependent on the size of the problem. For example, recursion stack space, dynamic memory allocation etc.
Space complexity S(p) of any algorithm p is S(p) = A + Sp(I) Where A is treated as the fixed part and S(I) is treated as the variable part of the algorithm which depends on instance characteristic I. Following is a simple example that tries to explain the concept
SUM(P, Q)
Step 1 - START
Step 2 - R ← P + Q + 10
Step 3 - Stop
Here we have three variables P, Q and R and one constant. Hence S(p) = 1+3. Now space is dependent on data types of given constant types and variables and it will be multiplied accordingly.
Time Complexity of an algorithm is the representation of the amount of time required by the algorithm to execute to completion. Time requirements can be denoted or defined as a numerical function t(N), where t(N) can be measured as the number of steps, provided each step takes constant time.
For example, in case of addition of two n-bit integers, N steps are taken. Consequently, the total computational time is t(N) = c*n, where c is the time consumed for addition of two bits. Here, we observe that t(N) grows linearly as input size increases.
Python program to find all close matches of input string from a list

In this tutorial, we are going to find a solution to a problem. Let's see what the problem is. We have a list of strings and an element. We have to find strings from a list in which they must closely match to the given element. See the example.
Inputs
strings = ["Lion", "Li", "Tiger", "Tig"] element = "Lion"
Ouput
Lion Li
We can achieve this by using the startswith built-in method. See the steps to find the strings.
Initialize string list and a string.
Loop through the list.If string from list startswith element or element startswith the string from the list
If string from list startswith element or element startswith the string from the list
Print the string
## initializing the string list
strings = ["Lion", "Li", "Tiger", "Tig"]
element = "Lion"
for string in strings:
   ## checking for the condition mentioned above
   if string.startswith(element) or element.startswith(string):
      ## printing the eligible string
      print(string, end = " ")
print()
If you run the above program,
Lion Li
If you have any doubts regarding the program, please do mention them in the comment section.
What is the purpose and usage of “WHERE CURRENT OF” clause in a COBOL-DB2 program?

The “WHERE CURRENT OF” clause will place the exclusive lock on the row once the UPDATE statement is executed. The “WHERE CURRENT OF” clause will point to the most recently fetched row of the cursor.
We can update the rows in cursor using “WHERE CURRENT OF” in the following way.
CURSOR definition.
CURSOR definition.
EXEC SQL
DECLARE ORDER_CUR CURSOR FOR
SELECT ORDER_ID, TRANSACTION_ID FROM ORDERS
WHERE ORDER_DATE = ‘2020-07-28’
END-EXEC
OPEN cursor
OPEN cursor
EXEC SQL
OPEN ORDER_CUR
END-EXEC
FETCH cursor and Update row
FETCH cursor and Update row
SET WF-END-CURSOR-N TO TRUE
   PERFORM UNTIL WF-END-CURSOR-Y
   EXEC SQL
   FETCH ORDER_CUR INTO :ORDER-ID, :TRANSACTION-ID
END-EXEC
IF TRANSACTION-ID NOT = SPACES
   EXEC SQL
  UPDATE ORDERS SET IS_PAID = ‘YES’
WHERE CURRENT OF ORDER_CUR
END-EXEC
ELSE
CONTINUE
END-IF
END-PERFORM
Java NIO - CharSet

In Java for every character there is a well defined unicode code units which is internally handled by JVM.So Java NIO package defines an abstract class named as Charset which is mainly used for encoding and decoding of charset and UNICODE.
The supported Charset in java are given below.
US-ASCII − Seven bit ASCII characters.
US-ASCII − Seven bit ASCII characters.
ISO-8859-1 − ISO Latin alphabet.
ISO-8859-1 − ISO Latin alphabet.
UTF-8 − This is 8 bit UCS transformation format.
UTF-8 − This is 8 bit UCS transformation format.
UTF-16BE − This is 16 bit UCS transformation format with big endian byte order.
UTF-16BE − This is 16 bit UCS transformation format with big endian byte order.
UTF-16LE − This is 16 bit UCS transformation with little endian byte order.
UTF-16LE − This is 16 bit UCS transformation with little endian byte order.
UTF-16 − 16 bit UCS transformation format.
UTF-16 − 16 bit UCS transformation format.


forName() − This method creates a charset object for the given charset name.The name can be canonical or an alias.
forName() − This method creates a charset object for the given charset name.The name can be canonical or an alias.
displayName() − This method returns the canonical name of  given charset.
displayName() − This method returns the canonical name of  given charset.
canEncode() − This method checks whether the given charset supports encoding or not.
canEncode() − This method checks whether the given charset supports encoding or not.
decode() − This method decodes the string of a given charset into charbuffer of Unicode charset.
decode() − This method decodes the string of a given charset into charbuffer of Unicode charset.
encode() − This method encodes charbuffer of unicode charset into the byte buffer of given charset.
encode() − This method encodes charbuffer of unicode charset into the byte buffer of given charset.
Following example illustrate important methods of Charset class.
package com.java.nio;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
public class CharsetExample {
   public static void main(String[] args) {
      Charset charset = Charset.forName("US-ASCII");
      System.out.println(charset.displayName());
      System.out.println(charset.canEncode());
      String str= "Demo text for conversion.";
      //convert byte buffer in given charset to char buffer in unicode
      ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
      CharBuffer charBuffer = charset.decode(byteBuffer);
      //convert char buffer in unicode to byte buffer in given charset
      ByteBuffer newByteBuffer = charset.encode(charBuffer);
      while(newbb.hasRemaining()){
         char ch = (char) newByteBuffer.get();
         System.out.print(ch);
      }
      newByteBuffer.clear();
   }
}
US-ASCII
Demo text for conversion.


    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
Hive - Drop Table - GeeksforGeeks

04 Nov, 2020
Apache hive is a data warehousing tool that we use to manage our structure data on Hadoop. The tables in the hive are used for storing data in tabular format(structured). Hive is very much capable such that it can query petabytes of records stored inside the hive table.
DROP TABLE command in the hive is used to drop a table inside the hive. Hive will remove all of its data and metadata from the hive meta-store. The hive DROP TABLE statement comes with a PURGE option.  In case if the PURGE option is mentioned the data will be completely lost and cannot be recovered later but if not mentioned then data will move to .Trash/current directory. 
Syntax:
DROP TABLE [IF EXISTS] table_name [PURGE];

Example:
To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system.
Step 1: Start all your Hadoop Daemon
start-dfs.sh                    # this will start namenode, datanode and secondary namenode

start-yarn.sh                   # this will start node manager and resource manager  

jps                             # To check running daemons

Step 2: Launch Hive
hive

Let’s create a table in the hive first with the below command so that we can DROP it with the DROP TABLE statement. In our example, we are not specifying any database name so hive will use its default database.
Command:
CREATE TABLE data (
Name STRING,
ContactNo BIGINT)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ',';

We have successfully created a data table in the default database of the hive. Below is the command to check
Syntax:
SHOW TABLES IN <database-name>;

Command:
show tables in default;

DROP TABLE in Hive
With the help of the below command, all the content of the data table will be removed permanently because I have used the PURGE option with the DROP TABLE command.
Command:
DROP TABLE IF EXISTS data PURGE;

The table is successfully dropped.
Apache-Hive
Hadoop
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hadoop MapReduce - Data Flow
Hadoop - Pros and Cons
Hive - Alter Table
Hadoop - Schedulers and Types of Schedulers
Import and Export Data using SQOOP
How to Create Table in Hive?
MapReduce - Combiners
Top 10 Hadoop Analytics Tools For Big Data
MapReduce - Understanding With Real-Life Example
How MapReduce completes a task?
Python VLC MediaPlayer – Setting Volume - GeeksforGeeks

11 Apr, 2022
In this article we will see how we can set volume of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediaPlayer object is the basic object in vlc module for playing the video. VLC offer us to change the volume of the media, it can be set in the form of percentage i.e 0 means mute and 100 means maximum sound.
In order to do this we will use audio_set_volume method with the MediaPlayer object 
Syntax : media_player.audio_set_volume(n) 
Argument : It takes integer as argument 
Return : It returns if the volume was set, -1 if it was out of range
Below is the implementation 
Python3
# importing vlc moduleimport vlc # importing time moduleimport time  # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("death_note.mkv") # setting media to the media playermedia_player.set_media(media) # setting video scalemedia_player.video_set_scale(0.6)  # setting volumemedia_player.audio_set_volume(50) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output :  Another example Below is the implementation 
Python3
# importing vlc moduleimport vlc # importing time moduleimport time # creating vlc media player objectmedia_player = vlc.MediaPlayer() # media objectmedia = vlc.Media("1mp4.mkv") # setting media to the media playermedia_player.set_media(media)  # setting volumemedia_player.audio_set_volume(70)  # setting video scalemedia_player.video_set_scale(0.6) # start playing videomedia_player.play() # wait so the video can be played for 5 seconds# irrespective for length of videotime.sleep(5)
Output : 
simranarora5sos
Python vlc-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
PyQt5 - Getting the text of selected item in ComboBox - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can get the text i.e content of current item selected in the combo box, in order to do this we will use the currentText method.
Syntax : combo_box.currentText()
Argument : It takes no argument
Return : It return string
Steps for implementation –
1. Create a combo box2. Add items to combo box3. Create push button4. Add action to the push button5. Create label to show count5. Inside the action get the content of current item selected in combo box with the help of currentText method and store it in variable6. Show the content variable in label with the help of setText method
Below is the implementation –
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # creating push button         button = QPushButton("Show content ", self)          print(self.combo_box.count())          # adding action to button        button.pressed.connect(self.find)          # creating label to         self.label = QLabel(self)          # setting geometry of the label        self.label.setGeometry(200, 200, 200, 30)      def find(self):          # finding the content of current item in combo box        content = self.combo_box.currentText()          # showing content on the screen though label        self.label.setText("Content : " + content)  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
sum() function in Python
isupper(), islower(), lower(), upper() in Python and their applications
How to drop one or multiple columns in Pandas Dataframe
PyQt5 QComboBox - Setting mouse tracking - GeeksforGeeks

10 May, 2020
In this article we will see how we can set mouse tracking to the combo box, combo box receive signal about the mouse when any button is pressed but after mouse tracking it will receive all the signals about the mouse even if any button is not pressed. By default this property is False.
In order to turn on the mouse tracking we use setMouseTracking method
Syntax : combo_box.setMouseTracking(bool)
Argument : It takes bool as argument
Return : It returns None
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):        # creating a check-able combo box object        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 100, 30)          # geek list        geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # setting mouse tracking        self.combo_box.setMouseTracking(True)          # setting stylesheet of the combo box        self.combo_box.setStyleSheet("border : 1px solid red;")            # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
Read a file line by line in Python
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Offset-Fetch in MS SQL Server - GeeksforGeeks

29 Jul, 2020
Suppose a table has 30 rows. A user wants to extract list of last 10 rows and skip topmost rows. To make job easier, the offset-fetch clause is used in the query.
Syntax :
order by column_list[ASC|DESC]
Offset offset_row count{ROW|ROWS}
Fetch{FIRST|NEXT} fetch row_count {ROW|ROWS} only

Analysis of Syntax :
Order by clause is mandatory to use alongside offset-fetch clause otherwise it results in an error. ASC arranges rows from ascending to descending order while DESC arranges rows from descending to ascending order.
Offset skips number of rows specified in a table.
Fetch returns number of rows after offset clause is being used. It returns specified number of rows.
FIRST returns number of rows at start of table after offset is while NEXT returns consecutive rows after first set of rows.
Example –
If the user wants to skip first two rows and return rest of them, query is given as –
select name, rollnumber, course
from student 
order by rollnumber ASC
offset 2 ROWS
Output –
Offset skips number of rows specified in query while order by ASC arranges rows from ascending to descending order. If a user wants to skip first 6 rows and fetch the next ones, query is given as –
select name, rollnumber, course 
from student
order by roll number ASC
offset 6 ROWS
fetch FIRST 2 ROWS ONLY
Output –
Offset clause skips all rows specified in table while Fetch clause returns first two rows after offset clause. In the fetch clause, FIRST and NEXT can be used according to user’s requirements. Offset clause is mandatory to use while fetch is optional for use in queries.
DBMS-SQL
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
Introduction of B-Tree
SQL Trigger | Student Database
CTE in SQL
Difference between Clustered and Non-clustered index
How to find Nth highest salary from a table
SQL Interview Questions
SQL | ALTER (RENAME)
SQL Trigger | Student Database
CTE in SQL
How to multiple a matrix rows in R with a vector?

When we multiple a matrix with a vector in R, the multiplication is done by column but if we want to do it with rows then we can use transpose function. We can multiply the transpose of the matrix with the vector and then take the transpose of that multiplication this will result in the multiplication by rows.
Consider the below matrix −
> M1<-matrix(1:25,nrow=5)
> M1
   [,1] [,2] [,3] [,4] [,5]
[1,] 1    6   11   16    21
[2,] 2    7   12   17    22
[3,] 3    8   13   18    23
[4,] 4    9   14   19    24
[5,] 5   10   15   20    25
> V1<-1:5
Simple multiplication −
> M1*V1
   [,1] [,2] [,3] [,4] [,5]
[1,] 1    6   11   16   21
[2,] 4   14   24   34   44
[3,] 9   24   39   54   69
[4,] 16  36   56   76   96
[5,] 25  50   75  100  125
Row-wise Multiplication −
> t(t(M1)*V1)
   [,1] [,2] [,3] [,4] [,5]
[1,] 1   12   33   64  105
[2,] 2   14   36   68  110
[3,] 3   16   39   72  115
[4,] 4   18   42   76  120
[5,] 5   20   45   80  125
Let’s have a look at one more example −
> M2<-matrix(sample(1:100,25),nrow=5)
> M2
      [,1] [,2] [,3] [,4] [,5]
[1,]   72    5   36   11   76
[2,]   61   38   17   73   25
[3,]   96    9   62   79   64
[4,]   77   53   80   78   50
[5,]   81   15   21   43   23
> V2<-sample(1:100,5)
> V2
[1] 28 20 1 68 86
> t(t(M2)*V2)
[,1] [,2] [,3] [,4] [,5]
[1,] 2016 100 36 748 6536
[2,] 1708 760 17 4964 2150
[3,] 2688 180 62 5372 5504
[4,] 2156 1060 80 5304 4300
[5,] 2268 300 21 2924 1978
How to push new items to an array inside of an object in MongoDB?

You can use $elemMatch operator for this. Let us first create a collection with documents −
> db.pushNewItemsDemo.insertOne(
   {
      "_id" :1,
      "StudentScore" : 56,
      "StudentOtherDetails" : [
         {
            "StudentName" : "John",
            "StudentFriendName" : [
               "Bob",
               "Carol"
            ]
         },
         {
            "StudentName" : "David",
            "StudentFriendName" : [
               "Mike",
               "Sam"
            ]      
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 1 }
Following is the query to display all documents from a collection with the help of find() method −
> db.pushNewItemsDemo.find();
This will produce the following output −
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] }
Following is the query to push new items to an array inside of an object −
>db.pushNewItemsDemo.update({"_id":1,"StudentOtherDetails":{"$elemMatch":{"StudentName":"David"}}},
   {"$push":{"StudentOtherDetails.$.StudentFriendName":"James"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents once again −
> db.pushNewItemsDemo.find();
This will produce the following output −
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam", "James" ] } ] }
Extract only characters from given string in Python

A piece of data may contain letters, numbers as well as special characters. If we are interested in extracting only the letters form this string of data, then we can use various options available in python.
The isalpha function will check if the given character is an alphabet or not. We will use this inside a for loop which will fetch each character from the given string and check if it is an alphabet. The join method will capture only the valid characters into the result.
 Live Demo
stringA = "Qwer34^&t%y"

# Given string
print("Given string : ", stringA)

# Find characters
res = ""
for i in stringA:
if i.isalpha():
res = "".join([res, i])

# Result
print("Result: ", res)
Running the above code gives us the following result −
Given string : Qwer34^&t%y
Result: Qwerty
We can leverage the regular expression module and use the function findall giving the parameter value which represents only the characters.
 Live Demo
import re
stringA = "Qwer34^&t%y"

# Given string
print("Given string : ", stringA)

# Find characters
res = "".join(re.findall("[a-zA-Z]+", stringA))

# Result
print("Result: ", res)
Running the above code gives us the following result −
Given string : Qwer34^&t%y
Result: Qwerty
Use of bool in C - GeeksforGeeks

14 Oct, 2020
Prerequisite: Bool Data Type in C++The C99 standard for C language supports bool variables. Unlike C++, where no header file is needed to use bool, a header file “stdbool.h” must be included to use bool in C. If we save the below program as .c, it will not compile, but if we save it as .cpp, it will work fine.  
C
int main(){  bool arr[2] = {true, false};  return 0;}
If we include the header file “stdbool.h” in the above program, it will work fine as a C program. 
C
#include <stdbool.h>int main(){    bool arr[2] = { true, false };    return 0;}
There is one more way to do it using enum function in C language. You can create a bool using enum. One enum will be created as bool, then put the elements of enum as True and False respectively. The false will be at the first position, so it will hold 0, and true will be at the second position, so it will get value 1.
Below is the implementation of the above idea:
C
// C implementation of the above idea#include <stdio.h>  // Declaration of enumtypedef enum { F, T } boolean;  int main(){    boolean bool1, bool2;    bool1 = F;      if (bool1 == F) {        printf("bool1 is false\n");    }    else {        printf("bool1 is true\n");    }    bool2 = 2;    if (bool2 == F) {        printf("bool2 is false\n");    }    else {        printf("bool2 is true\n");    }}
bool1 is false
bool2 is true

pulkitagarwal03pulkit
C-Data Types
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
Core Dump (Segmentation fault) in C/C++
fork() in C
Command line arguments in C/C++
Function Pointer in C
Substring in C++
Structures in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
How to use regular expressions in xpath in Selenium with python?

We can identify elements by matching its attributes partially with the help of regular expressions. In xpath, there are multiple methods to achieve this. They are listed below −
Using the contains() method. This means the string contains our given text.
Using the contains() method. This means the string contains our given text.
Syntax −
driver.find_element_by_xpath("//input[contains(@name,'sel')]")
It will search the input tag which contains the 'name' attribute containing 'sel' text.
Using the starts-with() method. This means the string starts with our given text.
Using the starts-with() method. This means the string starts with our given text.
Syntax −
driver.find_element_by_xpath("//input[starts-with (@name,'Tut')]")
It will search the input tag which contains the 'name' attribute starting with 'Tut' text.
Using the ends-with() method. This means the string ends with our given text.
Using the ends-with() method. This means the string ends with our given text.
Syntax
driver.find_element_by_xpath("//input[ends-with (@name,'nium')]")
It will search the input tag which contains the 'name' attribute ending with 'nium' text.
Code Implementation with contains()
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of contains() in xpath
driver.find_element_by_xpath("//input[contains(@id,'sc-i')]").
send_keys("Selenium")
#to close the browser
driver.close()
Code Implementation with starts-with()
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of starts-with() in xpath
driver.find_element_by_xpath("//input[starts-with(@id,'gsc')]").
send_keys("Selenium")
#to close the browser
driver.close()
Code Implementation with ends-with()
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
# identifying the edit box with the help of ends-with() in xpath
driver.find_element_by_xpath("//input[ends-with(@id,'id1')]").
send_keys("Selenium")
#to close the browser
driver.close()
How can we read a JSON file in Java?

The JSON is one of the widely used data-interchange formats and is a lightweight and language independent. The json.simple is a lightweight JSON processing library that can be used to read and write JSON files and it can be used to encode or decode JSON text and fully compliant with JSON specification (RFC4627). In order to read a JSON file, we need to download the json-simple.jar file and set the path to execute it.
import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      try {
         Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
         JSONObject jsonObject = (JSONObject)obj;
         String name = (String)jsonObject.get("Name");
         String course = (String)jsonObject.get("Course");
         JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
         System.out.println("Name: " + name);
         System.out.println("Course: " + course);
         System.out.println("Subjects:");
         Iterator iterator = subjects.iterator();
         while (iterator.hasNext()) {
            System.out.println(iterator.next());
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML
Matplotlib.axes.Axes.set_visible() in Python

30 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_visible() function in axes module of matplotlib library is used to set the artist’s visibility.
Syntax: Axes.set_visible(self, b)
Parameters: This method accepts only one parameters.
b: This parameter is the boolean value.
Returns: This method does not return any value.
Below examples illustrate the matplotlib.axes.Axes.set_visible() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltfrom mpl_toolkits.axisartist.axislines import Subplot   fig = plt.figure()   ax = Subplot(fig, 111)fig.add_subplot(ax)   ax.axis["left"].set_visible(False)ax.axis["top"].set_visible(False)   fig.suptitle('matplotlib.axes.Axes.set_visible()\ function Example\n', fontweight ="bold")  plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np        X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y)    fig, ax = plt.subplots()ax.quiver(X, Y, U, V)w = ax.get_xaxis()w.set_visible(False)   fig.suptitle('matplotlib.axes.Axes.set_visible() \function Example\n', fontweight ="bold")  plt.show()
Output:
Matplotlib axes-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.