code-rag-bench/online-tutorials huggingface dataset:
Swift - Sets

Swift 4 sets are used to store distinct values of same types but they don’t have definite ordering as arrays have.
You can use sets instead of arrays if ordering of elements is not an issue, or if you want to ensure that there are no duplicate values. (sets allow only distinct values.)
A type must be hashable to be stored in a set. A hash value is a Int value that is equal for equal objects. For example, if x == y, then x.hashvalue == y.hashvalue.
All the basic swift values are of hashable type by default and may be used as set values.
You can create an empty set of a certain type using the following initializer syntax −
var someSet = Set<Character>()     //Character can be replaced by data type of set.

You can access or modify a set using its methods and properties −
"count" method can be used to show the number of elements in the set.
someSet.count        // prints the number of elements

"insert" method can be used to insert values in set.
someSet.insert("c")   // adds the element to Set.

Similarly, isEmpty can be used to check if set is empty.
someSet.isEmpty       // returns true or false depending on the set Elements.

"remove" method can be used to remove value in set.
someSet.remove("c")     // removes a element , removeAll() can be used to remove all elements

"contains" method can be used to check existence of value in a set.
someSet.contains("c")     // to check if set contains this value.

You can iterate over a set using for-in loop −
for items in someSet {
   print(someSet)
}

//Swift sets are not in an ordered way, to iterate over a set in ordered way use

for items in someSet.sorted() {
   print(someSet)
}  
You can perform basic set operations on swift Sets.
Following are the methods for performing set operations −
Intersection
Union
subtracting
let evens: Set = [10,12,14,16,18]
let odds: Set = [5,7,9,11,13]
let primes = [2,3,5,7]
odds.union(evens).sorted()
// [5,7,9,10,11,12,13,14,16,18]
odds.intersection(evens).sorted()
//[]
odds.subtracting(primes).sorted()
//[9, 11, 13]


    38 Lectures 
     1 hours 

 Ashish Sharma

    13 Lectures 
     2 hours 

 Three Millennials

    7 Lectures 
     1 hours 

 Three Millennials

    22 Lectures 
     1 hours 

 Frahaan Hussain

    12 Lectures 
     39 mins

 Devasena Rajendran

    40 Lectures 
     2.5 hours 

 Grant Klimaytys
 Print
 Add Notes
 Bookmark this page
How to convert string to JSON using Python?

To convert a JSON string to a dictionary using json.loads(). This method accepts a valid json string and returns a dictionary in which you can access all elements. For example,
>>> import json
>>> s = '{"success": "true", "status": 200, "message": "Hello"}'
>>> d = json.loads(s)
>>> print d["success"], d["status"]
true 200
If you have a json file instead and want to construct a dict out of it, you can use the json.load() method.
Quick Sort Program in C

Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value.
#include <stdio.h>
#include <stdbool.h>

#define MAX 7

int intArray[MAX] = {4,6,3,2,1,9,7};

void printline(int count) {
   int i;
	
   for(i = 0;i < count-1;i++) {
      printf("=");
   }
	
   printf("=\n");
}

void display() {
   int i;
   printf("[");
	
   // navigate through all items 
   for(i = 0;i < MAX;i++) {
      printf("%d ",intArray[i]);
   }
	
   printf("]\n");
}

void swap(int num1, int num2) {
   int temp = intArray[num1];
   intArray[num1] = intArray[num2];
   intArray[num2] = temp;
}

int partition(int left, int right, int pivot) {
   int leftPointer = left -1;
   int rightPointer = right;

   while(true) {
      while(intArray[++leftPointer] < pivot) {
         //do nothing
      }
		
      while(rightPointer > 0 && intArray[--rightPointer] > pivot) {
         //do nothing
      }

      if(leftPointer >= rightPointer) {
         break;
      } else {
         printf(" item swapped :%d,%d\n", intArray[leftPointer],intArray[rightPointer]);
         swap(leftPointer,rightPointer);
      }
   }
	
   printf(" pivot swapped :%d,%d\n", intArray[leftPointer],intArray[right]);
   swap(leftPointer,right);
   printf("Updated Array: "); 
   display();
   return leftPointer;
}

void quickSort(int left, int right) {
   if(right-left <= 0) {
      return;   
   } else {
      int pivot = intArray[right];
      int partitionPoint = partition(left, right, pivot);
      quickSort(left,partitionPoint-1);
      quickSort(partitionPoint+1,right);
   }        
}

