code-rag-bench/online-tutorials huggingface dataset:
DynamoDB - Aggregation

DynamoDB does not provide aggregation functions. You must make creative use of queries, scans, indices, and assorted tools to perform these tasks. In all this, the throughput expense of queries/scans in these operations can be heavy.
You also have the option to use libraries and other tools for your preferred DynamoDB coding language. Ensure their compatibility with DynamoDB prior to using it.
Utilize the ascending/descending storage order of results, the Limit parameter, and any parameters which set order to find the highest and lowest values.
For example −
Map<String, AttributeValue> eaval = new HashMap<>(); 
eaval.put(":v1", new AttributeValue().withS("hashval")); 
queryExpression = new DynamoDBQueryExpression<Table>() 
   .withIndexName("yourindexname") 
   .withKeyConditionExpression("HK = :v1") 
   .withExpressionAttributeValues(values) 
   .withScanIndexForward(false);                //descending order 

queryExpression.setLimit(1); 
QueryResultPage<Lookup> res = 
   dynamoDBMapper.queryPage(Table.class, queryExpression);
Use DescribeTable to get a count of the table items, however, note that it provides stale data. Also, utilize the Java getScannedCount method.
Utilize LastEvaluatedKey to ensure it delivers all results.
For example −
ScanRequest scanRequest = new ScanRequest().withTableName(yourtblName); 
ScanResult yourresult = client.scan(scanRequest); 
System.out.println("#items:" + yourresult.getScannedCount());
Utilize indices and a query/scan to retrieve and filter values before processing. Then simply operate on those values through an object.

    16 Lectures 
     1.5 hours 

 Harshit Srivastava

    49 Lectures 
     3.5 hours 

 Niyazi Erdogan

    48 Lectures 
     3 hours 

 Niyazi Erdogan

    13 Lectures 
     1 hours 

 Harshit Srivastava

    45 Lectures 
     4 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
Java program to print prime numbers below 100

Any whole number which is greater than 1 and has only two factors that is 1 and the number itself, is called a prime number. Other than these two number it has no positive divisor. For example −
7 = 1 × 7
Few prime numbers are − 1, 2, 3, 5, 7, 11 etc.
1. Take integer variable A
2. Divide the variable A with (A-1 to 2)
3. If A is not divisible by any value (A-1 to 2), except itself it is a prime number.
4. Repeat this for all the numbers starting from 2 to the required limit.
Live Demo
public class First100Primes {
   public static void main(String args[]){

      for(int i = 2; i<=100;){
         int prime = 1;
         for(int loop = 2; loop <=i; loop++) {
            if((i % loop) == 0 &amp;&amp; loop!=i) {
               prime = 0;
            }
         }
         if (prime != 0){
            System.out.println(i+" is a prime number");
            i++;
         }
         else
         i ++;
      }
   }
}
2 is a prime number
3 is a prime number
5 is a prime number
7 is a prime number
11 is a prime number
13 is a prime number
17 is a prime number
19 is a prime number
23 is a prime number
29 is a prime number
31 is a prime number
37 is a prime number
41 is a prime number
43 is a prime number
47 is a prime number
53 is a prime number
59 is a prime number
61 is a prime number
67 is a prime number
71 is a prime number
73 is a prime number
79 is a prime number
83 is a prime number
89 is a prime number
97 is a prime number
Difference between two timestamps in seconds in MySQL?

Let us now see the following methods to calculate the time difference between two timestamps in seconds.
The following is the query to calculate the difference between two timestamps.
mysql> SELECT TIMESTAMPDIFF(SECOND, '2018-10-17 11:51:55', '2018-10-17 11:51:58');
The following is the output in seconds.
+---------------------------------------------------------------------+
| TIMESTAMPDIFF(SECOND, '2018-10-17 11:51:55', '2018-10-17 11:51:58') |
+---------------------------------------------------------------------+
|                                                                   3 |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)

The following is the query to calculate the difference between two timestamps with the help of UNIX Timestamp.
mysql>  SELECT UNIX_TIMESTAMP('2018-10-17 11:57:50') - UNIX_TIMESTAMP('2018-10-17 11:57:45') as DifferenceInSeconds;
The following is the output in seconds.
+---------------------+
| DifferenceInSeconds |
+---------------------+
|                   5 |
+---------------------+
1 row in set (0.00 sec)
How to add Youtube Videos in Next.js ? - GeeksforGeeks

