code-rag-bench/online-tutorials huggingface dataset:
How to read a text file in Python?

A text file is the file containing simple text. Python provides inbuilt functions to read, create and write text files. We will discuss how to read a text file in Python.
There are three ways to read a text file in Python −
read() − This method reads the entire file and returns a single string containing all the contents of the file .
read() − This method reads the entire file and returns a single string containing all the contents of the file .
readline() − This method reads a single line from the file and returns it as string.
readline() − This method reads a single line from the file and returns it as string.
readlines() − This method reads all the lines and return them as the list of strings.
readlines() − This method reads all the lines and return them as the list of strings.
Let there be a text file named “myfile.txt”. We need to open the file in read mode. The read mode is specified by “r”. The file can be opened using open(). The two parameters passed are the name of the file and the mode in which the file needs to be opened.
file=open("myfile.txt","r")

print("read function: ")
print(file.read())
print()

file.seek(0) #Take the cursor back to begining of the file since the read() takes the cursor to the end of file

print("readline function:")
print(file.readline())
print()

file.seek(0) #Take the cursor back to beginning of file

print("readlines function:")
print(file.readlines())
file.close()
read function:
This is an article on reading text files in Python.
Python has inbuilt functions to read a text file.
We can read files in three different ways.
Create a text file which you will read later.

readline function:
This is an article on reading text files in Python.

