code-rag-bench/online-tutorials huggingface dataset:
write() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
write - write to a file descriptor
#include <unistd.h> 
ssize_t write(int fd, const void *buf, size_t count); 


ssize_t write(int fd, const void *buf, size_t count); 

write() writes up to count bytes to the file referenced by the file descriptor
fd from the buffer starting at
buf. POSIX requires that a read() which can be proved to occur after a
write() has returned returns the new data.  Note that not all file
systems are POSIX conforming.
On success, the number of bytes written are returned (zero indicates 
nothing was written).  On error, -1 is returned, and errno is set
appropriately.
If count is zero and the file descriptor refers to
a regular file, 0 may be returned, or an error could be detected.
For a special file, the results are not portable.
Other errors may occur, depending on the object connected to fd. 
SVr4, 4.3BSD, POSIX.1-2001.  Under SVr4 a write may be interrupted and return EINTR at any point,
not just before any data is written.
A successful return from write() does not make any guarantee that data has been committed to disk.
In fact, on some buggy implementations, it does not even guarantee
that space has successfully been reserved for the data.
The only way to be sure is to call fsync(2)
after you are done writing all your data.
Python 3 – input() function

06 Oct, 2020
In Python, we use input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function convert it into a string.
Syntax: input(prompt)
Parameter:
Prompt: (optional) The string that is written to standard output(usually screen) without newline.
Return: String object
Let’s see the examples:
Example 1: Taking input from the user.
Python3
# Taking input from the userstring = input() # Outputprint(string)
  Output:
geeksforgeeks



 
Example 2: Taking input from the user with a message.
Python
# Taking input from the username = input("Enter your name") # Outputprint("Hello", name)
  Output:
Enter your name:ankit rai
Hello ankit rai



 
Example 3: By default input() function takes the user’s input in a string. So, to take the input in the form of int you need to use int() along with the input function.
Python3
# Taking input from the user as integernum = int(input("Enter a number:"))add = num + 1 # Outputprint(add)
Output:
Enter a number:15
16

Example 4:  Let’s take float input along with the input function.
Python3
# Taking input from the user as float num =float(input("Enter number "))add = num + 1 # outputprint(add)
Output:
Enter number 5
6.0

Example 5: Let’s take list input along with the input function.
Python3
# Taking input from the user as list li =list(input("Enter number ")) # outputprint(li)
Output:
Enter number 12345
['1', '2', '3', '4', '5']

Example 6: Let’s take tuple input along with the input function.
Python3
# Taking input from the user as tuple num =tuple(input("Enter number ")) # outputprint(num)
Output:
Enter number 123
('1', '2', '3')

kumar_satyam
python-input-output
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
What is the use of `%p` in printf in C?

In C we have seen different format specifiers. Here we will see another format specifier called %p. This is used to print the pointer type data. Let us see the example to get a better idea.
#include<stdio.h>
main() {
   int x = 50;
   int *ptr = &x;
   printf("The address is: %p, the value is %d", ptr, *ptr);
}
The address is: 000000000022FE44, the value is 50
Python | Print number of leap years from given list of years

24 Sep, 2021
The problem of finding leap year is quite generic and we might face the issue of finding the number of leap years in given list of years. Let’s discuss certain ways in which this can be performed.
Method #1: Using Iteration Check whether year is a multiple of 4 and not multiple of 100 or year is multiple of 400. 
Python3
# Python code to finding number of# leap years in list of years. # Input list initializationInput = [2001, 2002, 2003, 2004, 2005, 2006,         2007, 2008, 2009, 2010, 2011, 2012] # Find whether it is leap year or notdef checkYear(year):    return (((year % 4 == 0) and             (year % 100 != 0)) or             (year % 400 == 0))  # Answer InitializationAnswer = 0 for elem in Input:    if checkYear(elem):        Answer = Answer + 1 # Printingprint("No of leap years are:", Answer)
No of leap years are: 3
 
Method #2: Using calendar  
Python3
# Python code to finding number of# leap years in list of years. # Importing calendarimport calendar # Input list initializationInput = [2001, 2002, 2003, 2004, 2005,         2006, 2007, 2008, 2009, 2010] # Using calendar to find leap yeardef FindLeapYear(Input):    ans = 0    for elem in Input:        if calendar.isleap(int(elem)):            ans = ans + 1    return ans Output = FindLeapYear(Input) # Printingprint("No of leap years are:", Output)
No of leap years are: 2
 
