code-rag-bench/online-tutorials huggingface dataset:
Python | Convert Bytearray to Hexadecimal String - GeeksforGeeks

27 Jun, 2019
Sometimes, we might be in a problem in which we need to handle the unusual datatype conversions. One such conversion can be converting the list of bytes(bytearray) to the Hexadecimal string format. Let’s discuss certain ways in which this can be done.
Method #1 : Using format() + join()The combination of above functions can be used to perform this particular task. The format function converts the bytes in hexadecimal format. “02” in format is used to pad required leading zeroes. The join function allows to join the hexadecimal result into a string.
# Python3 code to demonstrate working of# Converting bytearray to hexadecimal string# Using join() + format()  # initializing list test_list = [124, 67, 45, 11]  # printing original list print("The original string is : " + str(test_list))  # using join() + format()# Converting bytearray to hexadecimal stringres = ''.join(format(x, '02x') for x in test_list)  # printing result print("The string after conversion : " + str(res))
The original string is : [124, 67, 45, 11]
The string after conversion : 7c432d0b

 
Method #2 : Using binascii.hexlify()The inbuilt function of hexlify can be used to perform this particular task. This function is recommended for this particular conversion as it is tailormade to solve this specific problem.
# Python3 code to demonstrate working of# Converting bytearray to hexadecimal string# Using binascii.hexlify()import binascii  # initializing list test_list = [124, 67, 45, 11]  # printing original list print("The original string is : " + str(test_list))  # using binascii.hexlify()# Converting bytearray to hexadecimal stringres = binascii.hexlify(bytearray(test_list))  # printing result print("The string after conversion : " + str(res))
The original string is : [124, 67, 45, 11]
The string after conversion : 7c432d0b

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Get the day from a date in Pandas - GeeksforGeeks

09 Dec, 2021
Given a particular date, it is possible to obtain the day of the week on which the date falls. This is achieved with the help of Pandas library and the to_datetime() method present in pandas. In most of the datasets the Date column appears to be of the data type String, which definitely isn’t comfortable to perform any calculations with that column, such as the difference in months between 2 dates, the difference in time or finding the day of the week. Hence Pandas provides a method called to_datetime() to convert strings into Timestamp objects.Examples :  
We'll use the date format 'dd/mm/yyyy'

Input :  '24/07/2020' 
Output : 'Friday' 

Input : '01/01/2001'
Output : 'Monday' 
Once we convert a date in string format into a date time object, it is easy to get the day of the week using the method day_name() on the Timestamp object created.Example 1 : In this example, we pass a random date with the type ‘str’ and format ‘dd/mm/yyyy’ to the to_datetime() method . As a result we get a Timestamp pandas object. Then we retrieve the day of the week by the Timestamp class’s day_name() method. 
Python3
# importing the moduleimport pandas as pd # the date in "dd/mm/yyyy" formatdate = "19/02/2022"print("Initially the type is : ", type(date)) # converting string to DateTimedate = pd.to_datetime(date, format = "%d/%m/%Y")print("After conversion, the type is : ", type(date)) # fetching the dayprint("The day is : " + date.day_name())
Output :  
Example 2 : In the below example, dates of different formats have been converted to a Timestamp object and then their respective days of the week are retrieved using day_name() method .  
Python3
# importing the moduleimport pandas as pd # 'dd-mm-yyyy'date_1 = '22-07-2011' date_1 = pd.to_datetime(date_1, format ="%d-%m-%Y") print("The day on the date " + str(date_1) +      " is : " + date_1.day_name()) # 'mm.dd.yyyy'date_2 = '12.03.2000' date_2 = pd.to_datetime(date_2, format ="%m.%d.%Y")print("The day on the date " + str(date_2) +      " is : " + date_2.day_name()) # 'yyyy / dd / mm'date_3 = '2004/9/4'   date_3 = pd.to_datetime(date_3, format ="%Y/%d/%m")print("The day on the date " + str(date_2) +      " is : " + date_3.day_name())
Output :  
 
surindertarika1234
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python program for arranging the students according to their marks in descending order - GeeksforGeeks