readlines function:
['This is an article on reading text files in Python.\n', 'Python has
inbuilt functions to read a text file.\n', 'We can read files in three
different ways.\n', 'Create a text file which you will read later.']
As clear from the output −
The read function() reads and returns the whole file.
The readline() function reads and returns only one line.
The readlines() function reads and returns all the lines as list of the strings.
How Ternary operator in PowerShell Works?

The ternary operator in PowerShell was introduced with the PowerShell version7.0. The ternary operator has ‘?’ (question mark) symbol and its syntax is,
[Condition] ? (output if True) : (output if false)
The left side of the ternary operator is condition and the right side is output based on the condition statement. The output from the condition is in the forms of the Boolean, if the condition is true, the True block will be executed and if the condition is false, the False block will be executed. For example,
$a = 5; $b = 6
($a -gt $b) ? "True" : "false"
false

As you can see the value 5 is less than 6 so the above condition is false and the second block is executed. You can also modify the statement like,
($a -gt $b) ? ("$a is greater than $b") : ("$a is less than $b")
5 is less than 6

You can see that the amount of code is reduced by just one line and if we have written the same with if/else condition then,
$a = 5; $b = 6

if($a -gt $b){"$a is greater than $b"}
else{"$b is greater than $a"}
So the use of the ternary operator seems simple. You can also use cmdlet on the left side of the operator which returns the Boolean value.
(Test-Connection google.com -Count 2 -Quiet) ? "Google.Com server is reachable" : "Google.Com server is unrechable"

Google.Com server is reachable
Try to make this ternary operator as simple as possible. It won’t work always if the right side part of the ternary operator is used for scripting purposes.
Powershell - Check File Existence

Test-Path cmdlet is used to check existence of a file.
In this example, we're having a file test.txt in D:\temp\test directory
Type the following command in PowerShell ISE Console
Test-Path D:\temp\test\test.txt
You can see following output in PowerShell console.
Test-Path D:\temp\test\test.txt
True

In this example, we're not having a file named test2.txt in D:\temp\test directory
Type the following command in PowerShell ISE Console
Test-Path D:\temp\test\test2.txt
You can see following output in PowerShell console.
Test-Path D:\temp\test\test2.txt
False


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Sort a multidimensional array by date element in PHP

07 Jan, 2020
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function. This function assigns new integral keys starting from zero to array elements.
Syntax:
boolean usort( $array, "function_name")
Parameters: This function accepts two parameters as shown in the above syntax and are described below:
$array: This parameter specifies the array which u want to sort.
function_name: This parameter specifies the name of a user-defined function which compares the values and sort the array specified by the parameter $array. This function returns an integer value based on the following conditions. If two argument are equal then it returns 0, If first argument is greater than second, it returns 1 and if first argument is smaller than second, it returns -1.
Return Value: This function returns Boolean type value. It returns TRUE in case of success and FALSE in case of failure.
We use strtotime to convert given time string to a timestamp object. Once we have timestamps, we subtract them to decide greater.
Program:
<?php  // Declare a multidimensional array// and initialize it$array = Array (    Array (        "gfg" => "GFG_1",        "datetime" => "2019-02-22 11:29:45",        ),    Array (        "gfg" => "GFG_2",        "datetime" => "2019-02-13 11:29:45",    ),    Array (        "gfg" => "GFG_3",        "datetime" => "2019-02-15 11:29:45",    ));  // Comparison functionfunction date_compare($element1, $element2) {    $datetime1 = strtotime($element1['datetime']);    $datetime2 = strtotime($element2['datetime']);    return $datetime1 - $datetime2;}   // Sort the array usort($array, 'date_compare');  // Print the arrayprint_r($array)  ?>
Array
(
    [0] => Array
        (
            [gfg] => GFG_2
            [datetime] => 2019-02-13 11:29:45
        )

    [1] => Array
        (
            [gfg] => GFG_3
            [datetime] => 2019-02-15 11:29:45
        )

    [2] => Array
        (
            [gfg] => GFG_1
            [datetime] => 2019-02-22 11:29:45
        )

)

Akanksha_Rai
date-time-program
PHP-date-time
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.isFunction() Method

10 Sep, 2020
The Lodash _.isFunction() Method checks whether the given value is a function object or not and returns the corresponding boolean value.
Syntax:
_.isFunction( value )

Parameters: This method accepts single parameter as mentioned above and described below:
value: This parameter holds the value that to be checked for a function object.
Return Value: This method returns a Boolean value(Returns true if the given value is Function object number, else false).
Example 1: 
Javascript
// Defining Lodash variable const _ = require('lodash');   function Geeks(){    var a="gfg";}// Checking for Functionconsole.log("The Value is Function : "        + _.isFunction(Geeks));
Output:
The Value is Function : true

Example 2: 
Javascript
// Defining Lodash variable const _ = require('lodash');   // Checking for Functionconsole.log("The Value is Function : "        + _.isFunction("Function"));
Output:
The Value is Function : false 

Example 3: For _ object, it returns true.
Javascript
// Defining Lodash variable const _ = require('lodash');   // Checking for Functionconsole.log("The Value is Function : "        + _.isFunction(_));
Output:
The Value is Function : true

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shellphish Tool in Kali Linux - GeeksforGeeks

15 Mar, 2021
Shellphish is a powerful open-source tool Phishing Tool. It became very popular nowadays that is used to do phishing attacks on Target. Shellphish is easier than Social Engineering Toolkit.  It contains some templates generated by another tool called SocialFish and offers phishing templates webpages for 18 popular sites such as Facebook, Instagram, Google, Snapchat, Github, Yahoo, Protonmail, Spotify, Netflix, LinkedIn, WordPress, Origin, Steam, Microsoft, etc. It also provides an option to use a custom template if someone wants. This tool makes it easy to perform a phishing attack. Using this tool you can perform phishing in (wide area network). This tool can be used to get credentials such as id, password.
Uses of Shellphish:
Shellphish tool can create phishing pages of most popular social networking sites like
Facebook
Instagram
Yahoo
Twitter
Netflix
Step 1: Open your Terminal on Kali Linux and move to Desktop
cd Desktop 
Step 2: Create a new Directory i.e shellphish
mkdir shellphish
Step 3: On Terminal itself download and install shellphish in the above directory by the following command
git clone https://github.com/suljot/shellphish.git
Step 4: Finally to execute shellphish tool-type following command
./shellphish.sh
Congratulations you have installed shellphish tool in your Kali Linux machine. You can see you are getting multiple options here, for Instagram you are getting [01], for Facebook you are getting [02], and for multiple other sites you are getting other options.
For example, let’s type 1 and press enter .now you can see shellphish has created the URL https://8b992b4bc918.ngrok.io. Send this link to the target person through any medium (email, WhatsApp, text message). Once your target open this link and fill the respective phishing form and I’d and password will be shown below {waiting IPs and Credentials}
Once the victim opens the link, they will be able to see a page that will look exactly like the Instagram login page, and this will earn their trust. Once they have entered the credentials, HACKED! You will be able to see their username and password on your Kali Linux terminal. The victim will be now redirected to the original Instagram page.
Kali-Linux
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Create and Setup Spring Boot Project in Eclipse IDE?
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
Python-Quizzes | Python List Quiz | Question 4 - GeeksforGeeks

17 Sep, 2020
Question 4: Find the output of the following program:
def addToList(listcontainer):     listcontainer += [10]   mylistContainer = [10, 20, 30, 40] addToList(mylistContainer) print len(mylistContainer) 
(A) 4(B) 5(C) 6(D) 10Answer: (B)Explanation: In Python, everything is a reference, and references are passed by value. Parameter passing in Python is the same as reference passing in Java. As a consequence, the function can modify the value referred by passed argument, i.e. the value of the variable in the caller’s scope can be changed. Here the task of the function “addToList” is to add an element 10 in the list, So this will increase the length of the list by 1. So the output of the program is 5.Quiz of this Question
Python-Quizzes
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python-Quizzes | Python Dictionary Quiz | Question 25
Python-Quizzes | Python Dictionary Quiz | Question 23
Python | Miscellaneous | Question 1
Python-Quizzes | Miscellaneous | Question 7
Python | Animated Banner showing 'GeeksForGeeks'
Python-Quizzes | Miscellaneous | Question 9
Why do people prefer Selenium with Python?
Output of Python Program - Dictionary (set 25)
Python-Quizzes | Miscellaneous | Question 10
Python-Quizzes | Miscellaneous | Question 8
File delete() method in Java with Examples - GeeksforGeeks

28 Jan, 2019
The delete() function is a part of File class in Java . This function deletes an existing file or directory. If the file is deleted then the function returns true else returns false
Function signature:
public boolean delete()
Syntax:
boolean var = file.delete();
Parameters: This method does not accept any parameter.
Return Type: The function returns boolean data type representing whether the new file is deleted or not.
Exception: This method throws Security Exception: if the write access to the file is denied.
Below programs illustrates the use of delete() function:
Example 1: The file “F:\\program.txt” is a existing file in F: Directory.
// Java program to demonstrate// delete() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          try {              // Get the file            File f = new File("F:\\program.txt");              // delete file            if (f.delete())                System.out.println("File deleted");            else                System.out.println("File was not deleted");        }        catch (Exception e) {            System.err.println(e);        }    }}
Output:
File deleted
Example 2: The file “F:\\program1.txt” does not exist
// Java program to demonstrate// delete() method of File Class  import java.io.*;  public class solution {    public static void main(String args[])    {          try {              // Get the file            File f = new File("F:\\program1.txt");              // delete file            if (f.delete())                System.out.println("File deleted");            else                System.out.println("File was not deleted");        }        catch (Exception e) {            System.err.println(e);        }    }}
Output:
File was not deleted
Note: The programs might not run in an online IDE. Please use an offline IDE and set the path of the file.
Java-File Class
java-file-handling
Java-Functions
Java-IO package
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
Java Program to Read a File to String
How to Replace a Element in Java ArrayList?
Java Program to Find Sum of Array Elements
How to Write Data into Excel Sheet using Java?
Removing last element from ArrayList in Java
Tic-Tac-Toe Game in Java
Java Program to Write an Array of Strings to the Output Console
How to Merge Two Pandas DataFrames on Index? - GeeksforGeeks

13 Jan, 2022
In this article, we will discuss how to merge two Pandas Dataframes on Index.
This method is used to join the dataframe based on index.
Syntax:
dataframe1.join(dataframe2)
Example:
Python3
# import pandas moduleimport pandas as pd # create student  dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4],                      'name': ['manoj', 'manoja', 'manoji', 'manij']},                     index=['one', 'two', 'three', 'four'])  # create marks  dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7],                      'marks': [98, 90, 78, 86, 78]},                     index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframesprint(data1.join(data2))
Output:
This will merge the two dataframes with matching indexes 
Syntax:
pandas.merge(dataframe1, dataframe2, left_index=True, right_index=True)
where,
dataframe1 is the first dataframe
dataframe2 is the second dataframe
left_index specifies the first dataframe index set to be true
right_index specifies the second dataframe index set to be true
Example:
Python3
# import pandas moduleimport pandas as pd # create student  dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4],                      'name': ['manoj', 'manoja', 'manoji', 'manij']},                     index=['one', 'two', 'three', 'four'])  # create marks  dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7],                      'marks': [98, 90, 78, 86, 78]},                     index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframes with mergeprint(pd.merge(data1, data2, left_index=True, right_index=True))
Output:
We can concatenate two dataframes by using concat() method by setting axis=1.
Syntax:
pandas.concat([daatframe1,dataframe2], axis=1)
Example:
Python3
# import pandas moduleimport pandas as pd # create student  dataframedata1 = pd.DataFrame({'id': [1, 2, 3, 4],                      'name': ['manoj', 'manoja', 'manoji', 'manij']},                     index=['one', 'two', 'three', 'four'])  # create marks  dataframedata2 = pd.DataFrame({'s_id': [1, 2, 3, 6, 7],                      'marks': [98, 90, 78, 86, 78]},                     index=['one', 'two', 'three', 'siz', 'seven']) # join two dataframes with concatprint(pd.concat([data1, data2], axis=1))
Output:
adnanirshad158
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
JavaScript | ArrayBuffer Object - GeeksforGeeks

26 Jun, 2018
An ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. The contents of an ArrayBuffer cannot be directly manipulated and can only be accessed through a DataView Object or one of the typed array objects. These Objects are used to read and write the contents of the buffer. More than one DataView or typed array objects can be added to one ArrayBuffer and any changes to one object can be easily seen by the other objects view.The following are the typed arrays:Float32Array, Float64Array, Int8Array, Int16Array, Int32Array, Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array.Syntax:
new ArrayBuffer(byteLength)
Parameters: It accepts one parameter i.e. bytelength which denotes the size, in bytes, of the array buffer to be created.Return value: It returns a new ArrayBuffer object of the specified size and the content is initialized to 0.
<script>      //Create a 16byte buffer    var buffer = new ArrayBuffer(16);      //Create a DataView referring to the buffer    var view1 = new DataView(buffer);      //Create a Int8Array view referring to the buffer    var view2 = new Int8Array(buffer);      //Put value of 32bits    view1.setInt32(0, 0x76543210);      //prints the 32bit value    document.write(view1.getInt32(0).toString(16) + "<br>");           //prints only 8bit value     document.write(view1.getInt8(0).toString(16) + "<br>");     document.write(view2[0].toString(16));  </script>                                       
Output:
76543210
76
76
Properties :
ArrayBuffer.byteLength: The byteLength property returns the length of the buffer in bytes.
ArrayBuffer.prototype: This property allows to add properties to all ArrayBuffer objects.
Methods:
ArrayBuffer.isView(arg): If arg is one of the ArrayBuffer views (typed array objects or a DataView) then true is returned otherwise, false is returned.
ArrayBuffer.transfer(oldBuffer [, newByteLength]): The contents from the oldbuffer specified is either truncated or zero-extended by the specified newByteLength and is returned as a new ArrayBuffer.
Instance Methods:
ArrayBuffer.slice() and ArrayBuffer.prototype.slice(): A new ArrayBuffer is returned whose contents are a copy of this ArrayBuffer’s bytes from begin, inclusive, up to end, exclusive.
javascript-array
javascript-object
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
JavaScript | console.log() with Examples
How to read a local text file using JavaScript?
Node.js | fs.writeFileSync() Method
How to Use the JavaScript Fetch API to Get Data?
Getting Synchronized Map from Java HashMap - GeeksforGeeks

13 Jan, 2021
HashMap is a non synchronized collection class. If we want to perform thread-safe operations on it then we must have to synchronize it explicitly. In order to synchronize it explicitly the synchronizedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) map backed by the specified map.
// Get synchronized map using Collections.synchronizedMap()

Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap);
To iterate the synchronized map we use a synchronized block:
// Synchronized block
synchronized (synchrMap) {

      // Iterate synchronized map
      for (Map.Entry<Integer, String> entry : synchrMap.entrySet()) {

        // Print key : value
        System.out.println(entry.getKey() + " : " + entry.getValue());
        
      }
}
Implementation:
Java
// Java Program to demonstrate how // to get synchronized map from HashMap  import java.util.*;  class GFG {    public static void main(String[] args)    {          // New HashMap        HashMap<Integer, String> hmap = new HashMap<>();          // Add element to map        hmap.put(1, "Akshay");        hmap.put(2, "Bina");        hmap.put(3, "Chintu");          // Get synchronized map using        // Collections.synchronizedMap()        Map<Integer, String> synchrMap = Collections.synchronizedMap(hmap);          System.out.println("Synchronized Map : ");          // Synchronized block        synchronized (synchrMap)        {              // Iterate synchronized map            for (Map.Entry<Integer, String> entry :                 synchrMap.entrySet()) {                  // Print key : value                System.out.println(entry.getKey() + " : "                                   + entry.getValue());            }        }    }}
Synchronized Map : 
1 : Akshay
2 : Bina
3 : Chintu
Java-Collections
Java-HashMap
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
PyQt5 QCalendarWidget - Setting date Range - GeeksforGeeks