22 Nov, 2021
In this article, we are going to learn how we can add Youtube Video in NextJs. NextJS is a React-based framework. It has the power to Develop beautiful Web applications for different platforms like Windows, Linux, and mac. The linking of dynamic paths helps in rendering your NextJS components conditionally.
Approach: To add our Youtube video we are going to use the react-youtube package. The react-youtube package helps us to add Youtube videos anywhere in our app. So first, we will install the react-youtube package and then we will add a youtube video on our homepage.
Create NextJS Application: You can create a new NextJs project using the below command:
npx create-next-app gfg
Install the required package: Now we will install the react-youtube package using the below command:
npm i react-youtube
Project Structure: It will look like this.
Adding the Youtube Video: We can easily add the Youtube videos in our app after installing the react-youtube package. For this example, we are going to add a text highlighter to our homepage.
Add the below content in the index.js file:
Javascript
import React from "react";import YouTube from "react-youtube";  export default class YoutubeVideo extends React.Component {  render() {    const opts = {      height: "390",      width: "640",      playerVars: {        autoplay: 1,      },    };      return (      <div>        <h3>GeeksforGeeks - Youtube</h3>        <YouTube videoId="sTnm5jvjgjM"             opts={opts} onReady={this._onReady} />      </div>    );  }    _onReady(event) {    event.target.pauseVideo();  }}
Explanation: In the above example first, we are importing the Youtube component from the installed package. After that, we are creating a new constant variable to store the settings of the video player. Then we are adding our videoId and options to our Youtube Component. You can find the videoId in the youtube video link.
Steps to run the application: Run the below command in the terminal to run the app.
npm run dev
Next.js
React-Questions
JavaScript
Node.js
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 detect browser or tab closing in JavaScript ?
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Express.js express.Router() Function
Node.js fs.readFile() Method
Python – Convert Values into proportions

08 May, 2020
Sometimes, while working with Python dictionaries, we can have problem in which we need to convert the values into proportions with respect to total. This can have applications in Data Science and Machine Learning domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + loopThe combination of above functionalities can be used to solve this problem. In this, we perform the task of finding sum using sum(). And the task of division is done inside a loop using division with sum of each value.
# Python3 code to demonstrate working of # Convert Values into proportions# Using sum() + loop  # initializing dictionarytest_dict = { 'gfg' : 10, 'is' : 15, 'best' : 20 }  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Convert Values into proportions# Using sum() + looptemp = sum(test_dict.values())for key, val in test_dict.items():    test_dict[key] = val / temp  # printing result print("The proportions divided values : " + str(test_dict)) 
The original dictionary is : {‘is’: 15, ‘best’: 20, ‘gfg’: 10}The proportions divided values : {‘is’: 0.3333333333333333, ‘best’: 0.4444444444444444, ‘gfg’: 0.2222222222222222}
 
Method #2 : Using dictionary comprehension + sum()The combination of above functions can be used to perform this task. In this, we calculate sum in similar manner as above method, and dictionary comprehension is used to perform the task of looping in one liner.
# Python3 code to demonstrate working of # Convert Values into proportions# Using dictionary comprehension + sum()  # initializing dictionarytest_dict = { 'gfg' : 10, 'is' : 15, 'best' : 20 }  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Convert Values into proportions# Using dictionary comprehension + sum()temp = sum(test_dict.values())res = {key: val / temp for key, val in test_dict.items()}  # printing result print("The proportions divided values : " + str(res)) 
The original dictionary is : {‘is’: 15, ‘best’: 20, ‘gfg’: 10}The proportions divided values : {‘is’: 0.3333333333333333, ‘best’: 0.4444444444444444, ‘gfg’: 0.2222222222222222}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
Python | Pandas Dataframe.to_dict()