int main() {
   printf("Input Array: ");
   display();
   printline(50);
   quickSort(0,MAX-1);
   printf("Output Array: ");
   display();
   printline(50);
}
If we compile and run the above program, it will produce the following result −
Input Array: [4 6 3 2 1 9 7 ]
==================================================
 pivot swapped :9,7
Updated Array: [4 6 3 2 1 7 9 ]
 pivot swapped :4,1
Updated Array: [1 6 3 2 4 7 9 ]
 item swapped :6,2
 pivot swapped :6,4
Updated Array: [1 2 3 4 6 7 9 ]
 pivot swapped :3,3
Updated Array: [1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
JavaScript: take every nth Element of Array and display a fixed number of values?

For this, you can use for loop along with if condition. Let’s say the following is our array −
var numbers = [1, 2, 34, 56, 78, 90, 100, 110, 40, 70, 67, 77, 34, 68, 89, 91, 94];
We have set a counter to set a value. This value is set to display a fixed number of values −
var counter = 6;
The above shows the result will be 6 values.
Following is the code −
var numbers = [1, 2, 34, 56, 78, 90, 100, 110, 40, 70, 67, 77, 34, 68, 89, 91, 94];
var counter = 6;
var newNumbers = [];
var start = 0;
for (var index = 0; index < numbers.length; index++) {
   if (index % 2 != 0) {
      start++;
      if (start <= counter) {
         newNumbers.push(numbers[index]);
      }
   }
}
console.log(newNumbers);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo231.js
The output is as follows −
PS C:\Users\Amit\JavaScript-code> node demo231.js
[ 2, 56, 90, 110, 70, 77 ]
Powershell - Miscellaneous Operators Examples

The following scripts demonstrates the miscellaneous operators.
> $location = Get-Location
 
> $location -is 'System.Management.Automation.PathInfo'
 True
 
> $location -isNot 'System.Management.Automation.PathInfo'
 True
 
> $i = 1
 
> $i++
 
> $i
 2

    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
The unless & die Function in Perl

The unless function in Perl is the logical opposite to if: statements can completely bypass the success status and only be executed if the expression returns false. For example −
unless(chdir("/etc")) {
   die "Error: Can't change directory - $!";
}
The unless statement is best used when you want to raise an error or alternative only if the expression fails. The statement also makes sense when used in a single-line statement −
die "Error: Can't change directory!: $!" unless(chdir("/etc"));
Here we die only if the chdir operation fails.
The die function works just like warn, except that it also calls exit. Within a normal script, this function has the effect of immediately terminating execution. You should use this function in case it is useless to proceed if there is an error in the program −
chdir('/etc') or die "Can't change directory";
Apache Drill - NULLIF(x,y)

The following program shows the query for this function −
0: jdbc:drill:zk = local> select NULLIF(3,3) from (values(1));
+---------+
| EXPR$0  |
+---------+
|  null   |
+---------+

Here both the arguments are same, so the result is NULL.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
C program to convert centimeter to meter and kilometer

Here, the user has to enter the length in centimeters (cm), and then, convert the length into meters (m), and kilometer (km).
1 Meter = 100 Centimeters
1 Kilometer = 100000 Centimeters
Refer an algorithm given below to convert centimeter into meter and kilometer respectively.
Step 1: Declare variables.
Step 2: Enter length in cm at runtime.
Step 3: Compute meter by using the formula given below.
   meter = centim / 100.0;
Step 4: Compute kilometer by using the formula given below.
   kilometer = centim / 100000.0
Step 5: Print meter.
Step 6: Print kilomete
Following is the C program to convert centimeter to meter and kilometer respectively −
 Live Demo
#include <stdio.h>
int main(){
   float centim, meter, kilometer;
   printf("enter length in cm:\n ");
   scanf("%f", &centim);
   meter = centim / 100.0;
   kilometer = centim / 100000.0;
   printf("length in mtrs = %.4f\n", meter);
   printf("length in km = %.4f", kilometer);
   return 0;
}
When the above program is executed, it produces the following result −
enter length in cm:
length in mtrs = 0.0000
length in km = 0.0000
Following is the C Program to convert meter to centimeter and kilometer respectively.
 Live Demo
#include <stdio.h>
int main(){
   float centim, meter, kilometer;
   printf("enter length in meter:\n ");
   scanf("%f", &meter);
   centim = meter*100.0;
   kilometer = meter / 1000.0;
   printf("length in cm = %.4f\n", centim);
   printf("length in km = %.4f", kilometer);
   return 0;
}
When the above program is executed, it produces the following result −
enter length in meter:
length in cm = 0.0000
length in km = 0.0000
How to change the color of a Tkinter label programmatically?

Tkinter Label widgets are used to add text or images to the application. We can even configure the basic properties of labels using the config(options) method. Generally, in order to configure the widgets property dynamically, we use callback functions where we modify the value of attributes.
In this example, we will modify the color Tkinter Labels by defining the callback function. The function can be activated by a button that forces the labels to change the color.
#Import required libraries
from tkinter import *
from tkinter import ttk

#Create an instance of tkinter frame
win= Tk()

#Define the geometry of the window
win.geometry("750x250")

#Define a function to Change the color of the label widget
def change_color():
   label.config(bg= "gray51", fg= "white")

#Create a label
label= Label(win, text= "Hey There! How are you?", font= ('Helvetica20 italic'))
label.pack(pady=30)

#Create a Button
ttk.Button(win, text="Change Color", command=change_color).pack(pady=20)
win.mainloop()
Running the above code will display a window that contains a label and a button.
Now, click "Change Color" button to change the color of the Label widget.
jQuery - noConflict()

Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all the functionality is available without using $.
Run $.noConflict() method to give control of the $ variable back to whichever library first implemented it. This helps us to make sure that jQuery doesn't conflict with the $ object of other libraries.
Here is simple way of avoiding any conflict −
// Import other Library
// Import jQuery Library
$.noConflict();
// Code that uses other library's $ can follow here.
This technique is especially effective in conjunction with the .ready() method's ability to alias the jQuery object, as within the .ready() we can use $ if we wish without fear of conflicts later −
// Import other library
// Import jQuery
$.noConflict();
jQuery(document).ready(function($) {
   // Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
D3.js style() Function - GeeksforGeeks

09 Aug, 2020
The d3.style() function in D3.js is used to style the specified node(attribute) with the specified name(Value). In this, if the node has an inline style with the specified name, its value is returned and if the node has not an inline style, the calculated value is returned.
Syntax: 
d3.style(node, name)

Parameters: This function accepts two parameters as mentioned above and described below:
node: This is a property of the selected element.
name: This is the value of the specified attribute.
Return Value: This function returns the value style property for the specified node(attribute) with the specified name(Value).
Below examples illustrate the d3.style() function in D3.jsExample 1:
html
<!DOCTYPE html><html>    <head>        <title>            D3.js | d3.style() Function        </title>          <script src="https://d3js.org/d3.v4.min.js">        </script>    </head>      <body>        <p style="color: green;">          GeeksforGeeks        </p>          <p style="color: green;">          A computer science portal for geeks        </p>          <script>                        // Calling the style() function            d3.select("p").style("color", "red");        </script>    </body></html>
Output:  
Example 2:
html
<!DOCTYPE html><html>    <head>        <title>            D3.js | d3.style() Function        </title>          <script src="https://d3js.org/d3.v4.min.js">        </script>    </head>      <body>        <p style="color: green;">          GeeksforGeeks        </p>            <p style="color: green;">          A computer science portal for geeks        </p>          <script>            // Calling the style() function            d3.select("p").style("font-size", "40px");        </script>    </body></html>
Output: 
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
JavaScript | console.log() with Examples
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to animate a Seaborn heatmap or correlation matrix(Matplotlib)?

To animate a Seaborn heatmap or correlation matrix, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Make a dimension tuple.
Make a Seaborn heatmap.
Create an init() method for the first heatmap.
Use FuncAnimation() class to make an animation by repeatedly calling a function animate that will create a random dataset and create a heatmap.
To display the figure, use show() method.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import animation

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
dimension = (5, 5)
data = np.random.rand(dimension[0], dimension[1])
sns.heatmap(data, vmax=.8)

def init():
    sns.heatmap(np.zeros(dimension), vmax=.8, cbar=False)

def animate(i):
    data = np.random.rand(dimension[0], dimension[1])
    sns.heatmap(data, vmax=.8, cbar=False)

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=20, repeat=False)

plt.show()
How to Print Hard Copy using Tkinter?

Tkinter allows developers to interact with the files inside the local system. In this article, we will see how to print a hardcopy of a file using Tkinter packages such as filedialog and win32api module.
In order to import these packages, we have to first install these modules in our environment. To install win32api, we will use pip install pywin32
#import the required libraries
from tkinter import *
from tkinter import filedialog
import win32api

#Create an instance of tkinter frame or window
win= Tk()

win.title('Print Hard Copy')
win.geometry("700x400")

#Define function
def print_file():
   file= filedialog.askopenfilename(initialdir="/", title="Select any file",filetypes=(("Text files", "*.txt"), ("all files", "*.*")))
   if file:
      #Print Hard copy using Printer
      win32api.ShellExecute(0, "Choose a File", file, None, ".", 0)
#Create a button for printing event
button= Button(win, text="Choose a File to Print", command=print_file).pack(pady= 20)

#Keep running the window or frame
win.mainloop()
Running the above code will produce the following output −
If you click the button, it will open up a folder from where you can select a file to
print.
PHP func_get_arg() Function - GeeksforGeeks

09 Jul, 2020
The func_get_arg() function is an inbuilt function in PHP which is used to get a mentioned value from the argument passed as the parameters.
Syntax:
mixed func_get_arg( int $arg )
Parameters: This function accepts a single parameter as mentioned above and described below.
$arg: This parameter holds the argument offset where the offset of the arguments in the parameter is counted by assuming the first argument to be 0.
Return Value: This method returns the mentioned argument and returns FALSE if an error occurs.
Example 1:
<?php  // Function definitionfunction geeks($a, $b, $c) {      // Calling func_get_arg() function      echo "Print second argument: "        . func_get_arg(1) . "\n";}  // Function callgeeks('hello', 'php', 'geeks');  ?>
Output:
Print second argument: php
When does any error occur?The error occurs in two cases.
If the value of argument offset is more than the actual value of arguments passed as the parameter of the function.
If this function is not being called from within the user-defined function.
<?php  // Function definitionfunction geeks($a, $b, $c) {      // Printing the sixth argument    // that doesn't exist    echo "Printing the sixth argument: "        . func_get_arg(5) . "\n";}  // Function callgeeks('hello', 'php', 'geeks');  ?>
Output:
Warning:  func_get_arg():  Argument 5 not passed to function in 
    [...][...] on line 4

Example:
<?php  // Function definitionfunction geeks($a, $b, $c) {     $a = "Bye";}  // Function callgeeks('hello', 'php', 'geeks');  // The func_get_arg() function// is called from outside the// user defined functionecho "Printing the sixth argument: "        . func_get_arg(5) . "\n";          ?>
Output:
PHP Warning:  func_get_arg():  Called from the global scope - 
no function context in /home/main.php on line 9       

For versions before PHP 5.3: Getting a function’s argument has a different approach for the PHP versions below 5.3. All the versions above 5.3 and 5.3 will show an error for the following code.
Example:
<?phpfunction geeks() {    include './testing.inc';}  geeks('Welcome', 'PHP', 'Geeks');?>
testing.inc:
<?php  $parameter = func_get_arg(1);var_export($parameter);  ?>
Output:
'PHP' warnings

Note: For getting more than one argument func_get_args() function can be used instead of func_get_arg() function.
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP str_replace() Function
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to use matTooltip in Angular Material ? - GeeksforGeeks

08 Feb, 2021
Angular Material is a UI component library developed by Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have done it you can enter the below command and can download it. matTooltip is used when certain information is to be displayed when a user hovers on a button.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatTooltipModule’ from ‘@angular/material/tooltip’ in the app.module.ts file.
We need to use ‘matTooltip’ property to display the text we want to render.
For showing the position we need to use the ‘matTooltipPosition’ property.
We can also customize the position of the tooltip regarding where to display like using the following names as “above”, “below”, “left”, “right” etc.
Once done with the above steps then serve or start the project.
Project Structure: It will look like the following.
Code Implementation:
app.module.ts:
Javascript
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms';       import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from     '@angular/platform-browser/animations';import { MatTooltipModule } from '@angular/material/tooltip'; import { MatButtonModule } from '@angular/material/button';   @NgModule({     imports: [         BrowserModule,         FormsModule,         MatButtonModule,        MatTooltipModule,        BrowserAnimationsModule    ],     declarations: [ AppComponent ],     bootstrap: [ AppComponent ] }) export class AppModule { }
app.component.html:
HTML
<br><button mat-raised-button matTooltip=    "Hover to display information on below."        matTooltipPosition="below">    Hover to show information</button>  <br><br><br><br><br>  <button mat-raised-button matTooltip=    "Hover to display information on right."        matTooltipPosition="right">    Hover to show information</button>
Output:
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
Angular PrimeNG Messages Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to check if a float value is a whole number in Python?

To check if a float value is a whole number, use the float.is_integer() method. For example,
print((10.0).is_integer())
print((15.23).is_integer())
This will give the output
True
False
How do I plot hatched bars using Pandas and Matplotlib?

To plot hatches bars using Pandas, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Make a dataframe using Pandas with two columns.
Make a dataframe using Pandas with two columns.
Add an axes to the current figure as a subplot arrangement.
Add an axes to the current figure as a subplot arrangement.
Make a plot with kind="bars" class by name.
Make a plot with kind="bars" class by name.
Make a list of hatches.
Make a list of hatches.
Get the bars patches using bars.patches.
Get the bars patches using bars.patches.
Iterate bars patches and set the hatch of each patch.
Iterate bars patches and set the hatch of each patch.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
ax = plt.figure().add_subplot(111)
bars = df.plot(ax=ax, kind='bar')
hatches = ["*", "/", "o", "x"]

for patch in bars.patches:
   patch.set_hatch(hatches[np.random.randint(10)%len(hatches)])

plt.show()
VBA - If Elseif - Else statement

An If statement followed by one or more ElseIf statements that consists of boolean expressions and then followed by a default else statement, which executes when all the condition becomes false.
Following is the syntax of an If Elseif - Else statement in VBScript.
If(boolean_expression) Then
   Statement 1
   .....
   .....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
   .....
   ....
   Statement n
ElseIf (boolean_expression) Then
   Statement 1
   .....
   ....
   Statement n
Else
   Statement 1
   .....
   ....
   Statement n
End If

For demo purpose, let us find the biggest between the two numbers of an Excel with the help of a function.
Private Sub if_demo_Click()
   Dim x As Integer
   Dim y As Integer
    
   x = 234
   y = 234
    
   If x > y Then
      MsgBox "X is Greater than Y"
   ElseIf y > x Then
      Msgbox "Y is Greater than X"
   Else
      Msgbox "X and Y are EQUAL"
   End If
End Sub
When the above code is executed, it produces the following result.
X and Y are EQUAL


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
How to write a text file in Selenium with python?

We can write a text file in Selenium with python by first creating a txt file and having a content on it.
First of all, we need to open the file in write mode and mention the path of the location of the text file as an argument. There are multiple reading methods to perform these operations.
write() – It writes the string in one line in a text file.
write() – It writes the string in one line in a text file.
writelines() – It writes more than one string in a text file.
writelines() – It writes more than one string in a text file.
Code Implementation with write().
#open the file for write operation
f = open('hello.txt' , 'w')
#writes the new content
f.write('Tutorialspoint')
#close the file
f.close()
# again open the file for read
f = open('hello.txt' , 'r')
#reads the file content and prints in console
print(f.read())
#close the file
f.close()
Code Implementation with writelines()
#open the file for write operation
f = open('hello.txt' , 'w')
lines = ["Tutorialspoint", "Selenium"]
#writes the new content
f.writelines(lines)
#close the file
f.close()
# again open the file for read
f = open('hello.txt' , 'r')
#reads the file content and prints in console
print(f.read())
#close the file
f.close()
Operating Procedures in Software Engineering - GeeksforGeeks

16 Jun, 2020
Prerequisite – Software ProcessesSoftware consist of the following components-
1. Program code
2. Documentation
3. Operating Procedures 
The operating procedures is a set of step-by-step instructions compiled by an organization to help workers carry out complex routine operations. It consists of all the information that is required for operating the Software. The operating procedures are equally important as the program code of the software.
The operating procedure consists of two modules : User manuals, and Operational manuals. These are explained as following below.
1. User Manuals :This manuals is used to describe how to operate the particular software.The User Manual consist of the following –
System overview –It describe the overview of the entire software. It is used to defines what are the purpose of the software.
Beginner’s guide tutorials –This guide consist of step by step procedure for operating the software. A beginner can know how to use software and the working of it. Overall, it helps in getting to know the software.
Reference guide –This guide is a help book for the users. Users can look forward for further reference in the Reference guide.
2. Operational Manual :This manual describes all the requirements and supports of the hardware and software that are required for software running.The Operational Manual consist of the following –
Installation guide –This guide consist of all information regarding the installation of the software.
System administration guide –This guide consist of all information regarding the Administration settings and the permissions that are required for the Software.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Waterfall Model and Spiral Model
DFD for Library Management System
Software Development Life Cycle (SDLC)
Data Dictionaries in Software Engineering
What is DFD(Data Flow Diagram)?
Software Engineering | User Interface Design
Software Processes in Software Engineering
Software Engineering | Control Flow Graph (CFG)
Software Engineering | Capability maturity model (CMM)
RUP and its Phases
What are enumerations in Java? How to retrieve values from an enum?

Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
You can define an enumeration using the keyword enum followed by the name of the enumeration as −
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Just like arrays, the elements/constants in an enumeration are identified using numbers starting from 0 in the above example the days are identified using numbers as shown in the following illustration −
You can retrieve all the elements of an enum using the values() method.
 Live Demo
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumerationExample {
   public static void main(String args[]) {
      Days constants[] = Days.values();
      System.out.println("Value of constants: ");
      for(Days d: constants) {
         System.out.println(d);
      }
   }
}
Value of constants:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
How to get a value more than a particular value from varchar column in MySQL?

Since the column wherein you want to get the value more than a particular value is VARCHAR, use the CAST() function. For example, to fetch the value more than 999 from a column with varchar values.
Let us first create a table −
mysql> create table DemoTable
(
   Value varchar(100)
);
Query OK, 0 rows affected (1.02 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('900');
Query OK, 1 row affected (0.49 sec)
mysql> insert into DemoTable values('1090');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('860');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('12345');
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable values('908345');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+
| Value  |
+--------+
| 900    |
| 1090   |
| 860    |
| 12345  |
| 908345 |
+--------+
5 rows in set (0.00 sec)
Following is the query to get a value more than a particular value from varchar column −
mysql> select max(cast(Value AS SIGNED)) from DemoTable;
This will produce the following output −
+----------------------------+
| max(cast(Value AS SIGNED)) |
+----------------------------+
|                     908345 |
+----------------------------+
1 row in set (0.05 sec)
Binary Search Tree Iterator in C++

Suppose we want to make one iterator for binary tree. There will be two methods. The next() method to return the next element, and hasNext() method to return Boolean value, that will indicate that the next element is present or not. So if the tree is like −
And the sequence of function calls are [next(), next(), hasNext(), next(), hasNext(),next(), hasNext(),next(), hasNext()]. The output will be [3,7,true,9,true,15,true,20,false]
To solve this, we will follow these steps −
There are two methods next and hasNext,
The next() method will be like −
curr := stack top element, and pop top element
if right of curr is not null, then push inorder successor from the right of node
return value of current
The hasNext() method will be like −
return true, when stack is not empty, otherwise false.
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   public:
      int val;
      TreeNode *left, *right;
      TreeNode(int data){
         val = data;
         left = right = NULL;
      }
};
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
   q.push(*root);
   while(q.size()){
      TreeNode *temp = q.front();
      q.pop();
      if(!temp->left){
         if(val != NULL)
            temp->left = new TreeNode(val);
         else
            temp->left = new TreeNode(0);
         return;
      } else {
         q.push(temp->left);
      }
      if(!temp->right){
         if(val != NULL)
            temp->right = new TreeNode(val);
         else
            temp->right = new TreeNode(0);
            return;
      }else{
            q.push(temp->right);
      }
   }
}
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   }
   return root;
}
class BSTIterator {
public:
   stack <TreeNode*> st;
   void fillStack(TreeNode* node){
      while(node && node->val != 0){
         st.push(node);
         node=node->left;
      }
   }
   BSTIterator(TreeNode* root) {
      fillStack(root);
   }
   /** @return the next smallest number */
   int next() {
      TreeNode* curr = st.top();
      st.pop();
      if(curr->right && curr->right->val != 0){
         fillStack(curr->right);
      }
      return curr->val;
   }
   /** @return whether we have a next smallest number */
   bool hasNext() {
      return !st.empty();
   }
};
main(){
   vector<int> v = {7,3,15,NULL,NULL,9,20};
   TreeNode *root = make_tree(v);
   BSTIterator ob(root);
   cout << "Next: " << ob.next() << endl;
   cout << "Next: " << ob.next() << endl;
   cout << ob.hasNext() << endl;
   cout << "Next: " << ob.next() << endl;
   cout << ob.hasNext() << endl;
   cout << "Next: " << ob.next() << endl;
   cout << ob.hasNext() << endl;
   cout << "Next: " << ob.next() << endl;
   cout << ob.hasNext() << endl;
}
BSTIterator ob(root);
ob.next()
ob.next()
ob.hasNext()
ob.next()
ob.hasNext()
ob.next()
ob.hasNext()
ob.next()
ob.hasNext()
Next: 3
Next: 7
1
Next: 9
1
Next: 15
1
Next: 20
0
Bubble Chart with Data Labels