18 Aug, 2021
In this article we will see how we can set the date range to the QCalendarWidget. The date range of QCalendarWidget restricts the user selection, i.e. the user can only select dates within the specified date range. Rest of the dates get disabled. 
In order to do this we will use setDateRange method with the QCalendarWidget object.Syntax : calendar.setDateRange(lower_date, upper_date)Argument : It takes two QDate object as argumentReturn : It return None  
Below is the implementation  
Python3
# 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 components    def UiComponents(self):         # creating a QCalendarWidget object        calendar = QCalendarWidget(self)         # setting geometry to the calendar        calendar.setGeometry(10, 10, 400, 250)         # lower bound date        l_date = QDate(2020, 6, 5)         # upper bound date        u_date = QDate(2020, 6, 15)         # setting date range        calendar.setDateRange(l_date, u_date)   # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
clintra
Python PyQt-QCalendarWidget
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
Python File flush() Method

Python file method flush() flushes the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.
Python automatically flushes the files when closing them. But you may want to flush the data before closing any file.
Following is the syntax for flush() method −
fileObject.flush(); 

NA
NA
This method does not return any value.
The following example shows the usage of flush() method.
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Here it does nothing, but you can call it with read operation.
fo.flush()

# Close opend file
fo.close()
When we run above program, it produces following result −
Name of the file:  foo.txt


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
JavaScript Number.MAX_VALUE & Number.MIN_VALUE with Examples