01 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas .to_dict() method is used to convert a dataframe into a dictionary of series or list like data type depending on orient parameter.
Syntax: DataFrame.to_dict(orient=’dict’, into=)
Parameters:orient: String value, (‘dict’, ‘list’, ‘series’, ‘split’, ‘records’, ‘index’) Defines which dtype to convert Columns(series into). For example, ‘list’ would return a dictionary of lists with Key=Column name and Value=List (Converted series).into: class, can pass an actual class or instance. For example in case of defaultdict instance of class can be passed. Default value of this parameter is dict.
Return type: Dataframe converted into Dictionary
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1: Default conversion into dictionary of DictionariesIn this case, no parameter is passed to the to_dict() method. Hence it will convert the dataframe in to a dictionary of dictionaries by default.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # converting to dictdata_dict = data.to_dict()  # displaydata_dict
Output:As shown in the output image, dictionary of dictionaries was returned by to_dict() method. The key of first dictionary is column name and the column is stored with index as key of 2nd dictionary. Example #2: Converting to dictionary of Series
In this example, ‘series’ is passed to the orient parameter to convert the data frame into Dictionary of Series.
# importing pandas module import pandas as pd  # reading csv file from url data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # dropping null value columns to avoid errorsdata.dropna(inplace = True)  # converting to dictdata_dict = data.to_dict('series')  # printing datatype of first keys value in dictprint(type(data_dict['Name']))  # displaydata_dict
Output:As shown in the output image, Since the type of data_dict[‘Name’] was pandas.core.series.Series, to_dict() returned a dictionary of series.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use aggregate Function in R

19 Dec, 2021
In this article, we will discuss how to use aggregate function in R Programming Language.
aggregate() function is used to get the summary statistics of the data by group. The statistics include mean, min, sum. max etc.
Syntax:
aggregate(dataframe$aggregate_column, list(dataframe$group_column), FUN) 
where
dataframe is the input dataframe.
aggregate_column is the column to be aggregated in the dataframe.
group_column is the column to be grouped with FUN.
FUN represents sum/mean/min/ max.
Example 1: R program to create with 4 columns and group with subjects and get the aggregates like minimum, sum, and maximum.
R
# create a dataframe with 4 columnsdata = data.frame(subjects=c("java", "python", "java",                             "java", "php", "php"),                  id=c(1, 2, 3, 4, 5, 6),                  names=c("manoj", "sai", "mounika",                          "durga", "deepika", "roshan"),                  marks=c(89, 89, 76, 89, 90, 67))  # displayprint(data)  # aggregate sum of marks with subjectsprint(aggregate(data$marks, list(data$subjects), FUN=sum))  # aggregate minimum  of marks with subjectsprint(aggregate(data$marks, list(data$subjects), FUN=min))  # aggregate maximum of marks with subjectsprint(aggregate(data$marks, list(data$subjects), FUN=max))
Output:
Example 2: R program to create with 4 columns and group with subjects and get the average (mean).
R
# create a dataframe with 4 columnsdata = data.frame(subjects=c("java", "python", "java",                             "java", "php", "php"),                  id=c(1, 2, 3, 4, 5, 6),                  names=c("manoj", "sai", "mounika",                          "durga", "deepika", "roshan"),                  marks=c(89, 89, 76, 89, 90, 67))  # displayprint(data)  # aggregate average of marks with subjectsprint(aggregate(data$marks, list(data$subjects), FUN=mean))
Output:
Picked
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Check whether string contains only numbers or not

22 Sep, 2021
Given a string, write a Python program to find whether a string contains only numbers or not. Let’s see a few methods to solve the above task.Method #1: Using isdigit() method  
Python3
# Python3 code to demonstrate# how to check whether string contains# only numbers or not # Initialising stringini_string1 = '1234556'ini_string2 = 'ab123bc' # printing initial stringprint ("Initial Strings : ", ini_string1, ini_string2) # Using isdigit()if ini_string1.isdigit():    print ("String1 contains all numbers")else:    print ("String1 doesn't contains all numbers")     if ini_string2.isdigit():    print ("String2 contains all numbers")else:    print ("String2 doesn't contains all numbers")
Initial Strings :  1234556 ab123bc
String1 contains all numbers
String2 doesn't contains all numbers
 
  Method #2: Using regex  