Following is an example of a Bubble Chart with Labels.
We have already seen the configurations used to draw a chart in Google Charts Configuration Syntax chapter. Now, let us see an example of a Bubble Chart with Data Labels.
We've used BubbleChart class to show a Bubble Chart with Data Labels.
type = 'BubbleChart';

app.component.ts
import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'Age vs Weight';
   type = 'BubbleChart';
   data = [
      ["Robert", 8, 12],
      ["Mohan", 4, 5.5],
      ["Ramesh", 11, 14],
      ["Julie", 3, 3.5],
      ["Sohan", 6.5, 7]
   ];
   columnNames = ['Id', 'Age','Weight'];
   options = { };
   width = 550;
   height = 400;
}
Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Matplotlib.axes.Axes.get_xaxis() in Python - GeeksforGeeks

19 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.get_xaxis() function in axes module of matplotlib library return the XAxis instance.
Syntax: Axes.get_xaxis(self)
Parameters: This method does not accepts any parameters.
Returns:This method returns the XAxis instance.
Below examples illustrate the matplotlib.axes.Axes.get_xaxis() function in matplotlib.axes:
Example 1:
# 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)ax.set_title('matplotlib.axes.Axes.get_xaxis() \Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np       x = np.linspace(0, 200, 10)yy = np.transpose([2 * np.sin(x + phi) for phi in x])   fig, ax = plt.subplots()ax.plot(yy)w = ax.get_xaxis()w.tick_top()ax.set_title('matplotlib.axes.Axes.get_xaxis() \Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Python String | replace()
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Python OOPs Concepts
Python | Get unique values from a list
vars() function in Python