20 Aug, 2020
Consider a class of 20 students whose names and marks are given to you. The task is to arrange the students according to their marks in decreasing order. Write a python program to perform the task.
Examples:
Input:
Arun: 78%
Geeta: 86%
Shilpi: 65%

Output: 
Geeta: 86%
Arun: 78%
Shilpi: 65%



Approach: Since problem states that we need to collect student name and their marks first so for this we will take inputs one by one in the list data structure then sort them in reverse order using sorted() built-in function based on the student’s percentage and in the last we will print the value accordingly.
Below is the implementation:
Python3
print("-----Program for printing student name with marks using list-----")  # create an empty dictionaryD = {}  n = int(input('How many student record you want to store?? '))  # create an empty list# Add student information to the listls = []  for i in range(0, n):          # Take combined input name and     # percentage and split values     # using split function.    x,y = input("Enter the student name and it's percentage: ").split()          # Add name and marks stored in x, y    # respectively using tuple to the list    ls.append((y,x))      # sort the elements of list# based on marksls = sorted(ls, reverse = True)  print('Sorted list of students according to their marks in descending order')  for i in ls:        # print name and marks stored in     # second and first position     # respectively in list of tuples.    print(i[1], i[0])
Output:
-----Program for printing student name with marks using list-----
How many student record you want to store?? 3
Enter the student name and percentage: Arun: 78%
Enter the student name and percentage: Geeta: 86%
Enter the student name and percentage: Shilpi: 65%
Sorted list of students according to their marks in descending order
Geeta: 86%
Arun: 78%
Shilpi: 65%



school-programming
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Program to define various types of constants in C# - GeeksforGeeks

22 Jun, 2020
As in other programming languages, various types of constants are defined the same as defined in C#, we can also define various types of constants and print their values. They are fixed in values in the program. There can be any types of constants like integer, character constants, float, double, string, octal, hexadecimal, etc.
Define constant: By using const keyword a constant can be defined. Its value can never be changed once it is defined.
Syntax:
const data_type constant_name = value;

Example:
Input: const int a = 15;  
Output: a: 15

Example 1:
// C# program to define different types of constants using System;using System.Text;   namespace Geeks{    class GFG    {        // Main Method         static void Main(string[] args)        {            // integer constant            const int A = 15;                            // float constant            const float B = 50.83f;                        // to print above values            Console.WriteLine("A: {0}", A);            Console.WriteLine("B: {0}", B);                       }    }}
Output:
A: 15
B: 50.83

Example 2:
// C# program to define different types of constants using System;using System.Text;   namespace Geeks{    class GFG    {        // Main Method         static void Main(string[] args)        {            // character constant             const char C = 'S';                          // double constant            const double D = 70.23;                          // string constant            const string E = "Geeks";                  // to print above values            Console.WriteLine("C: {0}", C);            Console.WriteLine("D: {0}", D);            Console.WriteLine("E: {0}", E);           }    }}
Output:
C: S
D: 70.23
E: Geeks

C#
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Convert String to Character Array in C#
Program to Print a New Line in C#
Getting a Month Name Using Month Number in C#
Socket Programming in C#
C# Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Difference between HLookup and VLookup - GeeksforGeeks

09 Mar, 2021
HLookup :Horizontal Lookup function is called as HLookup function. This function used to find values horizontally across a set of rows in a table. It looks for a value horizontally across the lookup table. It returns an approximate or exact value based on the row number given in Excel. VLookup function provides the same lookup value as HLookup function provides.
Syntax of HLookup : 
HLOOKUP(lookup_value, table_array, row_index_num, [range_lookup]).
VLookup :Vertical Lookup function is called as VLookup function. This function is used to find values vertically across a set of rows in a table. It looks for a value vertically across the lookup table.  It returns an exact or approximate value based on the column number given in Excel. 
Syntax of VLookup : 
VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup]).
Difference between HLookup and VLookup :
S.NO.
HLOOKUP
VLOOKUP
Difference Between
Software Engineering
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
Difference Between Method Overloading and Method Overriding in Java
Difference between Prim's and Kruskal's algorithm for MST
Difference between Internal and External fragmentation
Difference between Compile-time and Run-time Polymorphism in Java
Types of Software Testing
Software Engineering | COCOMO Model
Functional vs Non Functional Requirements
Software Engineering | Coupling and Cohesion
Software Engineering | Spiral Model
How to open a link in new tab using Selenium WebDriver?