Python3
# Python3 code to demonstrate# how to check whether string contains# only numbers or notimport re # Initialising stringini_string1 = '1234556'ini_string2 = 'ab123bc' # printing initial stringprint ("Initial Strings : ", ini_string1, ini_string2) # Using regex()if re.match('^[0-9]*$', ini_string1):    print ("String1 contains all numbers")else:    print ("String1 doesn't contains all numbers")     if re.match('^[0-9]*$', ini_string2):    print ("String2 contains all numbers")else:    print ("String2 doesn't contains all numbers")
Initial Strings :  1234556 ab123bc
String1 contains all numbers
String2 doesn't contains all numbers
 
  Method #3: Using try/exception  
Python3
# Python3 code to demonstrate# how to check whether string contains# only numbers or not # Initialising stringini_string1 = '1234556'ini_string2 = 'abc123' # printing initial stringprint ("Initial Strings : ", ini_string1, ini_string2) # Using try / exception:try:    num = int(ini_string1)    print ("String1 contains only digits")except:    print ("String1 doesn'tcontains only digits")     try:    num = int(ini_string2)    print ("String2 contains only digits")except:    print ("String2 doesn't contains only digits")    
Initial Strings :  1234556 abc123
String1 contains only digits
String2 doesn't contains only digits
 
anikakapoor
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream sorted() in Java

06 Dec, 2018
Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements.
Syntax :
Stream<T> sorted()

Where, Stream is an interface and T
is the type of stream elements.

Exception : If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.
Below given are some examples to understand the implementation of the function in a better way.
Example 1 :
// Implementation of Stream.sorted()// to get a stream of elements// sorted in their natural orderimport java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a list of integers        List<Integer> list = Arrays.asList(-9, -18, 0, 25, 4);          System.out.println("The sorted stream is : ");          // displaying the stream with elements        // sorted in natural order        list.stream().sorted().forEach(System.out::println);    }}
The sorted stream is : 
-18
-9
0
4
25

Example 2 :
// Implementation of Stream.sorted()// to get a stream of elements// sorted in their natural orderimport java.util.*;  class GFG {      // Driver code    public static void main(String[] args)    {          // Creating a list of strings        List<String> list = Arrays.asList("Geeks", "for",                     "GeeksQuiz", "GeeksforGeeks", "GFG");          System.out.println("The sorted stream is : ");          // displaying the stream with elements        // sorted in their natural order        list.stream().sorted().forEach(System.out::println);    }}
The sorted stream is : 
GFG
Geeks
GeeksQuiz
GeeksforGeeks
for

Example 3 :
// Using stream sorted to sort a stream// of user defined class objectsimport java.util.*;  class Point{    Integer x, y;    Point(Integer x, Integer y) {        this.x = x;        this.y = y;    }          public String toString() {         return this.x + ", "+ this.y;    } }  class GFG{    public static void main(String[] args)    {          List<Point> aList = new ArrayList<>();        aList.add(new Point(10, 20));        aList.add(new Point(5, 10));        aList.add(new Point(1, 100));        aList.add(new Point(50, 2000));          // displaying the stream with elements        // sorted according to x coordinate        aList.stream()        .sorted((p1, p2)->p1.x.compareTo(p2.x))        .forEach(System.out::println);    }}
1, 100
5, 10
10, 20
50, 2000

Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
MonthName() and Now() function in MS Access

03 Sep, 2020
1. MonthName() Function :MonthName() Function returns the month name based on the number. In this function the first parameter will be the month number and the second parameter will be the abbreviate. It will be optional. If we will pass abbreviate as true then month name should be abbreviated otherwise not. If we did not pass any value in the place of abbreviate then by default it takes false. Jan will 1st number month and dec will be 12th number month.
Syntax :
MonthName(number, abbreviate) 
Example-1 :
SELECT MonthName(7);
Output –
July
Example-2 :
SELECT MonthName(3, FALSE);
Output –
Mar
2. Now() Function :Now() function returns the current date and time of the computer system. In this function, no parameter will pass it return current date-time.
Syntax :
Now()
Example :
SELECT Now();
Output –
9/3/2020 2:10:29 AM
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Reverse a words in a line and keep the special characters untouched