vars() function belongs to the collection of inbuilt functions provided by the Python standard library. It returns the __dic__ attribute of an associated object to the console.
vars(object)
<Dictionary Type>
vars() function accepts only one parameter. It takes an object as its parameter which can be any module, class or any object having __dict__ attribute associated with it.
This parameter is optional in nature. In case the function is used without parameters A dictionary containing local symbol table is displayed.
If the argument passed doesn’t match the attribute, it raises the TypeError exception.
Vars() acts like locals() method when no argument is passed.The locals() method modifies and returns-back a dictionary of the currently present local symbol table.
The <class−name> associates with the __name__ attribute; the bases tuple get itemized with the base classes and associates the __bases__ attribute & dictionary is the current namespace that contains definitions contained in class body and gets copied to a standard dictionary type to display as the __dict__ attribute.
Let’s us discuss some examples so that we can grasp the concept of vars() function
 Live Demo
class test:
   def __init__(self, integer_1=555, integer_2=787):
      self.integer_1 = integer_1
      self.integer_2 = integer_2
   obj_test = test()
print(vars(obj_test))
{'integer_1': 555, 'integer_2': 787}
 Live Demo
class sample:
   company = "Tutorial's Point "
   Number = 4
   Topic = "Python 3.x."
obj = vars(sample)
print(obj)
{'__doc__': None, '__weakref__': <attribute '__weakref__' of 'sample' objects>, 'Topic': 'Python 3.x.', 'company': "Tutorial's Point ", '__module__': '__main__', 'Number': 4, '__dict__': <attribute '__dict__' of 'sample' objects>}
 Live Demo