khushboogoyal499
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Defaultdict in Python
Python program to add two numbers
Python | Get dictionary keys as a list
Python Program for Fibonacci numbers
Python Program for factorial of a number
How to get or set the resolution of an image using imageresolution() function in PHP?

imageresoulution() is an inbuilt function in PHP that is used to get or set the resolution of an image in dots per inch. If no optional parameters are given, then the current resolution is returned as an indexed array. If one of the optional parameters is given, then it will set both the width and height to that parameter.
The resolution is only used as meta information when the images are read from and written to formats supporting this kind of information (currently PNG and JPEG). It does not affect any drawing operations. The 96 DPI (dots per inch) is the default resolution for new images.
mixed imageresolution(resource $image, int $res_x, int $res_y)
imageresolution() accepts three parameters: $image, $res_x, $res_y.
$image − Specifies the image resource to work on.
$image − Specifies the image resource to work on.
$res_x − Specifies the horizontal resolution in dots per inch (DPI).
$res_x − Specifies the horizontal resolution in dots per inch (DPI).
$res_y − Specifies the vertical resolution in dots per inch (DPI).
$res_y − Specifies the vertical resolution in dots per inch (DPI).
imageresolution() returns the indexed array of the image.
<?php
   $img = imagecreatetruecolor(100, 100);
   imageresolution($img, 200);
   print_r(imageresolution($img));
   imageresolution($img, 300, 72);
   print_r(imageresolution($img));
?>
Array
(
   [0] => 200
   [1] => 200
)
Array
(
   [0] => 300
   [1] => 72
)
<?php
   // Load the png image using imagecreatefrompng() function
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img34.png');
   
   // Set the image resolution
   imageresolution($img, 300, 100);
   
   // Get the image resolution
   $imageresolution = imageresolution($img);
   print("<pre>".print_r($imageresolution, true)."</pre>");
?>
Array
(
   [0] => 300
   [1] => 100
)
Python | Pandas DataFrame.dtypes

20 Feb, 2019
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). Arithmetic operations align on both row and column labels. It can be thought of as a dict-like container for Series objects. This is the primary data structure of the Pandas.
Pandas DataFrame.dtypes attribute return the dtypes in the DataFrame. It returns a Series with the data type of each column.
Syntax: DataFrame.dtypes
Parameter : None
Returns : dtype of each column
Example #1: Use DataFrame.dtypes attribute to find out the data type (dtype) of each column in the given dataframe.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],                   'Age':[14, 25, 55, 8, 21]})  # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :Now we will use DataFrame.dtypes attribute to find out the data type of each column in the given dataframe.
# return the dtype of each columnresult = df.dtypes  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.dtypes attribute has successfully returned the data types of each column in the given dataframe. Example #2: Use DataFrame.dtypes attribute to find out the data type (dtype) of each column in the given dataframe.
# importing pandas as pdimport pandas as pd  # Creating the DataFramedf = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                    "C":[20, 16, 11, 3, 8],                    "D":[14, 3, None, 2, 6]})   # Create the indexindex_ = ['Row_1', 'Row_2', 'Row_3', 'Row_4', 'Row_5']  # Set the indexdf.index = index_  # Print the DataFrameprint(df)
Output :
Now we will use DataFrame.dtypes attribute to find out the data type of each column in the given dataframe.
# return the dtype of each columnresult = df.dtypes  # Print the resultprint(result)
Output :As we can see in the output, the DataFrame.dtypes attribute has successfully returned the data types of each column in the given dataframe.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Separate odd and even index elements

20 May, 2021
Python list are quite popular and no matter what type of field one is coding, one has to deal with lists and its various applications. In this particular article, we discuss ways to separate odd and even indexed elements and its reconstruction join. Let’s discuss ways to achieve this. 
Method #1 : Using Naive methodUsing Naive method, this task can be performed by using the loops. One can use two containers one each to store alternate elements and later joining them.
Python3
# Python3 code to demonstrate# Separating odd and even index elements# using naive method # initializing listtest_list = [3, 6, 7, 8, 9, 2, 1, 5] # printing original listprint("The original list : " + str(test_list)) # using naive method# Separating odd and even index elementsodd_i = []even_i = []for i in range(0, len(test_list)):    if i % 2:        even_i.append(test_list[i])    else :        odd_i.append(test_list[i]) res = odd_i + even_i # print resultprint("Separated odd and even index list: " + str(res))
The original list : [3, 6, 7, 8, 9, 2, 1, 5]
Separated odd and even index list: [3, 7, 9, 1, 6, 8, 2, 5]
 Method #2 : Using list slicing This particular task can be easily performed using the list slicing method in a more compact and efficient manner, this is a recommended method to solve this problem.