24 Mar, 2022
Reverse the characters in all words in a line including numbers, but leave special characters and symbols untouched in the same position. Consider the below examples.
Input: ‘Bangalore is@#$!123 locked again in jul2020’ should change to Output: ‘erolagnaB si@#$!321 dekcol niaga ni 0202luj’ 
Input: ‘Bangalore is@#$!123locked locked again in jul2020’ should change to Output: ‘erolagnaB si@#$!dekcol321 dekcol niaga ni 0202luj’  
Look at the above example, each word is reversed, if there is any special character, then the word surrounding the special character gets reversed.
Python3
def reverStringsInLine(s):       sl = s.split(' ')    rsl = ''         for word in sl:        str_word = ''        rev_sub_word = ''                 for ch in word:                         if ch.isalnum():                str_word += ch                         else:                                 # If it is special character, then                # reverse non special characters and                # append special character                                 rev_sub_word += str_word[::-1] + ch                                 # Clear the old stached character, as                # it is already reversed                str_word = ''                 # Keep appending each words, also add words        # ending with non-special character        r_word = rev_sub_word + str_word[::-1]        rsl += r_word + ' '    return rsl  s = 'Bangalore is@#$!123locked locked again in jul2020' print(reverStringsInLine(s))
Output:
erolagnaB si@#$!dekcol321 dekcol niaga ni 0202luj 
singghakshay
surinderdawra388
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Create an Area chart using Recharts in ReactJS

27 Jul, 2021
Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).  
To create Area Chart using Recharts, we create a dataset that contains actual data. Then we define the slices using area element with data property which will have the data of the dataset created and with datakey property which is the property name with a value for the slices.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save recharts
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react';import { AreaChart, Area, CartesianGrid, XAxis, YAxis } from 'recharts';    const App = () => {  // Sample dataconst data = [  {name: 'Geeksforgeeks', students: 400},  {name: 'Technical scripter', students: 700},  {name: 'Geek-i-knack', students: 200},  {name: 'Geek-o-mania', students: 1000}];    return (<AreaChart width={600} height={600} data={data}>    <Area dataKey="students" fill="green" stroke="green" />    <CartesianGrid stroke="#ccc" />    <XAxis dataKey="name" />    <YAxis />  </AreaChart>);}  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Output
React-Questions
Recharts
JavaScript
ReactJS
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
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
How to create a zebra striped table with CSS?

To create a zebra stripped table with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
   table {
      border-collapse: collapse;
      border-spacing: 0;
      width: 100%;
      border: 1px solid #ddd;
   }
   th, td {
      font-weight: bold;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      font-size: 18px;
      text-align: left;
      padding: 16px;
   }
   tr:nth-child(even) {
      background-color: #8b8b8b;
      color: white;
   }
</style>
</head>
<body>
<h1>Zebra Striped Table Example</h1>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>BirthMonth</th>
</tr>
<tr>
<td>Jack</td>
<td>Roy</td>
<td>January</td>
</tr>
<tr>
<td>Steve</td>
<td>Smith</td>
<td>March</td>
</tr>
<tr>
<td>Brandon</td>
<td>Anderson</td>
<td>February</td>
</tr>
<table>
</body>
</html>
The above code will produce the following output −
How to Find the Sum of Natural Numbers using Python?

You can use while loop to successively increment value of a variable i by one and adding it cumulatively.
s,i=0,0
n=10
while i<n:
   i=i+1
   s=s+i
print ("sum of first 10 natural numbers",s)
For loop is also used to loop over a range of natural numbers and add them cumulatively.
s=0
for i in range(11):
   s=s+i
print ("sum of first 10 natural numbers",s)
Lastly using the built in function sum() also gives sum of a range of numbers
s=sum(range(11))
print ("sum of first 10 natural numbers",s)
What is a malloc function in C language?

The malloc() function stands for memory allocation, that allocate a block of memory dynamically.
It reserves the memory space for a specified size and returns the null pointer, which points to the memory location.
malloc() function carries garbage value. The pointer returned is of type void.
The syntax for malloc() function is as follows −
ptr = (castType*) malloc(size);
The following example shows the usage of malloc() function.
 Live Demo
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(){
   char *MemoryAlloc;
   /* memory allocated dynamically */
   MemoryAlloc = malloc( 15 * sizeof(char) );
   if(MemoryAlloc== NULL ){
      printf("Couldn't able to allocate requested memory\n");
   }else{
      strcpy( MemoryAlloc,"TutorialsPoint");
   }
   printf("Dynamically allocated memory content : %s\n", MemoryAlloc);
   free(MemoryAlloc);
}
When the above program is executed, it produces the following result −
Dynamically allocated memory content: TutorialsPoint
MySQL DateTime Now()+5 days/hours/minutes/seconds?