class test():
# Python __repr__() function returns the representation of the object.
# It may contain any valid expression such as tuples, list, dictionary, string, set etc
   def __repr__(self):
      return "Tutorial's point"
   def localvariables(self):
      number = 4
      return locals()

if __name__ == "__main__":
   obj = test()
   print (obj.localvariables())
{'self': Tutorial's point, 'number': 4}
First example code depicts the use of __dict__ attributes associated with the constructor of the class with the default value set in the constructor method.4
Second example code depicts the use of __dict__ attributes associated with the class itself with the __doc__ attribute empty.
Third example code depicts the use of __dict__ attributes associated with a user-defined function inside the class with the variable in the local scope.
In this article, we learnt how to implement vars function in various cases in Python 3.x. Or earlier. You can implement the same algorithm to use the vars function whenever needed.
Python | Test for nested list - GeeksforGeeks

05 Sep, 2019
Sometimes, while working with Python list, we might have a problem in which we need to find that a list is a Matrix or a list contains list as it’s element. This problem can come in Data Science domain as it involves use of Matrices more than often. Let’s discuss certain way in which this task can be performed.
Method : Using any() + isinstance()The combination of above functions can be used to perform this task. The any() is used to check for each of the occurrence and isinstance() is used to check for list.
# Python3 code to demonstrate working of# Test for nested list# using any() + isinstance()  # initialize listtest_list = [[5, 6], 6, [7], 8, 10]  # printing original listprint("The original list is : " + str(test_list))  # Test for nested list# using any() + isinstance()res = any(isinstance(sub, list) for sub in test_list)  # printing resultprint("Does list contain nested list ? : " + str(res))
The original list is : [[5, 6], 6, [7], 8, 10]
Does list contain nested list ? : True

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
Java program to Count the number of digits in a given integer

Read a number from user. Create an integer (count) initialize it with 0. Divide the number with 10. till the number is 0 and for each turn increment the count.
import java.util.Scanner;
public class CountingDigitsInInteger {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      int count = 0;
      System.out.println("Enter a number ::");
      int num = sc.nextInt();
      while(num!=0){
         num = num/10;
         count++;
      }
      System.out.println("Number of digits in the entered integer are :: "+count);
   }
}
Enter a number ::
1254566
Number of digits in the entered integer are :: 7
Add to existing value in MySQL column using CONCAT function?