Python3
# Python3 code to demonstrate# Separating odd and even index elements# Using list slicing # initializing listtest_list = [3, 6, 7, 8, 9, 2, 1, 5] # printing original listprint("The original list : " + str(test_list)) # Using list slicing# Separating odd and even index elementsres = test_list[::2] + test_list[1::2] # print resultprint("Separated odd and even index list : " + str(res))
The original list : [3, 6, 7, 8, 9, 2, 1, 5]
Separated odd and even index list : [3, 7, 9, 1, 6, 8, 2, 5]
akshaysingh98088
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use flex to shrink an image in CSS ?

30 Jul, 2021
You can easily shrink an image by using the flex-wrap property in CSS and it specifies whether flex items are forced into a single line or wrapped onto multiple lines. The flex-wrap property allows enabling the control direction in which lines are stacked. It is used to designate a single line or multi-line format to flex items inside the flex container. 
Syntax:
flex-wrap: wrap
Note: wrap is used to break the flex item into multiples lines. It makes flex items wrap to multiple lines according to flex item width.
Example: In order to shrink the image, you have to make the width of the image to 100%, so that image occupies 100% of the size of the <div>.
HTML
<!DOCTYPE html><html>  <head>    <style>        .container {            display: -webkit-flex;            -webkit-flex-wrap: wrap;            display: flex;            flex-wrap: wrap;            background-color: grey;        }          img {            width: 100%;        }          div {            flex: 1;            padding: 10px;            margin: 10px;        }    </style></head>  <body>    <div class="container">        <div class="image">            <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" />        </div>        <div class="image">            <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" />        </div>        <div class="image">            <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png" />        </div>    </div></body>  </html>
Output:
flex-wrap property
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Design a Tribute Page using HTML & CSS
Working with BigDecimal values in Java

The java.math.BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion.
Two types of operations are provided for manipulating the scale of a BigDecimal −
scaling/rounding operations
decimal point motion operations
The following are some of the constructors of the BigDecimal values −
The following is an example −
 Live Demo
import java.math.BigDecimal;
public class Demo {
   public static void main(String[] argv) throws Exception {
      BigDecimal val1 = new BigDecimal("37578975.8768");
      BigDecimal val2 = new BigDecimal("62567878.9768");
      BigDecimal val3 = new BigDecimal("72567874.3768");
      System.out.println("Value 1 : "+val1);
      System.out.println("Value 2 : "+val2);
      val1 = val1.add(val2);
      System.out.println("Addition Operation = " + val1);
      val1 = val1.multiply(val2);
      System.out.println("Multiplication Operation = " + val1);
      val2 = val3.subtract(val2);
      System.out.println("Subtract Operation = " + val2);
      val2 = val3.divide(val2,BigDecimal.ROUND_UP);
      System.out.println("Division Operation = " + val2);
   }
}
Value 1 : 37578975.8768
Value 2 : 62567878.9768
Addition Operation = 100146854.8536
Multiplication Operation = 6265976294387200.48179648
Subtract Operation = 9999995.4000
Division Operation = 7.2568
How to use BooleanSupplier in lambda expression in Java?

BooleanSupplier is a functional interface defined in the "java.util.function" package. This interface can be used as an assignment target for a lambda expression or method reference. BooleanSupplier interface has only one method getAsBoolean() and returns a boolean result, true or false.
@FunctionalInterface
public interface BooleanSupplier {
   boolean getBoolean();
}
import java.util.function.BooleanSupplier;

public class BooleanSupplierLambdaTest {
   public static void main(String[] args) {
      BooleanSupplier Obj1 = () -> true;
      BooleanSupplier Obj2 = () -> 5 < 50; // lambda expression
      BooleanSupplier Obj3 = () -> "tutorialspoint.com".equals("tutorix.com");
      System.out.println("Result of Obj1: " + Obj1.getAsBoolean());
      System.out.println("Result of Obj2: " + Obj2.getAsBoolean());
      System.out.println("Result of Obj3: " + Obj3.getAsBoolean());
   }
}
Result of Obj1: true
Result of Obj2: true
Result of Obj3: false
NumPy Searching Arrays