We can open a link in the new tab with Selenium. . The methods Keys.chord and sendKeys can be used for this. The Keys.chord method allows you to pass multiple keys simultaneously.
We shall send Keys.CONTROL and Keys.ENTER as arguments to the Keys.chord method. Then the complete string is then passed as an argument to the sendKeys method. Finally, the sendKeys method has to be applied on the link which is identified by driver.findElement method.
String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Privacy Policy']")). sendKeys(clicklnk);
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class OpenInNwTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // Keys.Chord string
      String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      driver.findElement(
      By.xpath("//*[text()='Privacy Policy']")).sendKeys(clicklnk);
   }
}
How to convert NaN to NA in an R data frame?

To convert NaN to NA in an R data frame, we can set the NaN values to NA values by using single square brackets. Firstly, we would need to access the column that contains NaN values then NaN values will be accessed using is.nan then we can set those values to NA as shown in the below examples.
Consider the below data frame −
 Live Demo
x1<-sample(c(1,2,5,NaN),20,replace=TRUE)
x2<-rpois(20,2)
df1<-data.frame(x1,x2)
df1
   x1  x2
1  5   1
2  1   2
3  5   3
4  NaN 2
5  5   1
6  5   2
7  NaN 1
8  5   4
9  5   2
10 2   0
11 NaN 0
12 1   0
13 NaN 4
14 1   2
15 5   1
16 1   2
17 2   2
18 5   0
19 2   1
20 5   1
Replacing NaN with NA in column x1 of df1 −
df1$x1[is.nan(df1$x1)]<-NA
df1
   x1 x2
1  5   1
2  1   2
3  5   3
4  NA  2
5  5   1
6  5   2
7  NA  1
8  5   4
9  5   2
10 2   0
11 NA  0
12 1   0
13 NA  4
14 1   2
15 5   1
16 1   2
17 2   2
18 5   0
19 2   1
20 5   1
 Live Demo
y1<-sample(c(rnorm(2),NaN),20,replace=TRUE)
y2<-rnorm(20)
y3<-rnorm(20)
df2<-data.frame(y1,y2,y3)
df2
       y1         y2          y3
1  -0.0867355  -1.28729227   -0.20581922
2  NaN          1.11408057    0.56750161
3  NaN          0.47302790   -0.72410253
4  NaN         -0.34217866    0.33855658
5  NaN         -2.52516598    0.78809964
6  -0.0867355  -0.65268724   -0.04150251
7  -0.0867355   0.42845639   -0.12955272
8  -0.0867355   0.71995182    0.24011099
9  -0.0867355   0.07829339    3.10334568
10 -0.9135175   0.07250105   -0.41307585
11 -0.0867355   1.58477752    0.96751855
12 NaN         -1.84389126   -0.42843257
13 -0.0867355  -0.10860452   -0.32978319
14 -0.9135175  -1.25311587   -1.07537515
15 -0.0867355   0.58514141    2.05516953
16 NaN          2.02405825    0.18098639
17 -0.9135175   0.90327161   -0.22561346
18 -0.9135175   0.81260538   -1.98065156
19 NaN         -1.60608848   -1.39970818
20 NaN         -0.82239927   -1.45993348
Replacing NaN with NA in column y1 of df2 −
df2$y1[is.nan(df2$y1)]<-NA
df2
        y1          y2           y3
1   -0.0867355  -1.28729227   -0.20581922
2  NA            1.11408057    0.56750161
3  NA            0.47302790   -0.72410253
4  NA           -0.34217866    0.33855658
5  NA           -2.52516598    0.78809964
6  -0.0867355   -0.65268724   -0.04150251
7  -0.0867355    0.42845639   -0.12955272
8  -0.0867355    0.71995182    0.24011099
9  -0.0867355    0.07829339    3.10334568
10 -0.9135175    0.07250105   -0.41307585
11 -0.0867355    1.58477752    0.96751855
12 NA           -1.84389126   -0.42843257
13 -0.0867355   -0.10860452   -0.32978319
14 -0.9135175   -1.25311587   -1.07537515
15 -0.0867355    0.58514141    2.05516953
16 NA            2.02405825    0.18098639
17 -0.9135175    0.90327161   -0.22561346
18 -0.9135175    0.81260538   -1.98065156
19 NA           -1.60608848   -1.39970818
20 NA           -0.82239927   -1.45993348
Adding a Character as Thousands Separator to Given Number in Java - GeeksforGeeks

