code-rag-bench/online-tutorials huggingface dataset:
YAML - Syntax Characters

Various types of characters are used for various functionalities. This chapter talks in detail about syntax used in YAML and focuses on character manipulation.
Indicator characters include a special semantics used to describe the content of YAML document. The following table shows this in detail.
_
It denotes a block sequence entry
?
It denotes a mapping key
:
It denotes a mapping value
,
It denotes flow collection entry
[
It starts a flow sequence
]
It ends a flow sequence
{
It starts a flow mapping
}
It ends a flow mapping
#
It denotes the comments
&
It denotes node’s anchor property
*
It denotes alias node
!
It denotes node’s tag
|
It denotes a literal block scalar
>
It denotes a folded block scalar
`
Single quote surrounds a quoted flow scalar
"
Double quote surrounds double quoted flow scalar
%
It denotes the directive used
The following example shows the characters used in syntax −
%YAML 1.1
---
!!map {
   ? !!str "sequence"
   : !!seq [
      !!str "one", !!str "two"
   ],
   ? !!str "mapping"
   : !!map {
      ? !!str "sky" : !!str "blue",
      ? !!str "sea" : !!str "green",
   }
}

# This represents
# only comments.
---
!!map1 {
   ? !!str "anchored"
   : !local &A1 "value",
   ? !!str "alias"
What are Python dictionary view objects?

Dictionary methods items(), keys() and values() return view objects. The items() method returns a dict_items object containing list of key-value pairs in the dictionary
>>> D1={"pen":25, "pencil":10, "book":100, "sharpner":5, "eraser":5}
>>> i=D1.items()
>>> i
dict_items([('pen', 25), ('pencil', 10), ('book', 100), ('sharpner', 5), ('eraser', 5)])
The keys() method returns a view object of the type dict_keys that holds a list of all keys
>>> k=D1.keys()
>>> k
dict_keys(['pen', 'pencil', 'book', 'sharpner', 'eraser'])
Similarly, values() method returns dict_values object
>>> v=D1.values()
>>> v
dict_values([25, 10, 100, 5, 5])
These view objects are updated dynamically. In changes in the underlying dictionary object are reflected in the view. For instance, if ‘book’ key is deleted from the dictionary, the respective view objects will also not show related entries.
>>> del D1['book']
>>> k
dict_keys(['pen', 'pencil', 'sharpner', 'eraser'])
>>> i
dict_items([('pen', 25), ('pencil', 10), ('sharpner', 5), ('eraser', 5)])
>>> v
dict_values([25, 10, 5, 5])
numpy.empty() in Python

29 Nov, 2018
numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values.Parameters :
-> shape : Number of rows
-> order : C_contiguous or F_contiguous
-> dtype : [optional, float(by Default)] Data type of returned array.  

# Python Programming illustrating# numpy.empty method  import numpy as geek  b = geek.empty(2, dtype = int)print("Matrix b : \n", b)  a = geek.empty([2, 2], dtype = int)print("\nMatrix a : \n", a)  c = geek.empty([3, 3])print("\nMatrix c : \n", c)
Output :
Matrix b : 
 [         0 1079574528]

Matrix a : 
 [[0 0]
 [0 0]]

Matrix a : 
 [[ 0.  0.  0.]
 [ 0.  0.  0.]
 [ 0.  0.  0.]]
Note : empty, unlike zeros, does not set the array values to zero, and may therefore be marginally faster.Also, these codes won’t run on online-ID. Please run them on your systems to explore the working
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Python PIL | ImageOps.grayscale() method

27 Oct, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.ImageOps.grayscale() Convert the image to grayscale. The complete pixel turns to gray, no other color will be seen. 
Syntax: PIL.ImageOps.grayscale(image) Parameters: image – The image to convert into grayscale.Returns An image.  
Image Used:  
 
Python3
# Importing Image and ImageOps module from PIL packagefrom PIL import Image, ImageOps     # creating a image1 objectim1 = Image.open(r"C:\Users\System-Pc\Desktop\a.JPG") # applying grayscale methodim2 = ImageOps.grayscale(im1) im2.show()
Output: 
 
nidhi_biet
sudiptadey1
sooda367
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Python | Extract words from given string

28 Jul, 2021
We sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthands to perform this task is always useful. Additionally, this article also includes the cases in which punctuation marks have to be ignored.Method #1 : Using split() Using the split function, we can split the string into a list of words and this is the most generic and recommended method if one wished to accomplish this particular task. But the drawback is that it fails in cases the string contains punctuation marks. 
Python3
# Python3 code to demonstrate# to extract words from string# using split() # initializing string test_string = "Geeksforgeeks is best Computer Science Portal" # printing original stringprint ("The original string is : " +  test_string) # using split()# to extract words from stringres = test_string.split() # printing resultprint ("The list of words is : " +  str(res))
  Method #2 : Using regex( findall() ) In the cases which contain all the special characters and punctuation marks, as discussed above, the conventional method of finding words in string using split can fail and hence requires regular expressions to perform this task. findall function returns the list after filtering the string and extracting words ignoring punctuation marks. 
Python3
# Python3 code to demonstrate# to extract words from string# using regex( findall() )import re # initializing string test_string = "Geeksforgeeks,    is best @# Computer Science Portal.!!!" # printing original stringprint ("The original string is : " +  test_string) # using regex( findall() )# to extract words from stringres = re.findall(r'\w+', test_string) # printing resultprint ("The list of words is : " +  str(res))
  Method #3 : Using regex() + string.punctuation This method also used regular expressions, but string function of getting all the punctuations is used to ignore all the punctuation marks and get the filtered result string. 
Python3
# Python3 code to demonstrate# to extract words from string# using regex() + string.punctuationimport reimport string # initializing string test_string = "Geeksforgeeks,    is best @# Computer Science Portal.!!!" # printing original stringprint ("The original string is : " +  test_string) # using regex() + string.punctuation# to extract words from stringres = re.sub('['+string.punctuation+']', '', test_string).split() # printing resultprint ("The list of words is : " +  str(res))
ipablo26
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
How are Java objects stored in memory?

24 May, 2022
In Java, all objects are dynamically allocated on Heap. This is different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, when we allocate the object using new(), the object is allocated on Heap, otherwise on Stack if not global or static.In Java, when we only declare a variable of a class type, only a reference is created (memory is not allocated for the object). To allocate memory to an object, we must use new(). So the object is always allocated memory on the heap (See this for more details).
There are two ways to create an object  of string in java:
By string literalBy new keywordBy string literal:
By string literal
By new keyword
By string literal:
This is done using double-quotes.
For example:
String str1="GFG";
String str2="GFG";
By String Literal
Every time when a string literal is created, JVM will check whether that string already exists in the string constant pool or not. If the string already exists in the string literal pool then a reference to the pooled instance is returned. If the string does not exist, then a new string instance is created in the pool. Hence, only one object will get created.
Here, the JVM is not bonded to create a new memory.
This is done using a new keyword.
For example:
String str1=new String("Hello");
String str2=new String("Hello");
By new Keyword
Both str1 and str2 are objects of String.
Every time when a string object is created, JVM will create it in a heap memory. In this case, the JVM will not check whether the string already exists or not. If a string already exist , then also for every string object the memory will get created separately. 
Here, the JVM is bond to create a new memory. For example, the following program fails in the compilation. Compiler gives error “Error here because t is not initialized”.
java
class Test { // class contentsvoid show(){    System.out.println("Test::show() called");}} public class Main {         // Driver Code    public static void main(String[] args)    {        Test t;                 // Error here because t        // is not initialized        t.show();    }}
Output:
 
Allocating memory using new() makes the above program work. 
java
class Test {     // class contentsvoid show(){    System.out.println("Test::show() called");}} public class Main {         // Driver Code    public static void main(String[] args)    {                 // all objects are dynamically        // allocated        Test t = new Test();        t.show(); // No error    }}
Test::show() called

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
HarshithThonupunoori
RShriwas
sooda367
singhankitasingh066
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
How to Calculate Rolling Correlation in R?

20 Jun, 2022
In this article, we will discuss Rolling Correlation in R Programming Language.
Correlation is used to get the relationship between two variables.
It will result in 1 if the correlation is positive.
It will result in -1 if the correlation is negative.
it will result in 0 if there is no correlation.
Rolling correlations are used to get the relationship between two-time series on a rolling window. We can calculate by using rollapply() function, This is available in the zoo package, So we have to load this package.
Syntax:
rollapply(data, width, FUN, by.column=TRUE)
where,
data is the input dataframe.
width is an integer that specifies the window width for the rolling correlation.
FUN is the  function to be applied.
by.column is used to specify whether to apply the function to each column separately.
We can get correlation using cor() function.
Syntax:
cor(column1,column2)
Example 1: R program to calculate rolling correlation for the dataframe.
R
# load the librarylibrary(zoo) # create dataframe with 3 columnsdata = data.frame(day=1:15,                   col1=c(35:49),                   col2=c(33:47)) # displayprint(data) # get rolling correlation for col1 and# col2 with width 6print(rollapply(data, width=6, function(x) cor(x[,2],x[,3]),                by.column=FALSE))
Output:
Example 2:
R
# load the librarylibrary(zoo) # create dataframe with 3 columnsdata = data.frame(                   col1=c(23,45,23,32,23),                   col2=c(1,45,67,32,45)) # displayprint(data) # get rolling correlation for col1 and# col2 with width 2print(rollapply(data, width=2, function(x) cor(x[,1],x[,2]),                by.column=FALSE))
Output:
surinderdawra388
Picked
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Tensorflow.js tf.sum() Function

12 May, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The tf.sum() function is used to calculate sum of the elements of a specified Tensor across its dimension. It reduces the given input elements along the dimensions of axes. If the parameter “keepDims” is true, the reduced dimensions are retained with length 1 else the rank of Tensor is reduced by 1. If the axes parameter has no entries, it returns a Tensor with a single element with all reduced dimensions.
Syntax:
tf.sum(x, axis, keepDims)
Parameters: This function accepts three parameters which are illustrated below:
x: The input tensor on which sum operation is being computed. If the data type is Boolean value, it will be converted into int32 and the returned output will also be in int32.
axis: The specified dimension(s) to reduce. By default it reduces all dimensions. It is optional parameter.
keepDims: If this parameter value is true, it retains reduced dimensions with length 1 else the rank of Tensor is reduced by 1. It is also optional parameter.
Return Value: It returns a Tensor for the result of sum operation.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor1d([3, 5]);const c = tf.tensor1d([2, 4, 7]);  // Calling the .sum() function over // the above tensorsa.sum().print();b.sum().print();c.sum().print();
Output:
Tensor
   1
Tensor
   8
Tensor
   13
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Initializing a some tensors const a = tf.tensor1d([0, 1]);const b = tf.tensor2d([3, 5, 2, 8], [2, 2]);const c = tf.tensor1d([2, 4, 7]);  // Initializing a axis parametersconst axis1 = -1;const axis2 = -2;const axis3 = 0;  // Calling the .sum() function over // the above tensorsa.sum(axis1).print();b.sum(axis2, true).print();c.sum(axis1, false).print();b.sum(axis3, false).print();
Output:
Tensor
   1
Tensor
    [[5, 13],]
Tensor
   13
Tensor
   [5, 13]
Tensorflow
Tensorflow.js
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 ?
Reverse array elements in Julia – reverse(), reverse!() and reverseind() Methods

01 Apr, 2020
The reverse() is an inbuilt function in julia which is used to reverse the specified vector v from start to stop.
Syntax:reverse(v, start, stop)orreverse(A; dims::Integer)
Parameters:
v: Specified vector.
start: Specified starting value.
stop: Specified stopping value.
A: Specified array.
dims::Integer: Specified dimensions.
Returns: It returns a reversed copy of the vector.
Example 1:
# Julia program to illustrate # the use of reverse() method   # Getting the reversed copy of # the specified vector.A = Vector(2:8)println(reverse(A))println(reverse(A, 3, 6))println(reverse(A, 7, 4))
Output:
[8, 7, 6, 5, 4, 3, 2]
[2, 3, 7, 6, 5, 4, 8]
[2, 3, 4, 5, 6, 7, 8]
Example 2:
# Julia program to illustrate # the use of reverse() method   # Getting reversed array in # the specified dimensionA = [5 10; 15 20]println(reverse(A, dims = 1))println(reverse(A, dims = 2))
Output:
The reverse!() is an inbuilt function in julia which is In-place version of reverse() function.
Syntax:reverse!(v, start, stop)
Parameters:
v: Specified vector.
start: Specified starting value.
stop: Specified stopping value.
Returns: It returns a reversed copy of the vector.
Example:
# Julia program to illustrate # the use of reverse !() method   # Getting the reversed copy of # the specified vector.A = Vector(2:8)println(reverse !(A))println(reverse !(A, 3, 6))
Output:
[8, 7, 6, 5, 4, 3, 2]
[8, 7, 3, 4, 5, 6, 2]

The reverseind() is an inbuilt function in julia which is used to return the corresponding index in v so that v[reverseind(v, i)] == reverse(v)[i], where i is the given index.
Syntax:reverseind(v, i)
Parameters:
v: Specified string.
i: Specified index.
Returns: It returns the corresponding index in v so that v[reverseind(v, i)] == reverse(v)[i].
Example:
# Julia program to illustrate # the use of reverseind() method   # Getting the corresponding index in v# so that v[reverseind(v, i)] == reverse(v)[i]V = reverse("Geeks")for i in 1:length(r)    print(V[reverseind("Geeks", i)])end
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Implementation of ls | wc command

30 Apr, 2018
ls | wc command : Using ls|wc, we can count new lines, words and letters of all files of current directory. We can see from the following after execution of the code we get same results.
Prerequisites :ls command | wc command | piping in linux
Approach : First, we have to use pipe for inter process communication over an array where a[0] is used for reading and a[1] is used for writing. We can replicate the process using fork. In the parent process, standard output is closed so that output of ls command will go to a[0] and similarly standard input is closed in children process. Now, if we run the program output will be as same as command of linux ls|wc.
Below is the implementation of above approach :
// C code to implement ls | wc command#include <stdio.h>#include <stdlib.h>#include <fcntl.h>#include<errno.h>#include<sys/wait.h>#include <unistd.h>int main(){      // array of 2 size a[0] is for    // reading and a[1] is for    // writing over a pipe        int a[2];      // using pipe for inter    // process communication    pipe(a);      if(!fork())    {        // closing normal stdout        close(1);                  // making stdout same as a[1]        dup(a[1]);                  // closing reading part of pipe        // we don't need of it at this time        close(a[0]);                  // executing ls         execlp("ls","ls",NULL);    }    else    {        // closing normal stdin        close(0);                  // making stdin same as a[0]        dup(a[0]);                  // closing writing part in parent,        // we don't need of it at this time        close(a[1]);                  // executing wc        execlp("wc","wc",NULL);    }}
linux-command
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
'dd' command in Linux
How to Find Out File Types in Linux
Start/Stop/Restart Services Using Systemctl in Linux
mv command in Linux with examples
bc command in Linux with examples
du command in Linux with examples
uniq Command in LINUX with examples
vi Editor in UNIX
Multi-Line Comment in Shell Script
Draw Colorful Spiral Web Using Turtle Graphics in Python - GeeksforGeeks

20 Oct, 2020
Prerequisite: Turtle Basics
“Turtle” is a Python feature like a drawing board, which lets us command a turtle to draw all over it. This comes packed with the standard Python package and need not be installed externally.
Methods used:
forward(value): moves the turtle in the forward direction.
turtle.Pen(): setup the turtle pen
speed(value): changes the speed of the turtle
width(value): set the width
left(value): moves the turtle left.
bgcolor(color_name): changes background-color
Approach:
Import turtle.
Define colors using the list data structure in python.
Setup a turtle pen for drawing the Spiral Web.
Start making the Spiral Web according to your logic.  
Below is the implementation of the above approach.
Python3
# import turtleimport turtle # defining colorscolors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange'] # setup turtle pent= turtle.Pen() # changes the speed of the turtlet.speed(10) # changes the background colorturtle.bgcolor("black") # make spiral_webfor x in range(200):    t.pencolor(colors[x%6]) # setting color    t.width(x/100 + 1) # setting width    t.forward(x) # moving forward    t.left(59) # moving left turtle.done()t.speed(10) turtle.bgcolor("black") # changes the background color # make spiral_webfor x in range(200):    t.pencolor(colors[x%6]) # setting color    t.width(x/100 + 1) # setting width    t.forward(x) # moving forward    t.left(59) # moving left turtle.done()
  
Output:
 
 
pulkitagarwal03pulkit
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Angle Between Hands of a Clock in C++

Suppose we have two numbers, hour and minutes. We have to find a smaller angle (in sexagesimal units) formed between the hour and the minute hand. So if the input is like hour = 12 and min := 30, then the result will be 165°.
To solve this, we will follow these steps −
if h = 12, then set h := 0
if h = 12, then set h := 0
if m = 60, then set m := 0
if m = 60, then set m := 0
hAngle := 0.5 * (60h) + m
hAngle := 0.5 * (60h) + m
mAngle := 6m
mAngle := 6m
ret := |hAngle - mAngle|
ret := |hAngle - mAngle|
return minimum of ret and (360 – ret)
return minimum of ret and (360 – ret)
Let us see the following implementation to get better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   double angleClock(int h, int m) {
      if(h == 12) h = 0;
      if(m == 60) m = 0;
      double hAngle = 0.5*((60 * h) + m);
      double mAngle = 6 * m;
      double ret = abs(hAngle - mAngle);
      return min(360 - ret, ret);
   }
};
main(){
   Solution ob;
   cout << (ob.angleClock(12, 30));
}
12
30
165.00000
Run Linux Natively on Windows 10

Microsoft has introduced the WSL Subsystem for Linux, which lets users run their favorite Linux distributions directly from Windows 10 without dual-booting or using a virtual machine.
While this is a step in the right direction for Microsoft, it's not quite there yet in terms of full functionality. Specifically, WSL does not support AF_PACKET for security restrictions. This means that you won't be able to put a Wi-Fi adapter in promiscuous mode (or monitor mode), and tools that require raw sockets to function properly won't work, such as Nmap.
To do so, run the PowerShell with administrator rights and hit the following command.
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Download the 'Kali Linux' Application from the Microsoft Store by searching for "Kali Linux" on the list. And from there, click "Get" to begin installing. It will ask for system reboot after the package download it will install automatically. Once your system has rebooted and you've logged back into your account, launch the Kali from the Cortana bar.
The user will be prompted every time to enter the root password for the configuring the package since the default version of Kali Linux in the windows-10 OS installed without root permission. So, to enable the root privilege, hit the following commands.
Sudo –i
Chmod +s /bin/su
With that done, you'll be prompted to create and configure a Kali Linux username and password. When all set, the important first thing don't forget is to add the kali Linux repository in the /etc/apt/source.list file and then update it just like any Linux system with the following command.
Sudo apt-get update
Sudo apt-get upgrade
It might be possible that the Windows Defender could treat or detect Kali repository as viruses or malware and blocks some portion of the program. To prevent these errors, add Windows Defender exclusion for the Kali Linux folder.
Since this version of kali Linux will be in command mode out rightly. Now we need to set up the XFCE desktop manager but need to install some utilities first. Run the following command to install wget which is a utility that can download files over HTTP. Enter your password you created in the previous step when
prompted and hit Y to proceed with the download and install.
sudo apt-get install wget
wget https://kali.sh/xfce4.sh
sudo sh xfce4.sh
Now it is time to start up the xrdp server to connect to the XFCE desktop manager using Remote
Desktop. Run the following command
sudo /etc/init.d/xrdp start
Finally, the xrdp server has started, then open up the remote command connection (RDP) prompt using mstsc and connect to 127.0.0.1:3390. Then, you are required to logged-in with the previously defined ID and Password in the GUI. And, you got the full-fledged Linux XFC desktop. Enjoy.
Python – API.get_status() in Tweepy

05 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The API.get_status() method of the API class in Tweepy module is used to fetch a status / tweet.
Syntax : API.get_status(parameters)
Parameters :
id : The id of the status.
trim_user : A boolean indicating if user IDs should be provided, instead of complete user objects. The defaults value is False.
Returns : an object of the class Status
Example 1 : Consider the following tweet:
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # the ID of the statusID =   # obtaining the statusstatus = api.get_status(ID)  # printing the text of the statusprint("The text of the status is : " + status.text)
Output :
The text of the tweet is : This is a tweet.
Example 2 : Consider the following tweet :Obtaining the screen name, the number of replies and the number of retweets for the above tweet.
# the ID of the statusID = 1265569813281280006  # obtaining the statusstatus = api.get_status(ID)  # printing the text of the statusprint("The text of the status is : \n\n" + status.text)  # printing the screen nameprint("\nThe status was posted by : " + status.user.screen_name)  # printing the number of likesprint("The status has been liked " + str(status.favorite_count) + " number of times.")  # printing the number of retweetsprint("The status has been retweeted " + str(status.retweet_count) + " number of times.")
Output :
The text of the status is : 

Apart from coding, what GEEKS are doing in quarantine?

Reply us...

#Quarantine #QuarantineLife #coding #programming

The status was posted by : geeksforgeeks
The status has been liked 25 number of times.
The status has been retweeted 3 number of times.

Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
PHP | mysqli_connect() Function

06 Jul, 2021
The mysqli_connect() function in PHP is used to connect you to the database. In the previous version of the connection mysql_connect() was used for connection and then there comes mysqli_connect() where i means improved version of connection and is more secure than mysql_connect().Syntax:  
mysqli_connect ( "host", "username", "password", "database_name" )
Parameters used:  
host: It is optional and it specify the host name or IP address. In case of local server localhost is used as a general keyword to connect local server and run the program.
username: It is optional and it specify mysql username. In local server username is root.
Password: It is optional and it specify mysql password.
database_name: It is database name where operation perform on data. It also optional.
Return values:  
It returns an object which represent MySql connection. If connection failed then it return FALSE.
Program: Below is the implementation of mysqli_connect() function. 
php
<?php    mysqli_connect("localhost", "root", "", "GFG");     if(mysqli_connect_error())        echo "Connection Error.";    else        echo "Database Connection Successfully.";?>
Output:  
Database Connection Successfully.
 
saurabh1990aror
mysql
PHP-function
Misc
SQL
Misc
Misc
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
while loop in Perl

21 Nov, 2019
A while loop in Perl generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don’t know the number of times we want the loop to be executed however we know the termination condition of the loop. It is also known as an entry controlled loop as the condition is checked before executing the loop. The while loop can be thought of as a repeating if statement.
Syntax :
while (condition)
{
    # Code to be executed
}

Flow Chart:
Example :
# Perl program to illustrate# the while loop  # while loop$count = 3;while ($count >= 0){    $count = $count - 1;    print "GeeksForGeeks\n";}
Output:
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks

A Nested while loop is one in which one while loop is used inside another while loop. In a Nested while loop, for each iteration of the outer while loop, the inner while loop gets executed completely.
#!/usr/bin/perl# Perl program for Nested while loop$a = 0;    # while loop execution  while( $a <= 2 ){      $b = 0;      while( $b <= 2 )    {          printf "$a $b\n";          $b++;      }      $a++;  }  
Output:
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

While loop can execute infinite times which means there is no terminating condition for this loop. In other words, we can say there are some conditions that always remain true, which causes while loop to execute infinite times or we can say it never terminates.
Below program will print the specified statement infinite time and also gives the runtime error as Output Limit Exceeded on online IDE
# Perl program to illustrate# the infinite while loop  # infinite while loop# containing condition 1 # which is always truewhile(1){    print "Infinite While Loop\n";}
Output:
Infinite While Loop
Infinite While Loop
Infinite While Loop
Infinite While Loop
.
.
.
.

Perl-Loops
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | ne operator
Perl | Basic Syntax of a Perl Program
Perl | Opening and Reading a File
Perl | File Handling Introduction
Perl | Writing to a File
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | Multidimensional Hashes
Perl | Data Types
Perl | qw Operator
Print Patterns in PL/SQL

26 Feb, 2021
You have given a number n then you have to print number a right-angled pyramid of * Examples:  
Input : 3
Output :
*
**
***

Input : 7
Output :
*
**
***
****
*****
******
*******
 
C
DECLARE  -- declare variable n,  --I AND J of datatype number  N NUMBER := 7;  I NUMBER;  J NUMBER;BEGIN  -- loop from 1 to n  FOR I IN 1..N  LOOP    FOR J IN 1..I    LOOP      DBMS_OUTPUT.PUT('*') ; -- printing *    END LOOP;    DBMS_OUTPUT.NEW_LINE; -- for new line  END LOOP;END;--Program End
Output:  
*
**
***
****
*****
******
*******
 
viswajit4u
pattern-printing
SQL-PL/SQL
DBMS
SQL
pattern-printing
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – distort() method in Wand

23 Dec, 2021
ImageMagick provides several ways to distort an image by applying various transformations against user-supplied arguments. In Wand, the method distort() is used, and follows a basic function. 
Syntax :  
wand.image.distort(method, arguments, best_fit)
Parameters :  
Following are the Distortion Methods :  
Source Image:  
Code Example 1:  
Python3
# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename ="gog.png") as img:    img.distort('arc', (45, ))    img.save(filename ='gogdistort1.png')
Output Image:  
Code Example 2: Changing DISTORTION_METHOD to ‘perspective’.  
Python3
# Import Image from wand.image modulefrom wand.image import Image # Read image using Image functionwith Image(filename ="gog.png") as img:    arguments = (0, 0, 20, 60,                 90, 0, 70, 63,                 0, 90, 5, 83,                 90, 90, 85, 88)    img.distort('perspective', arguments)    img.save(filename ='gogdistort.png')
Output Image:  
 
sagar0719kumar
surinderdawra388
ruhelaa48
Python-gui
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Java sqrt() method with Examples

09 Apr, 2018
The java.lang.Math.sqrt() returns the square root of a value of type double passed to it as argument. If the argument is NaN or negative, then the result is NaN. If the argument is positive infinity, then the result is positive infinity. If the argument passed is positive zero or negative zero then the result will be same as that of the argument.
Syntax:
public static double sqrt(double a)
Parameter :
a : the value whose square root is to be returned.
Return :
This method returns the positive square root value of 
the argument passed to it.

Example 1: To show working of java.lang.Math.sqrt() method.
// Java program to demonstrate working// of java.lang.Math.sqrt() methodimport java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        double a = 30;          System.out.println(Math.sqrt(a));          a = 45;          System.out.println(Math.sqrt(a));          a = 60;          System.out.println(Math.sqrt(a));          a = 90;          System.out.println(Math.sqrt(a));    }}
Output:
5.477225575051661
6.708203932499369
7.745966692414834
9.486832980505138

Example 2: To show working of java.lang.Math.sqrt() method when argument is NaN or +infinity.
// Java program to demonstrate working// of java.lang.Math.sqrt() methodimport java.lang.Math; // importing java.lang package  public class GFG {    public static void main(String[] args)    {          double positiveInfinity = Double.POSITIVE_INFINITY;        double negativeVal = -5;        double nan = Double.NaN;        double result;          // Here argument is negative,        // output will be NaN        result = Math.sqrt(negativeVal);        System.out.println(result);          // Here argument is positive infinity,        // output will also positive infinity        result = Math.sqrt(positiveInfinity);        System.out.println(result);          // Here argument is NaN, output will be NaN        result = Math.sqrt(nan);        System.out.println(result);    }}
Output:
NaN
Infinity
NaN

Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Collections in Java
Stream In Java
Singleton Class in Java
Set in Java
Introduction to Java
Constructors in Java
Multithreading in Java
LinkedList in Java
Initializing a List in Java
How to enable webview java script in android?

This example demonstrate about How to enable webview java script in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <WebView
      android:id = "@+id/web_view"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken web view to show google.com.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
   @RequiresApi(api = Build.VERSION_CODES.P)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      WebView web_view = findViewById(R.id.web_view);
      web_view.loadUrl("https://www.google.com/");
      web_view.requestFocus();
      web_view.getSettings().setLightTouchEnabled(true);
      web_view.getSettings().setJavaScriptEnabled(true);
   }
}
Step 4 − Add the following code to AndroidManifest.xml
<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.myapplication">
   <uses-permission android:name = "android.permission.INTERNET"/>
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
Python def Keyword

29 Sep, 2021
Python def keyword is used to define a function, it is placed before a function name that is provided by the user to create a user-defined function. In python, a function is a logical unit of code containing a sequence of statements indented under a name given using the “def” keyword. In python def keyword is the most used keyword.
Syntax:
def function_name: 
    function definition statements...
Use of def keyword:
In the case of classes, the def keyword is used for defining the methods of a class.
def keyword is also required to define the special member function of a class like __init__().
The possible practical application is that it provides the feature of code reusability rather than writing the piece of code again and again we can define a function and write the code inside the function with the help of the def keyword. It will be more clear in the illustrated example given below. There can possibly be many applications of def depending upon the use cases. 
Example 1: Use of def keyword.
In this example, we are going to create a user define a function using def keyword.
Python3
# Python3 code to demonstrate# def keyword # function for subtraction of 2 numbers.def subNumbers(x, y):    return (x-y) # main codea = 90b = 50 # finding subtractionresult = subNumbers(a, b) # print statementprint("subtraction of ", a, " and ", b, " is = ", result)
Output:
subtraction of  90  and  50  is =  40
Example 2: User defines a function with first 10 prime numbers.  
Python3
# Python program to print first 10# prime numbers # A function name prime is defined# using defdef prime(n):    x = 1    count = 0    while count < n:        for d in range(2, x, 1):            if x % d == 0:                x += 1        else:            print(x)            x += 1            count += 1 # Driver Coden = 10 # print statementprint("First 10 prime numbers are:  ")prime(n)
Output: 
First 10 prime numbers are:  
1
2
3
5
7
11
13
17
19
23
 Example 3: User defines a function with a factorial number.
Python3
# Python program to find the# factorial of a number # Function name factorial is defineddef factorial(n):    if n == 1:        return n    else:        return n*factorial(n-1) # Main codenum = 6 # check is the number is negativeif num < 0:    print("Sorry, factorial does not exist for negative numbers")elif num == 0:    print("The factorial of 0 is 1")else:    print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 6 is 720
sweetyty
Picked
python-basics
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Convert Tuple String to Integer Tuple

01 Mar, 2020
Interconversion of data is a popular problem developers generally deal with. One can face a problem to convert tuple string to integer tuple. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using tuple() + int() + replace() + split()The combination of above methods can be used to perform this task. In this, we perform the conversion using tuple() and int(). Extraction of elements is done by replace() and split().
# Python3 code to demonstrate working of # Convert Tuple String to Integer Tuple# Using tuple() + int() + replace() + split()  # initializing string test_str = "(7, 8, 9)"   # printing original string print("The original string is : " + test_str)  # Convert Tuple String to Integer Tuple# Using tuple() + int() + replace() + split()res = tuple(int(num) for num in test_str.replace('(', '').replace(')', '').replace('...', '').split(', '))  # printing result print("The tuple after conversion is : " + str(res)) 
The original string is : (7, 8, 9)
The tuple after conversion is : (7, 8, 9)

 
Method #2 : Using eval()This is recommended method to solve this task. This performs the interconversion task internally.
# Python3 code to demonstrate working of # Convert Tuple String to Integer Tuple# Using eval()  # initializing string test_str = "(7, 8, 9)"   # printing original string print("The original string is : " + test_str)  # Convert Tuple String to Integer Tuple# Using eval()res = eval(test_str)  # printing result print("The tuple after conversion is : " + str(res)) 
The original string is : (7, 8, 9)
The tuple after conversion is : (7, 8, 9)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
NPDA for accepting the language L = {aibjckdl | i==k or j==l,i>=1,j>=1}

28 Aug, 2019
Prerequisite – Pushdown automata, Pushdown automata acceptance by final stateProblem – Design a non deterministic PDA for accepting the language L = {    : i==k or j==l, i>=1, j>=1}, i.e.,
L = {abcd, aabccd, aaabcccd, abbcdd, aabbccdd, aabbbccddd, ......} 
In each string, the number of a’s are followed by any number of b’s and b’s are followed by the number of c’s equal to the number of a’s and c’s are followed by number of d’s equal number of b’s.
Explanation –Here, we need to maintain the order of a’s, b’s, c’s and d’s.That is, all the a’s are coming first then all the b’s are coming and then all the c’s are coming then all the d’s are coming . Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack.We will take 2 stack alphabets:
 = { a, b, c, d, z } 
Where, = set of all the stack alphabetz = stack start symbol
Approach used in the construction of PDA –In designing a NPDA, for every a’, ‘b’, ‘c’ and ‘d’ will comes in proper order.
For i==k : Whenever ‘a’ comes, push it in stack and if ‘a’ comes again then also push it in the stack.After that, if ‘b’ comes not do any operation. After that, when ‘c’ comes then pop ‘a’ from the stack each time.After that, if ‘d’ comes not do any operation.
For j==l : Whenever ‘a’ comes, not do any operation.After that, if ‘b’ comes push it in stack and if ‘b’ comes again then also push it in the stack. After that, when ‘c’ comes not do any operation.After that, if ‘d’ comes then pop ‘b’ from the stack each time.
So that the stack becomes empty.If stack is empty then we can say that the string is accepted by the PDA.
Stack transition functions –
(q0, a, z)  (q1, az)
(q0, a, z)  (q3, z)
(q1, a, a)  (q1, aa)
(q1, b, a)  (q1, a)
(q1, c, a)  (q2, ) 
(q2, c, a)  (q2, ) 
(q2, d,  )  (q2, ) 
(q2, , z)  (qf1, z)   
(q3 a, z)  (q3, z)
(q3 b, z)  (q3, bz)
(q3 b, b)  (q3, bb)
(q3 c, b)  (q3, b)
(q3, d, b)  (q4, ) 
(q4, d, b)  (q4, ) 
(q4, , z)  (qf2, z)   

Where, q0 = Initial stateqf1, qf2 = Final state = indicates pop operation
So, this is our required non deterministic PDA for accepting the language L ={    : i==k or j==l, i>=1, j>=1}.
nidhi_biet
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Introduction of Process Synchronization
Three address code in Compiler
Differences between IPv4 and IPv6
Phases of a Compiler
Introduction of Finite Automata
Difference between DFA and NFA
Turing Machine in TOC
Chomsky Hierarchy in Theory of Computation
Boyer-Moore Majority Voting Algorithm