You can search an array for a certain value, and return the indexes that get a match.
To search an array, use the where() method.
Find the indexes where the value is 4:
The example above will return a tuple: (array([3, 5, 6],)
Which means that the value 4 is present at index 3, 5, and 6.
Find the indexes where the values are even:
Find the indexes where the values are odd:
There is a method called searchsorted() which performs a binary search in the array,
and returns the index where the specified value would be inserted to maintain the 
search order.
The searchsorted() method is assumed to be 
  used on sorted arrays.
Find the indexes where the value 7 should be inserted:
Example explained: The number 7 should be inserted on index 1 to remain the sort order.
The method starts the search from the left and returns the first index where the number 
7 is no longer larger than the next value.
By default the left most index is returned, but we can give side='right' to return the right most index instead.
Find the indexes where the value 7 should be inserted, starting from the 
right:
Example explained: The number 7 should be inserted on index 2 to remain the sort order.
The method starts the search from the right and returns the first index where the number 
7 is no longer less than the next value.
To search for more than one value, use an array with the specified values.
Find the indexes where the values 2, 4, and 6 should be inserted:
The return value is an array: [1 2 3] containing the three indexes where 2, 4, 6 would be inserted 
in the original array to maintain the order.
Use the correct NumPy method to find all items with the value 4.
arr = np.array([1, 2, 3, 4, 5, 4, 4])

x = np.(arr == 4)

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Dynamic Arrays and its Operations in Solidity

17 Nov, 2020
The Dynamic arrays are the arrays that are allocated memory at the runtime and the memory is allocated from the heap. 
Syntax:
// declaration of dynamic array
 int[] private arr;   
How They Are Different From Fixed Size Arrays?
The fixed-size array has a fixed memory size whereas, in dynamic arrays, the size can be randomly updated during the run time which may be considered efficient with respect to the memory complexity of the code. 
Problem: How to create a dynamic array in solidity and perform its associated operations?
Solution: In this article, we will create dynamic arrays in solidity language and will perform the following operations on it:
Add data in an arrayGet data of an arrayGet length of an arrayGet sum of elements of an arraySearch a particular element in an array
Add data in an array
Get data of an array
Get length of an array
Get sum of elements of an array
Search a particular element in an array
What is Solidity?
Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol.
What are Smart Contracts?
Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum.
Step 1: Open Remix-IDE.
Step 2: Select File Explorer from the left side icons and select Solidity in the environment. Click on the New option below the Solidity environment. Enter the file name as dynamicArray.sol and Click on the OK button.
Step 3: Enter the following Solidity Code. Select the same solidity version as in your code.
Solidity
// Solidity program to demonstrate// the above approachpragma solidity ^0.6.8;contract DynamicArray{    // Declaring state variable  int[] private arr;       // Function to add data // in dynamic arrayfunction addData(int num) public{  arr.push(num);}      // Function to get data of// dynamic arrayfunction getData() public view returns(int[] memory){  return arr;}      // Function to return length // of dynamic arrayfunction getLength() public view returns (uint){  return arr.length;}  // Function to return sum of // elements of dynamic arrayfunction getSum() public view returns(int){  uint i;  int sum = 0;      for(i = 0; i < arr.length; i++)    sum = sum + arr[i];  return sum;}      // Function to search an // element in dynamic arrayfunction search(int num) public view returns(bool){  uint i;      for(i = 0; i < arr.length; i++)  {    if(arr[i] == num)    {      return true;    }  }      if(i >= arr.length)    return false;}}
Step 4: Compile the file dynamicArray.sol from the Solidity Compiler tab.
Step 5: Deploy the smart contract from the Deploy and Run Transaction tab.
Step 6: Perform various operations on the array under the deployed contracts section.
Solidity-Arrays
Technical Scripter 2020
Solidity
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Check if dictionary is empty

During analysis of data sets we may come across situations where we have to deal with empty dictionaries. In tis article we will see how to check if a dictionary is empty or not.
The if condition evaluates to true if the dictionary has elements. Otherwise it evaluates to false. So in the below program we will just check the emptiness of a dictionary using only the if condition.
 Live Demo
dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
if dict1:
   print("dict1 is not empty")
else:
   print("dict1 is empty")
if dict2:
   print("dict2 is not empty")
else:
   print("dict2 is empty")
Running the above code gives us the following result −
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
dict1 is not empty
dict2 is empty
The bool method evaluates to true if the dictionary is not empty. Else it evaluates to false. So we use this in expressions to print the result for emptiness of a dictionary.
 Live Demo
dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
print("Is dict1 empty? :",bool(dict1))
print("Is dict2 empty? :",bool(dict2))
Running the above code gives us the following result −
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
Is dict1 empty? : True
Is dict2 empty? : False
Type Conversion in C++

Here we will see what are the type conversion techniques present in C++. There are mainly two types of type conversion. The implicit and explicit.
Implicit type conversionThis is also known as automatic type conversion. This is done by the compiler without any external trigger from the user. This is done when one expression has more than one datatype is present.All datatypes are upgraded to the datatype of the large variable.
Implicit type conversion
This is also known as automatic type conversion. This is done by the compiler without any external trigger from the user. This is done when one expression has more than one datatype is present.
All datatypes are upgraded to the datatype of the large variable.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double
In the implicit conversion, it may lose some information. The sign can be lost etc.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a = 10;
   char b = 'a';
   a = b + a;
   float c = a + 1.0;
   cout << "a : " << a << "\nb : " << b << "\nc : " << c;
}
a : 107
b : a
c : 108
This is also known as type casting. Here the user can typecast the result to make it to particular datatype. In C++ we can do this in two ways, either using expression in parentheses or using static_cast or dynamic_cast
 Live Demo