04 Nov, 2020
Given an integer n and character ch, return a String using the character as thousands separator on the given number.
Examples:
Input: n=1234 , ch =’.’
Output: 1.234 
In the above-given input, “.” character is used as the thousands separator and is placed between hundreds and thousands of places starting from the right. The obtained output is returned as String Format.
Input: n=123456789 , ch =’.’
Output: 123.456.789
Approach: 
Convert number into a string.Start string traversal from the right side.Add the separator character after every three digits
Convert number into a string.
Start string traversal from the right side.
Add the separator character after every three digits
Below is the code using the same approach using Java. 
Java
// Java Program for Adding a character as thousands separator// to the given number and returning in string format  class GFG {      static String thousandSeparator(int n, String ch)    {          // Counting number of digits        int l = (int)Math.floor(Math.log10(n)) + 1;        StringBuffer str = new StringBuffer("");        int count = 0;        int r = 0;          // Checking if number of digits is greater than 3        if (l > 3) {              for (int i = l - 1; i >= 0; i--) {                  r = n % 10;                n = n / 10;                count++;                if (((count % 3) == 0) && (i != 0)) {                      // Parsing String value of Integer                    str.append(String.valueOf(r));                      // Appending the separator                    str.append(ch);                }                else                    str.append(String.valueOf(r));            }            str.reverse();        }          // If digits less than equal to 3, directly print n        else            str.append(String.valueOf(n));          return str.toString();    }      // Driver code    public static void main(String[] args)    {          int n = 123456789;        String ch = ".";        System.out.println(thousandSeparator(n, ch));    }}
123.456.789


Time Complexity: O(n)
Java-String-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Different ways of Reading a text file in Java
Constructors in Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
LinkedList in Arduino

The LinkedList library by Ivan Seidel helps implement this data structure in Arduino. A linked list contains a set of nodes wherein each node contains some data, and a link (reference) to the next node in the list.
To install this library, go to Library Manager, and search for LinkedList.
Once installed, go to: File→ Examples→LinkedList and open the SimpleIntegerList example.
Much of the code is self-explanatory. We include the library and create the object, specifying integer as the data type.
#include <LinkedList.h>
LinkedList<int> myList = LinkedList<int>();
Within setup, we populate the list with some integers, using the .add() function.
void setup()
{
   Serial.begin(9600);
   Serial.println("Hello!");

   // Add some stuff to the list
   int k = -240,
      l = 123,
      m = -2,
      n = 222;
   myList.add(n);
   myList.add(0);
   myList.add(l);
   myList.add(17);
   myList.add(k);
   myList.add(m);
}
In the loop, we print the size of the list, using the .size() function, and get each successive element using the .get() function. If the value of that element is less than 0, we print it.
void loop() {
   int listSize = myList.size();

   Serial.print("There are ");
   Serial.print(listSize);
   Serial.print(" integers in the list. The negative ones are: ");

   // Print Negative numbers
   for (int h = 0; h < listSize; h++) {

      // Get value from list
      int val = myList.get(h);

      // If the value is negative, print it
      if (val < 0) {
         Serial.print(" ");
         Serial.print(val);
      }
   }

   while (true); // nothing else to do, loop forever
}
When run on the Serial Monitor, the output is −
As you can see, this one is quite straightforward. You are encouraged to go through the other examples that come in with this library as well.
List vs tuple vs dictionary in Python