To update the current date and time to 5 days, you need to use the Now() + 5. That would update the entire date-time i.e. days, hour, minutes and seconds. To understand this, let us create a table. The query to create a table is as follows −
mysql> create table UserInformationExpire
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(10),
   -> UserInformationExpireDateTime datetime not null
   -> );
Query OK, 0 rows affected (0.83 sec)
Now you can insert some records in the table using insert command. The query is as follows −
mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime)
values('Maxwell','2019-02-09 23:56:27');
Query OK, 1 row affected (0.22 sec)
mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime)
values('Carol','2018-11-21 15:45:21');
Query OK, 1 row affected (0.24 sec)
mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime)
values('Bob','2019-01-22 16:30:35');
Query OK, 1 row affected (0.25 sec)
mysql> insert into UserInformationExpire(UserName,UserInformationExpireDateTime)
values('Larry','2017-12-25 17:20:33');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using a select statement. The query is as follows −
mysql> select *from UserInformationExpire;
+----+----------+-------------------------------+
| Id | UserName | UserInformationExpireDateTime |
+----+----------+-------------------------------+
|  1 | Maxwell  | 2019-02-09 23:56:27           |
|  2 | Carol    | 2018-11-21 15:45:21           |
|  3 | Bob      | 2019-01-22 16:30:35           |
|  4 | Larry    | 2017-12-25 17:20:33           |
+----+----------+-------------------------------+
4 rows in set (0.00 sec)
Here is your syntax to update the current datetime to 5 days/hours/minutes/seconds for id = 1 i.e. the current date is 2019-02-09 and it will be updated to 2019-02-14
mysql> update UserInformationExpire set UserInformationExpireDateTime = now()+interval 5
day where Id = 1;
Query OK, 1 row affected (0.24 sec)
Rows matched: 1 Changed: 1 Warnings: 0
Now check the table records once again to verify the date and time has been updated for only id 1 −
mysql> select *from UserInformationExpire where Id = 1;
+----+----------+-------------------------------+
| Id | UserName | UserInformationExpireDateTime |
+----+----------+-------------------------------+
|  1 | Maxwell  | 2019-02-14 23:56:27           |
+----+----------+-------------------------------+
1 row in set (0.00 sec)
Java Examples - Array output

How to write an array of strings to the output console ?
Following example demonstrates writing elements of an array to the output console through looping.
public class Welcome {
   public static void main(String[] args) {
      String[] greeting = new String[3];
      greeting[0] = "This is the greeting";
      greeting[1] = "for all the readers from";
      greeting[2] = "Java Source .";
      
      for (int i = 0; i < greeting.length; i++){
         System.out.println(greeting[i]);
      }
   }
}
The above code sample will produce the following result.
This is the greeting
For all the readers From
Java source .

Following example demonstrates writing elements of an array to the output console
import java.util.Arrays;

public class HelloWorld {
   public static void main(String[] args) {
      String[] arr = new String[] {"Tutorials", "Point", ".com"}; 
      System.out.println(Arrays.toString(arr));
   }
}
The above code sample will produce the following result.
[Tutorials, Point, .com]    .

Following example demonstrates writing elements of an array to the output console through looping.
import java.util.Arrays;

public class HelloWorld {
   public static void main(String[] args) {
      String[][] deepArr = new String[][] {{"Sai", "Gopal"}, {"Pallavi", "Priya"}};
      System.out.println(Arrays.toString(deepArr));
      System.out.println(Arrays.deepToString(deepArr));
   }
}
The above code sample will produce the following result.
[[Sai, Gopal], [Pallavi, Priya]]  

 Print
 Add Notes
 Bookmark this page
Git Pull Branch from GitLab

Now continue working on our new branch in our local Git.
Lets pull from our GitLab repository again so that our code is up-to-date:
git pull
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 2), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 429 bytes | 2.00 KiB/s, done.
From https://gitlab.com/w3schools-test/hello-world
 * [new branch]      html-skeleton -> origin/html-skeleton