The JavaScript Number.MAX_VALUE & Number.MIN_VALUE property represents the maximum and minimum numeric value representation possible in JavaScript respectively.
Following is the code for the JavaScript Number.MAX_VALUE & Number.MIN_VALUE property −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample{
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript Number.MAX_VALUE & Number.MIN_VALUE</h1>
<div class="sample"></div>
<div style="font-weight: bold; color: black;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above to get the maximum and minimum number value possible in JavaScript
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   document.querySelector(".Btn").addEventListener("click", () => {
      sampleEle.innerHTML = 'Number.MAX_VALUE = ' + Number.MAX_VALUE + '<br>';
      sampleEle.innerHTML += 'Number.MIN_VALUE = ' + Number.MIN_VALUE + '<br>';
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
PHP - Local Variables

Scope can be defined as the range of availability a variable has to the program in which it is declared. PHP variables can be one of four scope types −
Local variables
Function parameters
Global variables
Static variables.
A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function −
<?php
   $x = 4;
   
   function assignx () { 
      $x = 0;
      print "\$x inside function is $x. <br />";
   }
   
   assignx();
   print "\$x outside of function is $x. <br />";
?>
This will produce the following result −
$x inside function is 0. 
$x outside of function is 4. 


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
MongoDB aggregation group and remove duplicate array values?

Use MongoDB aggregate for this and within that, use $group. Let us create a collection with documents −
> db.demo649.insertOne(
...    { "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo649.insertOne({ "_id" :102, "Names" : [ "John", "Robert" ], "CountryName" : "UK"});
{ "acknowledged" : true, "insertedId" : 102 }
Display all documents from a collection with the help of find() method −
> db.demo649.find();
This will produce the following output −
{ "_id" : 101, "Names" : [ "John", "Bob", "Bob", "Robert" ], "CountryName" : "US" }
{ "_id" : 102, "Names" : [ "John", "Robert" ], "CountryName" : "UK" }
Following is the query for aggregation group −
> db.demo649.aggregate(
...    { $unwind : "$Names"},
...    { $group : { _id : "$_id" , Names : { $addToSet : "$Names" } ,
...    CountryName : { $first : "$CountryName" }}}
... )
This will produce the following output −
{ "_id" : 102, "Names" : [ "Robert", "John" ], "CountryName" : "UK" }
{ "_id" : 101, "Names" : [ "Robert", "Bob", "John" ], "CountryName" : "US" }
Select specific rows in a range with MySQL?

Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20)
   );
Query OK, 0 rows affected (1.23 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentName) values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(StudentName) values('Carol');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable(StudentName) values('David');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Adam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentName) values('Mike');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName) values('Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+-------------+
| Id | StudentName |
+----+-------------+
| 1  | John        |
| 2  | Carol       |
| 3  | David       |
| 4  | Bob         |
| 5  | Chris       |
| 6  | Robert      |
| 7  | Adam        |
| 8  | Mike        |
| 9  | Sam         |
+----+-------------+
9 rows in set (0.00 sec)
Here is the query to select specific rows MySQL −
mysql> select *from DemoTable ORDER BY Id DESC LIMIT 4 OFFSET 2;
+----+-------------+
| Id | StudentName |
+----+-------------+
| 7  | Adam        |
| 6  | Robert      |
| 5  | Chris       |
| 4  | Bob         |
+----+-------------+
4 rows in set (0.00 sec)
How to create a command-line progress bar in C/C++ - GeeksforGeeks

19 Jul, 2020
The task is to write a C/C++ program to draw a command-line progress bar.
Approach: To create a progress bar the idea is to use system() function which will give colored output. Below is the illustration of how to use system() function.
The system function accepts the following parameters for colouring the output screen:
keyword: colorBackground colorForeground color
keyword: color
Background color
Foreground color
Color Codes: 
Syntax:         
system(“color 9F”); The above code will give White Color output with Bright Blue color on Background. 
Below is the program to draw the progress bar in the command line in C/C++: 
C
C++
// C program to create loading bar#include <stdio.h>#include <windows.h>  // Function to creating loading barvoid loadingBar(){    // 0 - black background,    // A - Green Foreground    system("color 0A");      // Initialize char for printing    // loading bar    char a = 177, b = 219;      printf("\n\n\n\n");    printf("\n\n\n\n\t\t\t\t\t"           + "Loading...\n\n");    printf("\t\t\t\t\t");      // Print initial loading bar    for (int i = 0; i < 26; i++)        printf("%c", a);      // Set the cursor again starting    // point of loading bar    printf("\r");    printf("\t\t\t\t\t");      // Print loading bar progress    for (int i = 0; i < 26; i++) {        printf("%c", b);          // Sleep for 1 second        Sleep(1000);    }}  // Driver Codeint main(){    // Function Call    loadingBar();    return 0;}
// C++ program to create loading bar#include <iostream>#include <windows.h>using namespace std;  // Function to creating loading barvoid loadingBar(){    // 0 - black background,    // A - Green Foreground    system("color 0A");      // Initialize char for printing    // loading bar    char a = 177, b = 219;      printf("\n\n\n\n");    printf("\n\n\n\n\t\t\t\t\t"           + "Loading...\n\n");    printf("\t\t\t\t\t");      // Print initial loading bar    for (int i = 0; i < 26; i++)        printf("%c", a);      // Set the cursor again starting    // point of loading bar    printf("\r");    printf("\t\t\t\t\t");      // Print loading bar progress    for (int i = 0; i < 26; i++) {        printf("%c", b);          // Sleep for 1 second        Sleep(1000);    }}  // Driver Codeint main(){    // Function Call    loadingBar();    return 0;}
Output:Below is the output of the above program:
C Programs
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Regular expressions in C
C++ Program for QuickSort
CSV file management using C++
delete keyword in C++
cin in C++
Shallow Copy and Deep Copy in C++
Python | Ways to Convert a 3D list into a 2D list

02 Aug, 2019
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development.Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source.Below are some ways to achieve the above task.
Input:
[[[3], [4]], [[5], [6]], [[7], [8]]]
Output:
[[3], [4], [5], [6], [7], [8]]

Method #1: Using simple iteration to convert a 3D list into a 2D list.
# Python code to convert a 3D list into a 2D list  # Input list initializationInput = [[[3], [4]], [[5], [6]], [[7], [8]]]  # Output list initializationOutput = []  # Using iterationfor temp in Input:    for elem in temp:        Output.append(elem)  # printing outputprint("Initial 3d list is")print(Input)print("Converted 2d list is")print(Output)
Output:
Initial 3d list is
[[[3], [4]], [[5], [6]], [[7], [8]]]
Converted 2d list is
[[3], [4], [5], [6], [7], [8]]

Method #2: Using List Comprehension to convert a 3D list into a 2D list
# Python code to convert a 3D list into a 2D list  # Input list initializationInput = [[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]]  # Using list comprehensionOutput = [elem for twod in Input for elem in twod]  # printing outputprint("Initial 3d list is")print(Input)print("Converted 2d list is")print(Output)
Output:
Initial 3d list is
[[[1, 1], [2, 7]], [[3], [4]], [[6, 5], [6]]]
Converted 2d list is
[[1, 1], [2, 7], [3], [4], [6, 5], [6]]

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Django model data types and fields list - GeeksforGeeks

04 Jan, 2022
The most important part of a model and the only required part of a model is the list of database fields it defines. Fields are specified by class attributes. Be careful not to choose field names that conflict with the models API like clean, save, or delete. 
Example: 
from django.db import models

class Musician(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    instrument = models.CharField(max_length=200)

class Album(models.Model):
    artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()
Setting a field for storing any type of data is like deciding a data type in C/C++ for storing a particular integer, char etc. Fields in Django are the data types to store a particular type of data. For example, to store an integer, IntegerField would be used. These fields have in-built validation for a particular data type, that is you can not store “abc” in an IntegerField. Similarly, for other fields. This post revolves around major fields one can use in Django Models. 
Here are some key attributes one should be aware of before starting to use Django Fields.  
Each field in the model should be an instance of the appropriate Field class. Django uses field class types to determine a few things: 
The column type, which tells the database what kind of data to store (e.g. INTEGER, VARCHAR, TEXT).
The default HTML widget to use when rendering a form field (e.g. <input type=”text”>, <select>).
The minimal validation requirements, used in Django’s admin and in automatically-generated forms.
Django ships with dozens of built-in field types which can be used to save any type of data from number to entire HTML file too. Here is a list of all Field types used in Django.  
 
Django also defines a set of fields that represent relations. 
 
NaveenArora
junejavaibhav92
rathoreparikshit893
Sapna2001
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python | Multiply elements of Tuple - GeeksforGeeks

11 Dec, 2019
Given, a list of tuples, the task is to multiply the elements of the tuple and return list of the multiplied elements.
Examples:
Input: [(2, 3), (4, 5), (6, 7), (2, 8)]Output: [6, 20, 42, 16]
Input: [(11, 22), (33, 55), (55, 77), (11, 44)]Output: [242, 1815, 4235, 484]
There are multiple ways to multiply elements of a tuple. Let’s see a couple of them.
# Method 1: Using IterationThis is the most naive method to achieve a solution to this task. In this, we iterate over the whole list of tuples and multiply the elements in each tuple to get the list of elements.
# Python code to convert list of tuple into list of elements# formed by multiplying elements of tuple.  # Input list initialisationInput = [(2, 3), (4, 5), (6, 7), (2, 8)]  # Output list initialisationOutput = []  # Iteration to multiply element and append multiplied element in # new listfor elem in Input:    temp = elem[0]*elem[1]    Output.append(temp)  # printing outputprint("The original list of tuple is ")print(Input)  print("\nThe answer is")print(Output)
Output:
The original list of tuple is 
[(2, 3), (4, 5), (6, 7), (2, 8)]

The answer is
[6, 20, 42, 16]

# Method 2: Using list comprehensionThis is the one-liner approach to achieve the solution to this task.
# Python code to convert list of tuple into list of elements# formed by multiplying elements of tuple.  # Input list initialisationInput = [(2, 3), (4, 5), (6, 7), (2, 8)]  # Iteration to multiply element and append multiplied element in # new listOutput = [(x * y) for x, y in Input]  # printing outputprint("The original list of tuple is ")print(Input)  print("\nThe answer is")print(Output)
Output:
The original list of tuple is 
[(2, 3), (4, 5), (6, 7), (2, 8)]

The answer is
[6, 20, 42, 16]

python-tuple
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
mount command in Linux with Examples - GeeksforGeeks

23 May, 2019
All files in a Linux filesystem are arranged in form of a big tree rooted at ‘/‘.These files can be spread out on various devices based on your partition table, initially your parent directory is mounted(i.e attached) to this tree at ‘/‘, others can be mounted manually using GUI interface(if available) or using mount command.mount command is used to mount the filesystem found on a device to big tree structure(Linux filesystem) rooted at ‘/‘. Conversely, another command umount can be used to detach these devices from the Tree.
Syntax:
mount -t type device dir
Other forms:
mount [-l|-h|-V]
mount -a [-fFnrsvw] [-t fstype] [-O optlist]
mount [-fnrsvw] [-o options] device|dir
mount [-fnrsvw] [-t fstype] [-o options] device dir

These commands tells the Kernel to attach the filesystem found at device to the dir.
Note:
If you leave the dir part of syntax it looks for a mount point in /etc/fstab.
You can use –source or –target to avoid ambivalent interpretation.mount --target /mountpoint
mount --target /mountpoint
/etc/fstab usually contains information about which device is need to be mounted where.
Most of the devices are indicated by files like /dev/sda4, etc. But it can be different for certain filesystems. Please refer below for more information.man mount
man mount
Note: It is important to note that we are only discussing the standard form of mount command given as syntax. Different forms are somewhat discussed because it has certain limitations on different kernels.
Some Important Options:
l : Lists all the file systems mounted yet.
h : Displays options for command.
V : Displays the version information.
a : Mounts all devices described at /etc/fstab.
t : Type of filesystem device uses.
T : Describes an alternative fstab file.
r : Read-only mode mounted.
Examples:
Displays information about file systems mounted:
Mounts file systems:
Displays version information:
Unmounts file systems:
linux-command
Linux-file-commands
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
UDP Server-Client implementation in C
Tail command in Linux with examples
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
Python | Pandas Series.dt.is_month_end - GeeksforGeeks

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.is_month_end attribute return a boolean value Indicating whether the date is the last day of the month.
Syntax: Series.dt.is_month_end
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.is_month_end attribute to check if the dates in the underlying data of the given series object is last day of the month or not.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-1-31', '2019-7-18 12:30', '2008-02-2 10:30',               '2010-4-22 09:25', '2019-1-1 00:00'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.is_month_end attribute to check if the dates in the given series object is last day of the month or not.
# check if dates are the last# day of the month or notresult = sr.dt.is_month_end  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.is_month_end attribute has successfully accessed and returned boolean values indicating whether the dates are the last day of the month or not. Example #2 : Use Series.dt.is_month_end attribute to check if the dates in the underlying data of the given series object is last day of the month or not.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-3-31 00:00',                       periods = 5, freq = 'M'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.is_month_end attribute to check if the dates in the given series object is last day of the month or not.
# check if dates are the last# day of the month or notresult = sr.dt.is_month_end  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.is_month_end attribute has successfully accessed and returned boolean values indicating whether the dates are the last day of the month or not.
Python pandas-series-datetime
Python-pandas
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
*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
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
DateTimeOffset.ToUnixTimeMilliseconds() Method in C# - GeeksforGeeks

19 Mar, 2019
DateTimeOffset.ToUnixTimeMilliseconds Method is used to return the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z. This method will return a negative value for the date and time values before 1970-01-01T00:00:00Z.
Syntax: public long ToUnixTimeMilliseconds ();
Return Value: This method returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z.
Below programs illustrate the use of DateTimeOffset.ToUnixTimeMilliseconds() Method:
Example 1:
// C# program to demonstrate the// DateTimeOffset.ToUnixTimeMilliseconds()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // creating object of  DateTimeOffset        DateTimeOffset offset = new DateTimeOffset(2007,                6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));          // Returns the number of milliseconds        // instance using ToUnixTimeMilliseconds() method        long value = offset.ToUnixTimeMilliseconds();          // Display the time        Console.WriteLine("Returns the number of"+                    " milliseconds : {0}", value);    }}
Returns the number of milliseconds : 1180702500000

Example 2:
// C# program to demonstrate the// DateTimeOffset.ToUnixTimeMilliseconds()// Methodusing System;using System.Globalization;  class GFG {      // Main Method    public static void Main()    {        // Creating object of  DateTimeOffset        DateTimeOffset offset = new DateTimeOffset(1960,                6, 1, 7, 55, 0, new TimeSpan(-5, 0, 0));          // Returns the number of milliseconds        // instance using ToUnixTimeMilliseconds() method        long value = offset.ToUnixTimeMilliseconds();          // Display the time        Console.WriteLine("Returns the number "+                "of milliseconds : {0}", value);    }}
Returns the number of milliseconds : -302439900000

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimemilliseconds?view=netframework-4.7.2
CSharp-DateTimeOffset-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
Difference between Ref and Out keywords in C#
Extension Method in C#
Introduction to .NET Framework
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
C# | Data Types
C# | Arrays
HashSet in C# with Examples