List and Tuple objects are sequences. A dictionary is a hash table of key-value pairs. List and tuple is an ordered collection of items. Dictionary is unordered collection.
List and dictionary objects are mutable i.e. it is possible to add new item or delete and item from it. Tuple is an immutable object. Addition or deletion operations are not possible on tuple object.
Each of them is a collection of comma-separated items. List items are enclosed in square brackets [], tuple items in round brackets or parentheses (), and dictionary items in curly brackets {}
>>> L1=[12, "Ravi", "B.Com FY", 78.50] #list
>>> T1=(12, "Ravi", "B.Com FY", 78.50)#tuple
>>> D1={"Rollno":12, "class":"B.com FY", "precentage":78.50}#dictionary
List and tuple items are indexed. Slice operator allows item of certain index to be accessed
>>> print (L1[2])
B.Com FY
>>> print (T1[2])
B.Com FY
Items in dictionary are not indexed. Value associated with a certain key is obtained by putting in square bracket. The get() method of dictionary also returns associated value.
>>> print (D1['class'])
B.com FY
>>> print (D1.get('class'))
B.com FY
Collect.js | transform() Function - GeeksforGeeks

04 Jun, 2020
The transform() function iterates over a collection and callback each item in the collection, the items inside the collection are replaced by the new callback values. It is similar to the JavaScript map() function but the values got replaced in transform() function.In JavaScript, the array is first converted to a collection and then the function is applied to the collection.
Syntax:
data.transform(item, key)
Parameters: This function accepts two parameter as mentioned above and described below:
item: This parameter holds the collection item.
key: This parameter holds new operational value.
Return Value: Returns an modified array which is created by this function.
Below examples illustrate the transform() function in collect.js
Example 1: Here in this example, we take a collection and then using the transform() function modified the values using the key transformation parameter and return the new value.
// It is used to import collect.js libraryconst collect = require('collect.js');  const data= collect([1, 2, 3, 4, 5]);  data.transform((item, key) => item * 5);  console.log(data.all());
Output:
[5 , 10 , 15 , 20 , 25 ]
Example 2: Same thing we have done here as above example.
// It is used to import collect.js libraryconst collect = require('collect.js');  const x= collect([10, 20, 30, 40, 50]);  x.transform((item, key) => item / 10);  console.log(x.all());
Output:
[1 , 2 , 3 , 4 , 5 ]
Reference: https://collect.js.org/api/transform.html
akhilsharma870
Collect.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
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
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?
Create a legend with Pandas and Matplotlib.pyplot

To create a legend with Pandas and matplotib.pyplot(), we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a two-dimensional, size-mutable, potentially heterogeneous tabular data.
Plot the dataframe instance with bar class by name and legend is True.
To display the figure, use show() method.
import pandas as pd
from matplotlib import pyplot as plt

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

fig, ax = plt.subplots()

df = pd.DataFrame({'Numbers': [3, 4, 1, 7, 8, 5], 'Frequency': [2, 4, 1, 4, 3, 2]})
df.plot(ax=ax, kind='bar', legend=True)

plt.show()
Explain the concept of Uninitialized array accessing in C language

In C language, is the program executed, if we use an uninitialized array?
If we use any uninitialized array, compiler will not generate any compilation and an execution error.
If we use any uninitialized array, compiler will not generate any compilation and an execution error.
If an array is uninitialized, you may get unpredictable result.
If an array is uninitialized, you may get unpredictable result.
So, it’s better we should always initialize the array elements with default values.
So, it’s better we should always initialize the array elements with default values.
Following is the C program of accessing an uninitialized array −
 Live Demo