Already up to date.
Now our main branch is up todate. And we can see that there is a new branch available on GitLab.
Do a quick status check:
git status
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
And confirm which branches we have, and where we are working at the moment:
git branch
* master
So, we do not have the new branch on our local Git. But we know it is available on GitLab. So we can use the -a option to see all local and remote branches:
git branch -a
* master
  remotes/origin/html-skeleton
  remotes/origin/master
Note: branch -r is for remote branches only.
We see that the branch html-skeleton is available remotely, but not on our local git. Lets check it out:
git checkout html-skeleton
Switched to a new branch 'html-skeleton'
Branch 'html-skeleton' set up to track remote branch 'html-skeleton' from 'origin'.
And check if it is all up to date:
git pull
Already up to date.
Which branches do we have now, and where are we working from?
git branch
* html-skeleton
  master
Now, open your favourite editor and confirm that the changes from the GitLab branch carried over.
That is how you pull a GitLab branch to your local Git.
List all local and remote branches of the current Git.
git  


Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Program to convert speed in km/hr to m/sec and vice versa in C++

Conversion Formulas −
1 km/hr = 5/18 m/sec or 0.277778 m/sec
1 m/sec = 18/5 km/hr or 3.6 km/hr
Example
Input-: km = 60.00
   mk = 70.00
Output-: speed in meter per second = 16.6667
   speed in km per hour = 252
Start
Step 1 -> Declare function to convert km/hr into m/sec
   float km_m(float km)
      return (0.277778 * km)
Step 2 -> Declare function to convert m/sec into km/hr
   float m_km(float mk)
      return (3.6 * mk)
step 3 -> In main()
   declare variable as float km = 60.0 and float mk = 70.0
   Print km_m(km)
   Print m_km(mk);
Stop
#include <bits/stdc++.h>
using namespace std;
//function to convert km/hr into m/sec
float km_m(float km){
   return (0.277778 * km);
}
//function to convert m/sec into km/hr
   float m_km(float mk){
      return (3.6 * mk);
}
int main(){
   float km = 60.0;
   float mk = 70.0;
   cout << "speed in meter per second = " << km_m(km)<<endl<< " speed in km per hour = " << m_km(mk);
   return 0;
}
speed in meter per second = 16.6667
speed in km per hour = 252
How to handle very large numbers in Python?

You can perform arithmetic operations on large numbers in python directly without worrying about speed. Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.
As long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.
a = 182841384165841685416854134135
b = 135481653441354138548413384135
print(a - b)
This will give the output −
47359730724487546868440750000
PHP - Function file_put_contents()

The file_put_contents() function can write a string to file. 
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

 If successful, the function can return the number of characters written to the file. If it fails, it can return false. 
<?php
   echo file_put_contents("PhpProject/sample.txt" ,"Hello World!");
?> 
11

<?php
   $file = "/PhpProject1/sample.txt";
   // The new person to add to the file
   $test = " Tutorialspoint";
   // using the FILE_APPEND flag to append the content to the end of the file
   // and the LOCK_EX flag to prevent anyone else writing to the file at the same time
   file_put_contents($file, $test, FILE_APPEND | LOCK_EX);
   echo "Content has been loaded successfully";
?>

Content has been loaded successfully


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers

When it is required to find all the numbers that are odd, and are palindromes and lie between a given range of values, and it has been told that recursion can’t be used, then, list comprehension, and ‘%’ operator can be used to achieve the same.
Palindromes are string that are same when they are read in either way- left to right and right to left.
Below is a demonstration for the same −
 Live Demo
my_list = []
lower_limit = 5
upper_limit = 189
print("The lower limit is : ")
print(lower_limit)
print("The upper limit is : ")
print(upper_limit)
my_list = [x for x in range(lower_limit,upper_limit+1) if x%2!=0 and str(x)==str(x)[::-1]]
print("The numbers which are odd and palindromes between " + str(lower_limit) + " and " + str(upper_limit) + " are : ")
print(my_list)
The lower limit is :
5
The upper limit is :
189
The numbers which are odd and palindromes between 5 and 189 are :
[5, 7, 9, 11, 33, 55, 77, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181]
An empty list, a lower limit and an upper limit is defined.
The upper and lower limit are displayed on the console.
The values between upper and lower limit are iterated over, and checked to see if it is divisible by 2.
Then, it is converted to a string, and elements from the end of the string and the string are compared.
This is assigned to a variable.
This is displayed as output on the console.
How to set the alignment of labels in horizontal bar plot to left in R?