#include <iostream>
using namespace std;
int main() {
   double x = 1.574;
   int add = (int)x + 1;
   cout << "Add: " << add;
   float y = 3.5;
   int val = static_cast<int>(y);
   cout << "\nvalue: " << val;
}
Add: 2
value: 3
Matplotlib.axis.Axis.set_major_locator() function in Python

10 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_major_locator() function in axis module of matplotlib library is used to set the locator of the major ticker. 
Syntax: Axis.set_major_locator(self, locator)
Parameters: This method accepts the following parameters. 
locator: This parameter is the Locator.
Return value: This method does not returns any value. 
Below examples illustrate the matplotlib.axis.Axis.set_major_locator() function in matplotlib.axis:Example 1:
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.cbook as cbook     years = mdates.YearLocator()    months = mdates.MonthLocator()   years_fmt = mdates.DateFormatter('% Y')     with cbook.get_sample_data('goog.npz') as datafile:     data = np.load(datafile)['price_data'].view(np.recarray)         fig, ax = plt.subplots() ax.plot('date', 'adj_close', data = data, color ="green")     Axis.set_major_locator(ax.xaxis, years) ax.set_ylim((100, 300))     ax.format_xdata = mdates.DateFormatter('% m') ax.grid(True)    fig.suptitle("Matplotlib.axis.Axis.set_major_locator()\n\Function Example", fontsize = 12, fontweight ='bold')   plt.show()
Output: 
Example 2:
Python3
# Implementation of matplotlib function from matplotlib.axis import Axisimport matplotlib.pyplot as plt import matplotlib.ticker as ticker         x = [0, 5, 9, 10, 15] y = [0, 1, 2, 3, 4]     tick_spacing = 1    fig, ax = plt.subplots(1, 1) ax.plot(x, y) ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))   fig.suptitle("Matplotlib.axis.Axis.set_major_locator()\n\Function Example", fontsize = 12, fontweight ='bold')   plt.show()
Output: 
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to change the font size in HTML?

15 Mar, 2021
In this article, we will learn how one can change the font size in HTML. This can be used in situations where a text has to be highlighted due to its importance or made smaller for a caption. This can be achieved using the following approaches.
Approach 1: The <font> tag in HTML can be used for making changes to the font that is enclosed within the tags. It has various attributes that can be used to specify the size, color, or face of the font. This tag was deprecated in HTML5, therefore this approach may not work in modern browsers.
Syntax:
<font size="24">Your Text</font>
Example:
HTML
<html><body>  <!-- Using <font> tag to set font size -->  <font size="6">    Welcome to GeeksforGeeks  </font>  <font size="24">    Aman Rathod  </font></body></html>
Output:
Approach 2:  The <big> tag in HTML can be used for increasing the font size by one level that is enclosed within the tags. It does not have any attributes. This tag was deprecated in HTML5, therefore this approach may not work in modern browsers.
Syntax:
<big>Your Text</big>
Example:
HTML
<html><body>    <p>    <!-- Using the <big> tag for increasing    the font size -->    Welcome to <big>GeeksforGeeks</big>  </p>  </body></html>
Output:
Approach 3: Using the inline style attribute to change the font-size of the tag it is used on. The usage of this attribute overrides any style set globally.
Syntax:
<p style="font-size: 24px;">Your Text</p>
Example:
HTML
<html><body>  <!--- Using Inline style  attribute to edit font size -->  <p style="font-size:20px">    GeeksforGeeks  </p>    <p style="font-size:25px">    Courses  </p>  </body></html>
Output:
Approach 4: Using separate CSS to select the required text and using the font-size property to change the font size. The size value can be set using length units or keywords like x-small, small or large.
Syntax:
<style>
p
{
  font-size: large;
}
</style>
Example:
HTML
<html><head>      <!-- Using CSS to change  the font size -->  <style>    body {        font-size: 60px;    }      p {      font-size:xx-large;    }    </style>  </head><body>  Perfect Portal for Geeky    <p>Welcome to GeeksforGeeks</p>  </body></html>
Output:
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Java Program to Count Primes in Ranges