To understand the concept, let us first create a demo table.
mysql> create table addToExistingValueDemo
   -> (
   -> Instructor_Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Instructor_Name varchar(30),
   -> Instructor_TechnicalSubject text
   -> );
Query OK, 0 rows affected (0.54 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('John','C,C++');
Query OK, 1 row affected (0.15 sec)
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('Carol','Java,Python');
Query OK, 1 row affected (0.18 sec)
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('Bob','MySQL,SQL Server');
Query OK, 1 row affected (0.15 sec)
mysql> insert into addToExistingValueDemo(Instructor_Name,Instructor_TechnicalSubject) values('David','DataStructure');
Query OK, 1 row affected (0.18 sec
Display all records from the table using select statement. The query is as follows −
mysql> select *from addToExistingValueDemo;
The following is the output
+---------------+-----------------+-----------------------------+
| Instructor_Id | Instructor_Name | Instructor_TechnicalSubject |
+---------------+-----------------+-----------------------------+
|             1 | John            | C,C++                       |
|             2 | Carol           | Java,Python                 |
|             3 | Bob             | MySQL,SQL Server            |
|             4 | David           | DataStructure               |
+---------------+-----------------+-----------------------------+
4 rows in set (0.00 sec)
Here is the query to add to existing value in MySQL column using CONCAT function
mysql> update addToExistingValueDemo
   -> set Instructor_TechnicalSubject=concat(Instructor_TechnicalSubject,', Introduction To Algorithm')
   -> where Instructor_Id=4;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Let us check the table records once again to see the new changes. The query is as follows −
mysql> select *from addToExistingValueDemo;
The following is the output
+---------------+-----------------+------------------------------------------+
| Instructor_Id | Instructor_Name | Instructor_TechnicalSubject              |
+---------------+-----------------+------------------------------------------+
|             1 | John            | C,C++                                    |
|             2 | Carol           | Java,Python                              |
|             3 | Bob             | MySQL,SQL Server                         |
|             4 | David           | DataStructure, Introduction To Algorithm |
+---------------+-----------------+------------------------------------------+
4 rows in set (0.00 sec)