When we create a horizontal bar plot using ggplot2 package, the labels of the categorical variable are aligned to the right-side of the axis and if the size of these labels are different then it looks a little ambiguous. Therefore, we might want to set the alignment of the labels to left-side and this can be done by using theme function of ggplot2 package.
Consider the below data frame:
> df<-data.frame(x,y)
> df
    x     y
1 India  14
2 UK     15
3 Russia 12
4 United States of America 18
Loading ggplot2 package and creating a horizontal bar plot:
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_bar(stat="identity")+coord_flip()
Creating the horizontal bar plot with categorical variable labels aligned to left-side:
> ggplot(df,aes(x,y))+geom_bar(stat="identity")+coord_flip()+theme(axis.text.y=element_text(hjust=0))
VBScript Right Function

The Right Function returns a specified number of characters from the right side of the given input string.
Right(String, Length)

String, a Required Parameter. Input String from which the specified number of characters to be returned from Right side.
String, a Required Parameter. Input String from which the specified number of characters to be returned from Right side.
Length, a Required Parameter. An Integer, which Specifies the number of characters to be returned.
Length, a Required Parameter. An Integer, which Specifies the number of characters to be returned.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "Microsoft VBScript"
         document.write("Line 1 : " & Right(var,2) & "<br />")
         
         var = "MS VBSCRIPT"
         document.write("Line 2 : " & Right(var,5) & "<br />")
         
         var = "microsoft"
         document.write("Line 3 : " & Right(var,9) & "<br />")
      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : pt
Line 2 : CRIPT
Line 3 : microsoft


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
C - Bitwise Operators Examples

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
Try following example to understand all the Bitwise  operators. Copy and paste following C program in test.c file and compile and run this program.
main()
{

   unsigned int a = 60;	/* 60 = 0011 1100 */  
   unsigned int b = 13;	/* 13 = 0000 1101 */
   int c = 0;           

   c = a & b;       /* 12 = 0000 1100 */ 
   printf("Line 1 - Value of c is %d\n", c );

   c = a | b;       /* 61 = 0011 1101 */
   printf("Line 2 - Value of c is %d\n", c );

   c = a ^ b;       /* 49 = 0011 0001 */
   printf("Line 3 - Value of c is %d\n", c );

   c = ~a;          /*-61 = 1100 0011 */
   printf("Line 4 - Value of c is %d\n", c );

   c = a << 2;     /* 240 = 1111 0000 */
   printf("Line 5 - Value of c is %d\n", c );

   c = a >> 2;     /* 15 = 0000 1111 */
   printf("Line 6 - Value of c is %d\n", c );
}

This will produce following result
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15


Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
How to get Resource Name using Resource id in Android using Kotlin?

This example demonstrates how to get Resource Name using Resource id in Android using Kotlin.
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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/relativeLayout"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:background="#008080"
      android:padding="5dp"
      android:text="TutorialsPoint"
      android:textColor="#fff"
      android:textSize="24sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_marginTop="20dp"
      android:text=""
      android:textColor="@android:color/holo_red_light"
      android:textSize="24sp"
      android:textStyle="bold|italic" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val textView: TextView = findViewById(R.id.textView)
      val text: Int = textView.id
      val string = resources.getResourceName(text)
      textView.text = "Resource ID: $string"
   }
}
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.q11">
   <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 the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.
GATE | GATE-CS-2017 (Set 2) | Question 24 - GeeksforGeeks

01 Oct, 2021
Let L1 and L2 be any context-free language and R be any regular language. Then, which of the following is correct ?
I. L1 ∪ L2 is context-free.
II. L1' is context-free.
III. L1-R is context-free.
IV. L1 ∩ L2 context-free.

(A) I, II and IV only(B) I and III only(C) II and IV only(D) I onlyAnswer: (B)Explanation: Context free language are closed under union and difference with regular language.It is not closed under complementation and intersection . Complement of CFL is recursive language.
YouTubeGeeksforGeeks GATE Computer Science16K subscribersGATE PYQ's on Grammars with Praddyumn Shukla | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0025:42 / 56:03•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2_61UCrVLc8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2011 | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2009 | Question 60