13 Jan, 2022
Given a range [L, R], we need to find the count of total numbers of prime numbers in the range [L, R] where 0 <= L <= R < 10000. Consider that there are a large number of queries for different ranges.Examples:  
Input : Query 1 : L = 1, R = 10
        Query 2 : L = 5, R = 10
Output : 4
         2
Explanation
Primes in the range L = 1 to R = 10 are 
{2, 3, 5, 7}. Therefore for query, answer 
is 4 {2, 3, 5, 7}.
For the second query, answer is 2 {5, 7}.
 
A simple solution is to do the following for every query [L, R]. Traverse from L to R, check if current number is prime. If yes, increment the count. Finally, return the count.An efficient solution is to use Sieve of Eratosthenes to find all primes up to the given limit. Then we compute a prefix array to store counts till every value before limit. Once we have a prefix array, we can answer queries in O(1) time. We just need to return prefix[R] – prefix[L-1].  
Java
// Java program to answer queries for // count of primes in given range.import java.util.*;  class GFG {      static final int MAX = 10000;  // prefix[i] is going to store count // of primes till i (including i).static int prefix[] = new int[MAX + 1];  static void buildPrefix() {          // Create a boolean array "prime[0..n]". A    // value in prime[i] will finally be false    // if i is Not a prime, else true.    boolean prime[] = new boolean[MAX + 1];    Arrays.fill(prime, true);      for (int p = 2; p * p <= MAX; p++) {      // If prime[p] is not changed, then    // it is a prime    if (prime[p] == true) {          // Update all multiples of p        for (int i = p * 2; i <= MAX; i += p)        prime[i] = false;    }    }      // Build prefix array    prefix[0] = prefix[1] = 0;    for (int p = 2; p <= MAX; p++) {    prefix[p] = prefix[p - 1];    if (prime[p])        prefix[p]++;    }}  // Returns count of primes in range // from L to R (both inclusive).static int query(int L, int R){    return prefix[R] - prefix[L - 1]; }  // Driver codepublic static void main(String[] args) {          buildPrefix();    int L = 5, R = 10;    System.out.println(query(L, R));      L = 1; R = 10;    System.out.println(query(L, R));}}  // This code is contributed by Anant Agarwal.
Output:  
2
4
Please refer complete article on Count Primes in Ranges for more details!
array-range-queries
prefix-sum
Prime Number
sieve
Java
Java Programs
Mathematical
prefix-sum
Mathematical
Prime Number
Java
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
How to Create User in Oracle Database ?

28 Oct, 2021
In oracle there are different type of user accounts system, sys, hr and many more. This user accounts is by default created by oracle .If you want to create your own user then you can create it by two different methods.
Step 1. Login to your database as normally you would by username and password.
Step 2. Use create user command and specify username, password as you want.
Syntax:
CREATE USER user_name IDENTIFIED BY password ;
Here ‘Geeks’ is user_name and ‘Geeks123’ is  password for this user_name .create and user both are the keywords followed by username.
New user ‘Geeks’ is created and which is identified by password ‘Geeks123’ .
Output:
Step 3. You can check that user is created or not in your database by simply login as shown. here we logged in successfully with new username and password. Now you can grant the role and privileges to your new user by using grant command.
Step 1. Login into your oracle database.
Step 2. Go to administration option and then go to database user option now database users is appear as shown.
Step 3. Click on the create option present on right side. As you see create database user window now create new user and set password for that user.
Step 4. Type username as you want and password for that username. confirm the password and if you want that  password is expired after some time so than you can change it so you can check the expire password box .you can also set account status lock/unlock according to privacy and give the role and privileges according to the user.
Step 5. After completion click on create option .Now you get a confirmation message that user is created in your database and you can also see that new user ‘Newgeeks’ is added in the list as shown.
surindertarika1234
Oracle
SQL-basics
SQL
Oracle
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL | DROP, TRUNCATE
How to convert array of strings to array of numbers in JavaScript ?