#include <stdio.h>
int main(void){
   int a[4];
   int b[4] = {1};
   int c[4] = {1,2,3,4};
   int i; //for loop counter
   //printing all alements of all arrays
   printf("\nArray a:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i,a[i]);
   printf("\nArray b:\n");
   for( i=0; i<4; i++)
      printf("arr[%d]: %d\n",i,b[i]);
   printf("\nArray c:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i, c[i]);
   return 0;
}
When the above program is executed, it produces the following result −
Array a:
arr[0]: 4195872
arr[1]: 0
arr[2]: 4195408
arr[3]: 0

Array b:
arr[0]: 1
arr[1]: 0
arr[2]: 0
arr[3]: 0

Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 3
arr[3]: 4
If we didn’t initialize an array, by default, it prints garbage values and never show an error.
Consider another C program for accessing an uninitialized array −
 Live Demo
#include <stdio.h>
int main(void){
   int A[4];
   int B[4] ;
   int C[4] = {1,2};
   int i; //for loop counter
   //printing all alements of all arrays
   printf("\nArray a:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i,A[i]);
   printf("\nArray b:\n");
   for( i=0; i<4; i++)
      printf("arr[%d]: %d\n",i,B[i]);
   printf("\nArray c:\n");
   for( i=0; i<4; i++ )
      printf("arr[%d]: %d\n",i, C[i]);
   return 0;
}
When the above program is executed, it produces the following result −
Array a:
arr[0]: 4195856
arr[1]: 0
arr[2]: 4195408
arr[3]: 0

Array b:
arr[0]: -915120393
arr[1]: 32767
arr[2]: 0
arr[3]: 0

Array c:
arr[0]: 1
arr[1]: 2
arr[2]: 0
arr[3]: 0
Program to find last digit of n’th Fibonnaci Number in C++

In this problem, we are given a number N. Our task is to create a Program to find last digit of Nth Fibonacci number in C++.
We need to find the last digit (i.e. LSB ) of the Nth Fibonacci number.
Let’s take an example to understand the problem,
Input: N = 120 Output: 1
A simple solution will be using the direct Fibonacci formula to find the Nth term. But this method will not be feasible when N is a large number. So to overcome this thing, we will use the property of the Fibonacci Series that the last digit repeats itself after 60 terms. I.e. The last digit of the 75th term is the same as that of the 135th term.
This means that working till 60 will give us all possible combinations and to find which term to use we will find the number’s mod with 60.
 Live Demo
#include
using namespace std;
long int fibo(int N){
   long int a=0,b=1,c;
   for(int i=2; i< N;i++) {
      c=a+b;
      a=b;
      b=c;
   }
   return c;
}
int findLastDigitNterm(int N) {
   N = N % 60;
   return ( fibo(N)%10);
}
int main() {
   int N = 683;
   cout<<"The last digit of "<<N<<"th Fibonacci term is "<<findLastDigitNterm(N);
   return 0;
}
The last digit of 683th Fibonacci term is 1
How to select from table where conditions are set for id and name in MySQL?

Let us first create a table −
mysql> create table DemoTable819(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100)
);
Query OK, 0 rows affected (0.88 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable819(StudentName) values('Chris');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable819(StudentName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable819(StudentName) values('Adam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable819(StudentName) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable819(StudentName) values('Sam');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable819;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Robert      |
|         3 | Adam        |
|         4 | Mike        |
|         5 | Sam         |
+-----------+-------------+
5 rows in set (0.00 sec)
Following is the query to select from the table where conditions are set for name and id −
mysql> select *from DemoTable819 where StudentName='Robert' and StudentId > 1;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         2 | Robert      |
+-----------+-------------+
1 row in set (0.00 sec)
Cordova - Vibration

This plugin is used for connecting to device's vibration functionality.
We can install this plugin in command prompt window by running the following code −
C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-vibration

Once the plugin is installed we can add buttons in index.html that will be used later to trigger the vibration.
<button id = "vibration">VIBRATION</button>
<button id = "vibrationPattern">PATTERN</button>
Now we are going to add event listeners inside onDeviceReady in index.js.
document.getElementById("vibration").addEventListener("click", vibration);
document.getElementById("vibrationPattern").addEventListener("click", vibrationPattern);
This plugin is very easy to use. We will create two functions.
function vibration() {
   var time = 3000;
   navigator.vibrate(time);
}

function vibrationPattern() {
   var pattern = [1000, 1000, 1000, 1000];
   navigator.vibrate(pattern);
}
The first function is taking time parameter. This parameter is used for setting the duration of the vibration. Device will vibrate for three seconds once we press VIBRATION button.
The second function is using pattern parameter. This array will ask device to vibrate for one second, then wait for one second, then repeat the process again.

    45 Lectures 
     2 hours 

 Skillbakerystudios

    16 Lectures 
     1 hours 

 Nilay Mehta
 Print
 Add Notes
 Bookmark this page
JavaScript - Array filter() Method

Javascript array filter() method creates a new array with all elements that pass the test implemented by the provided function.
Its syntax is as follows −
array.filter(callback[, thisObject]);

callback − Function to test each element of the array.
callback − Function to test each element of the array.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns created array.
This method is a JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard. To make it work, you need to add the following code at the top of your script.
if (!Array.prototype.filter) {
   Array.prototype.filter = function(fun /*, thisp*/) {
      var len = this.length;
      if (typeof fun != "function")
      throw new TypeError();
      
      var res = new Array();
      var thisp = arguments[1];
      for (var i = 0; i < len; i++) {
         if (i in this) {
            var val = this[i];   // in case fun mutates this
            if (fun.call(thisp, val, i, this))
            res.push(val);
         }
      }
      return res;
   };
}
Try the following example.
<html>
   <head>
      <title>JavaScript Array filter Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         if (!Array.prototype.filter) {
            Array.prototype.filter = function(fun /*, thisp*/) {
               var len = this.length;
            
               if (typeof fun != "function")
               throw new TypeError();
            
               var res = new Array();
               var thisp = arguments[1];
            
               for (var i = 0; i < len; i++) {
                  if (i in this) {
                     var val = this[i];   // in case fun mutates this
                     if (fun.call(thisp, val, i, this))
                     res.push(val);
                  }
               }
               return res;
            };
         }
         function isBigEnough(element, index, array) {
            return (element >= 10);
         }
         var filtered  = [12, 5, 8, 130, 44].filter(isBigEnough);
         document.write("Filtered Value : " + filtered ); 
      </script>      
   </body>
</html>
Filtered Value : 12,130,44 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Perl - Loops

There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages −
Perl programming language provides the following types of loop to handle the looping requirements.
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn.
Like a while statement, except that it tests the condition at the end of the loop body
You can use one or more loop inside any another while, for or do..while loop.
Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Perl supports the following control statements. Click the following links to check their detail.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
Terminates the loop statement and transfers execution to the statement immediately following the loop.
A continue BLOCK, it is always executed just before the conditional is about to be evaluated again.
The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed.
Perl supports a goto command with three forms: goto label, goto expr, and goto &name.
A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty.
#!/usr/local/bin/perl
 
for( ; ; ) {
   printf "This loop will run forever.\n";
}
You can terminate the above infinite loop by pressing the Ctrl + C keys.
When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but as a programmer more commonly use the for (;;) construct to signify an infinite loop.

    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
numpy.random.dirichlet() in Python - GeeksforGeeks

15 Jul, 2020
With the help of dirichlet() method, we can get the random samples from dirichlet distribution and return the numpy array of some random samples by using this method.
Syntax : numpy.random.dirichlet(alpha, size=None)
Parameters :
1) alpha – number of samples.
2) size – output shape of a numpy array.
Return : Return the random samples array.
Example #1 :
In this example we can see that by using random.dirichlet() method, we are able to get the random samples of dirichlet distribution and return the numpy array having size defined in the parameters.
Python3
# import dirichletimport numpy as npimport matplotlib.pyplot as plt  # Using dirichlet() methodgfg = np.random.dirichlet((3, 4, 5, 19), size = 1000)  count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()
Output :
Example #2 :
Python3
# import dirichletimport numpy as npimport matplotlib.pyplot as plt  # Using dirichlet() methodgfg = np.random.dirichlet((6, 5, 4, 3, 2, 1), 1000)  count, bins, ignored = plt.hist(gfg, 30, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
LocalDate getDayOfYear() method in Java with Examples - GeeksforGeeks

28 Nov, 2018
The getDayOfYear() method of LocalDate class in Java gets the day-of-year field.
Syntax:
public int getDayOfYear()

Parameter: This method does not accepts any parameter.
Return Value: The function returns the day of the year which is in range [1, 365/366] depending on leap year or not.
Below programs illustrate the getDayOfYear() method of LocalDate in Java:
Program 1:
// Program to illustrate the getDayOfYear() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        LocalDate dt = LocalDate.parse("2018-11-27");          // Prints the day number        System.out.println(dt.getDayOfYear());    }}
331

Program 2:
// Program to illustrate the getDayOfYear() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the date        LocalDate dt = LocalDate.parse("2018-01-02");          // Prints the day number        System.out.println(dt.getDayOfYear());    }}
2

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getDayOfYear()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Multithreading in Java
Collections in Java
Scala Float round() method with example - GeeksforGeeks

29 Oct, 2019
The round() method is utilized to return the rounded value of the specified float value. If the float value is 5.5 or greater than 5.5 till 5.9, then it will returns 6 otherwise 5 if the float value is 5.0 or till 5.4
Method Definition: (Float_Value).round
Return Type: It returns the rounded value of the specified float value.
Example #1:
// Scala program of Float round()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying round method        val result = (5.4).round                  // Displays output        println(result)          }} 
5

Example #2:
// Scala program of Float round()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying round method        val result = (5.9).round                  // Displays output        println(result)          }} 
6

Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Scala Map
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Scala List contains() method with example
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
How to get the first element of List in Scala
Scala | Traits
HTTP headers | Access-Control-Allow-Credentials - GeeksforGeeks

07 Jan, 2022
The HTTP Access-Control-Allow-Credentials is a Response header. The Access-Control-Allow-Credentials header is used to tell the browsers to expose the response to front-end JavaScript code when the request’s credentials mode Request.credentials is “include”. Remember one thing when the Request.credentials is “include” mode browsers will expose the response to front-end JavaScript code if the Access-Control-Allow-Credentials is set true.
The Access-Control-Allow-Credentials header performs with the XMLHttpRequest.withCredentials property or with the credentials option in the Request() constructor of the Fetch API.
Note: Credentials are actually cookies, authorization headers or TLS(Transport Layer Security) client certificates.
Syntax:
Access-Control-Allow-Credentials: true
Directives: This header accept a single directive mentioned above and described below:
true: This the only meaningful or you can say valid value for Access-Control-Allow-Credentials header. If this credentials is not required, then remove the header. Don’t put there Access-Control-Allow-Credentials: false. This directive is case sensitive true
Example:
This is allowing the Access-Control-Allow-Credentials.Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: true
This is using the xhr with credentials.var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.geeksforgeeks.org/', true); 
xhr.withCredentials = true; 
xhr.send(null);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.geeksforgeeks.org/', true); 
xhr.withCredentials = true; 
xhr.send(null);
This is using Fetch with credentials.fetch(url, {
  credentials: 'include'  
})
fetch(url, {
  credentials: 'include'  
})
To check this Access-Control-Allow-Credentials in action go to Inspect Element -> Network check the response header for Access-Control-Allow-Credentials like below, Access-Control-Allow-Credentials is highlighted you can see.
Supported Browsers: The browsers compatible with HTTP Access-Control-Allow-Credentials header are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
rajeev0719singh
HTTP-headers
Picked
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
Python | Decimal logical_xor() method - GeeksforGeeks

05 Sep, 2019
Decimal#logical_xor() : logical_xor() is a Decimal class method which returns the digit-wise exclusive or of the two Decimal values.
Syntax: Decimal.logical_xor()
Parameter: Decimal values
Return: the digit-wise and of the two (logical) Decimal values.
Code #1 : Example for logical_xor() method
# Python Program explaining # logical_xor() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('0')  b = Decimal('1')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.logical_xor() methodprint ("\n\nDecimal a with logical_xor() method : ", a.logical_xor(b))  print ("Decimal b with logical_xor() method : ", b.logical_xor(b))
Output :
Decimal value a :  0
Decimal value b :  1


Decimal a with logical_xor() method :  1
Decimal b with logical_xor() method :  0


Code #2 : Example for logical_xor() method
# Python Program explaining # logical_xor() method  # loading decimal libraryfrom decimal import *    # Initializing a decimal valuea = Decimal('1')  b = Decimal('0')  # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b)    # Using Decimal.logical_xor() methodprint ("\n\nDecimal a with logical_xor() method : ", a.logical_xor(a))  print ("Decimal b with logical_xor() method : ", a.logical_xor(b))
Output :
Decimal value a :  1
Decimal value b :  0


Decimal a with logical_xor() method :  0
Decimal b with logical_xor() method :  1

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()