22 Jun, 2021
In this article, we have given an array of strings and the task is to convert it into an array of numbers in JavaScript.
Input: ["1","2","3","4","5"]
Output: [1,2,3,4,5]

Input: ["10","21","3","14","53"]
Output: [10,21,3,14,53]
There are two methods to do this, which are given below:
Method 1: Array traversal and typecasting: In this method, we traverse an array of strings and add it to a new array of numbers by typecasting it to an integer using the parseInt() function.
Javascript
<script>      // Create an array of string    var stringArray = ["1", "2", "3", "4", "5"];      // Create an empty array of number    var numberArray = [];      // Store length of array of string    // in variable length    length = stringArray.length;      // Iterate through array of string using    // for loop    // push all elements of array of string    // in array of numbers by typecasting    // them to integers using parseInt function    for (var i = 0; i < length; i++)          // Instead of parseInt(), Number()        // can also be used        numberArray.push(parseInt(stringArray[i]));      // Print the array of numbers    console.log(numberArray);</script>
Output:
[1, 2, 3, 4, 5]
Method 2: Using map() method of JavaScript: In this method, we use the array map method of JavaScript.
Javascript
<script>    // Create an array of string    var stringArray = ["10", "21", "3", "14", "53"];      // Create a numberArray and using    // map function iterate over it    // and push it by typecasting into    // int using Number    var numberArray = stringArray.map(Number);      // Print the array of numbers    console.log(numberArray);</script>
Output:
[10, 21, 3, 14, 53]
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Stack iterator() method in Java with Example

24 Dec, 2018
The Java.util.Stack.iterator() method is used to return an iterator of the same elements as that of the Stack. The elements are returned in random order from what was present in the stack.
Syntax:
Iterator iterate_value = Stack.iterator();

Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the stack and returns the values(iterators).
Below program illustrates the use of Java.util.Stack.iterator() method:
Example 1:
// Java code to illustrate iterator()  import java.util.*;import java.util.Stack;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<String> stack = new Stack<String>();          // Use add() method to add elements into the Stack        stack.add("Welcome");        stack.add("To");        stack.add("Geeks");        stack.add("4");        stack.add("Geeks");          // Displaying the Stack        System.out.println("Stack: " + stack);          // Creating an iterator        Iterator value = stack.iterator();          // Displaying the values        // after iterating through the stack        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
Stack: [Welcome, To, Geeks, 4, Geeks]
The iterator values are: 
Welcome
To
Geeks
4
Geeks

Example 2:
// Java code to illustrate hashCode()  import java.util.*;  public class StackDemo {    public static void main(String args[])    {        // Creating an empty Stack        Stack<Integer> stack            = new Stack<Integer>();          // Use add() method        // to add elements into the Stack        stack.add(10);        stack.add(20);        stack.add(30);        stack.add(40);        stack.add(50);          // Displaying the Stack        System.out.println("Stack: " + stack);          // Creating an iterator        Iterator value = stack.iterator();          // Displaying the values        // after iterating through the stack        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
Stack: [10, 20, 30, 40, 50]
The iterator values are: 
10
20
30
40
50

Java - util package
Java-Collections
Java-Functions
Java-Stack
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Explain serial execution or transaction with an example(DBMS)

There are three possible ways in which a transaction can be executed. These are as follows −
Serial execution − In serial execution, the second transaction can begin its execution only after the first transaction has completed. This is possible on a uniprocessor system.
Serial execution − In serial execution, the second transaction can begin its execution only after the first transaction has completed. This is possible on a uniprocessor system.
Parallel execution − In parallel execution, two transactions can start their execution at exactly the same instant of time. For this, we require more than one processor.
Parallel execution − In parallel execution, two transactions can start their execution at exactly the same instant of time. For this, we require more than one processor.
Concurrent execution − In concurrent execution, execution of the second process can begin even before the process has completed its execution.
Concurrent execution − In concurrent execution, execution of the second process can begin even before the process has completed its execution.
Let us consider two transactions T1 and T2. In concurrent execution, the CPU executes some instructions of transaction T1, then moves to the second transaction and executes its instructions for some time and again it comes back to the first transaction.
The cycle is repeated until all the instructions of both the transactions are executed. The process is called context switching.
Given below is an example of serial execution −
Let us consider two transactions T1 and T2 where T1 performs transfer Rs.150 from account A to account B and similarly T2 transfers 10% of balance from A to B.
  T1               T2
  Read(A)        Read(A)
  A=A-150        temp =0.1 *A
  Write(A)       A=A-temp
  Read(B)        Write(A)
  B=B+150        Read(B)
  Write(B)      B=B+temp
                 Write(B)
The order in which the instructions of transaction T1 and T2 are executed is called a Schedule.
The possible serial schedules are as follows −
Let A= 200, B=200
Schedule S1 and S2 keeps the database in consistent state.
In general if the system consists of n number of transactions, then we can generate n! number of valid serial schedules.
Decode String in C++

Suppose we have an encoded string; we have to return its decoded string. The rule for encoding is: k[encoded_string], this indicates where the encoded_string inside the square brackets is being repeated exactly k times. We can assume that the original data does not contain any numeric characters and that digits are only for those repeat numbers, k. So if the input is like “1[ba]2[na]”, then the output will be “banana”.
To solve this, we will follow these steps −
create one empty stack, set i := 0
while i < size of a stringif s[i] is ‘]’res := delete element from the stack and take only the string that is inside the square brackets.n := 0while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as nfor j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stackotherwise insert s[i] into the stackincrease i by 1
if s[i] is ‘]’res := delete element from the stack and take only the string that is inside the square brackets.n := 0while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as nfor j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stack
res := delete element from the stack and take only the string that is inside the square brackets.
n := 0
while stack is not empty, and stack top is one numeric character, then accommodate the numbers and form the actual integer as n
for j in range 1 to nfor x in range 0 to size of resinsert res[x] into the stack
for x in range 0 to size of resinsert res[x] into the stack
insert res[x] into the stack
otherwise insert s[i] into the stack
increase i by 1
ans := an empty string
while stack is not emptyans := stack top element + anspop from stack
ans := stack top element + ans
pop from stack
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string decodeString(string s) {
      stack <char> st;
      int i = 0;
      while(i<s.size()){
         if(s[i] == ']'){
            string res = "";
            while(st.top()!='['){
               res = st.top() + res;
               st.pop();
            }
            st.pop();
            int n = 0;
            int x = 1;
            while(!st.empty() && st.top()>='0' && st.top()<='9'){
               n = n + (st.top()-'0')*x;
               x*=10;
               st.pop();
            }
            for(int j = 1; j <= n; j++){
               for(int x = 0; x < res.size();x++){
                  st.push(res[x]);
               }
            }
         }
         else{
            st.push(s[i]);
         }
         i++;
      }
      string ans ="";
      while(!st.empty()){
         ans = st.top() + ans;
         st.pop();
      }
      return ans;
   }
};
main(){
   Solution ob;
   cout << ob.decodeString("1[ba]2[na]");
}
"1[ba]2[na]"
"banana"
LISP - Bitwise Operators

Bitwise operators work on bits and perform bit-by-bit operation. The truth tables for bitwise and, or, and xor operations are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A and B = 0000 1100
A or B = 0011 1101
A xor B = 0011 0001
not A  = 1100 0011
The Bitwise operators supported by LISP are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Create a new source code file named main.lisp and type the following code in it.
(setq a 60)
(setq b 13)

(format t "~% BITWISE AND of a and b is ~a" (logand a b))
(format t "~% BITWISE INCLUSIVE OR of a and b is ~a" (logior a b))
(format t "~% BITWISE EXCLUSIVE OR of a and b is ~a" (logxor a b))
(format t "~% A NOT B is ~a" (lognor a b))
(format t "~% A EQUIVALANCE B is ~a" (logeqv a b))

(terpri)
(terpri)

(setq a 10)
(setq b 0)
(setq c 30)
(setq d 40)

(format t "~% Result of bitwise and operation on 10, 0, 30, 40 is ~a" (logand a b c d))
(format t "~% Result of bitwise or operation on 10, 0, 30, 40 is ~a" (logior a b c d))
(format t "~% Result of bitwise xor operation on 10, 0, 30, 40 is ~a" (logxor a b c d))
(format t "~% Result of bitwise eqivalance operation on 10, 0, 30, 40 is ~a" (logeqv a b c d))
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
BITWISE AND of a and b is 12
BITWISE INCLUSIVE OR of a and b is 61
BITWISE EXCLUSIVE OR of a and b is 49
A NOT B is -62
A EQUIVALANCE B is -50

Result of bitwise and operation on 10, 0, 30, 40 is 0
Result of bitwise or operation on 10, 0, 30, 40 is 62
Result of bitwise xor operation on 10, 0, 30, 40 is 60
Result of bitwise eqivalance operation on 10, 0, 30, 40 is -61


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page