code-rag-bench/online-tutorials huggingface dataset:
How to merge multiple documents in MongoDB?

To merge multiple documents in MongoDB, use aggregate(). Let us create a collection with documents −
> db.demo436.insertOne(
...    {
...       "_id" : "101",
...       "Name": "Chris",
...       "details" : [
...          {
...             "CountryName" : "US",
...             "Age" : 21
...          }
...       ],
...       "Price" : 50
...    }
... );
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo436.insertOne(
...    {
...       "_id" : "102",
...       "Name": "Chris",
...       "details" : [
...          {
...             "CountryName" : "UK",
...             "Age" : 22
...          }
...       ],
...       "Price" : 78
...    }
... );
{ "acknowledged" : true, "insertedId" : "102" }
> db.demo436.insertOne(
...    {
...       "_id" : "103",
...       "Name": "Chris",
...       "details" : [
...          {
...             "CountryName" : "US",
...             "Age" : 21
...          }
...       ],
..      . "Price" : 50
...    }
... );
{ "acknowledged" : true, "insertedId" : "103" }
Display all documents from a collection with the help of find() method −
> db.demo436.find();
This will produce the following output −
{ "_id" : "101", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 }
{ "_id" : "102", "Name" : "Chris", "details" : [ { "CountryName" : "UK", "Age" : 22 } ], "Price" : 78 }
{ "_id" : "103", "Name" : "Chris", "details" : [ { "CountryName" : "US", "Age" : 21 } ], "Price" : 50 }
Following is the query to merge multiple documents in MongoDB −
> db.demo436.aggregate([
...    {$sort: {_id: 1, Name: 1}},
...    {$unwind: '$details'},
...    {$group: {_id: '$Name', details: {$push: '$details'},
...    Price: {$sum: '$Price'},
...    id: {$last: {$concat: ["$_id", "_", "AppendedValue" ]}},
...    Name: {$last: '$Name'}}},
...    {$addFields: {Id: 'NewIdAppped', _id: '$id'}},
...    {$project: {"id": 0 }}])
This will produce the following output −
{ "_id" : "103_AppendedValue", "details" : [ { "CountryName" : "US", "Age" : 21 }, { "CountryName" : "UK", "Age" : 22 }, { "CountryName" : "US", "Age" : 21 } ], "Price" : 178, "Name" : "Chris", "Id" : "NewIdAppped" }
Add Titles to a Graph in R Programming - title() Function - GeeksforGeeks

20 Jul, 2020
title() function in R Language is used to add main title and axis title to a graph. This function can also be used to modify the existing titles.
Syntax:title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL, ...)
Parameters:main: Main title of the graphsub: Defines subtitles
Returns: Plot after title addition
Example 1:
# R program to add title to a Graph  # Specifying axis valuesx<-1:5; y<-x*x  # Creating a plotplot(x, y, main = "", xlab = "", ylab = "",     col.axis = "darkgreen")   # Calling title() functiontitle(main = "Graph ", sub = "Geeksforgeeks article",      xlab = "X axis", ylab = "Y axis",      cex.main = 4,   font.main = 3, col.main = "darkgreen",      cex.sub = 2, font.sub = 3, col.sub = "darkgreen",      col.lab ="black"      )
Output:
In above example main title and sub titles are added to the plot. The arguments that can be used to change the font size are as follows:
cex.main: size for main title
cex.lab: text size for axis title
cex.sub: text size of the sub-title
Example 2:
barplot(c(1, 10) )title(main = "PLOT ", sub = "Geeksforgeeks article",      xlab = "X axis", ylab = "Y axis",    # Change the colors  col.main="darkgreen", col.lab="black", col.sub="darkgreen",    # Titles in italic and bold  font.main = 4, font.lab = 4, font.sub = 3,    # Change font size  cex.main = 3, cex.lab = 1.7, cex.sub = 2  )
Output:
R Graphics-Functions
R-Graphs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Find minimum steps required to reach the end of a matrix in C++

Suppose we have a 2D matrix with positive integers. We have to find the minimum steps required to move from to the end of the matrix (rightmost bottom cell), If we are at cell (i, j), we can go to the cell (i, j+mat[i, j]) or (i+mat[i, j], j), We cannot cross the bounds. So if the matrix is like −
The output will be 2. Path will be (0, 0) →(0, 2) → (2, 2)
Here we will use the Dynamic programming approach to solve this. Suppose we are at cell (i, j), we want to reach (n-1, n-1) cell. We can use the recurrence relation like below −
DP[i, j]=1+min ⁡(DP [i+arr [i , j] , j], DP[i , j+arr [ i , j]])
#include<iostream>
#define N 3
using namespace std;
int table[N][N];
bool temp_val[N][N];
int countSteps(int i, int j, int arr[][N]) {
   if (i == N - 1 and j == N - 1)
      return 0;
   if (i > N - 1 || j > N - 1)
      return INT_MAX;
   if (temp_val[i][j])
      return table[i][j];
   temp_val[i][j] = true;
   table[i][j] = 1 + min(countSteps(i + arr[i][j], j, arr), countSteps(i, j + arr[i][j], arr));
   return table[i][j];
}
int main() {
   int arr[N][N] = { { 2, 1, 2 }, { 1, 1, 1 }, { 1, 1, 1 } };
   int ans = countSteps(0, 0, arr);
   if (ans >= INT_MAX)
      cout << -1;
   else
      cout <<"Number of steps: "<< ans;
}
Number of steps: 2
How can I set a MySQL database to use MyISAM by default?

To set the default storage engine, use the following syntax −
set @@default_storage_engine = ’yourEngineType’;
Now implement the above syntax to set the default engine to MyISAM. The query is as follows −
mysql> set @@default_storage_engine = 'MyISAM';
Query OK, 0 rows affected (0.05 sec)
Now you can check the default engine type with the help of SELECT statement. The query is as follows −
mysql> select @@default_storage_engine;
The following is the output displaying the engine as MyISAM −
+--------------------------+
| @@default_storage_engine |
+--------------------------+
| MyISAM                   |
+--------------------------+
1 row in set (0.00 sec)
Now create a table and check for the default engine MyISAM.
Let us create a table. The query to create a table is as follows −
mysql> create table Followers
   -> (
   -> FollowerId int,
   -> FollowerName varchar(20)
   -> );
Query OK, 0 rows affected (0.32 sec)
Let us check the default engine type of the above table with the help of SHOW TABLE command. The query is as follows −
mysql> SHOW TABLE STATUS WHERE Name = 'Followers'\G
Name: followers
Engine: MyISAM
Version: 10
Row_format: Dynamic
Rows: 0
Avg_row_length: 0
Data_length: 0
Max_data_length: 281474976710655
Index_length: 1024
Data_free: 0
Auto_increment: 1
Create_time: 2019 - 02 - 12 00: 42: 27
Update_time: 2019 - 02 - 12 00: 42: 28
Check_time: NULL
Collation: utf8_general_ci
Checksum: NULL
Create_options:
Comment:
1 row in set(0.00 sec)
In MySQL version 8.0.12 the default engine is InnoDB but we have changed it above to MyISAM only for a session. If you restart the MySQL then the storage engine will be in the default MySQL mode i.e. InnoDB. Let’s restart MySQL. The query is as follows −
mysql> restart;
Query OK, 0 rows affected (0.20 sec)
Now check the default engine type once again. It would be InnoDB now −
mysql> select @@default_storage_engine;
No connection. Trying to reconnect...
Connection id: 8
Current database: sample
+--------------------------+
| @@default_storage_engine |
+--------------------------+
| InnoDB                   |
+--------------------------+
1 row in set (0.00 sec)
DAX Filter - HASONEVALUE function

Returns TRUE when the context for columnName has been filtered down to one distinct value only. Otherwise, returns FALSE.
HASONEVALUE (<columnName>) 

columnName
The name of a column. It cannot be an expression.
TRUE or FALSE.
= HASONEVALUE (Sales[Product]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to use Null Coalescing Operator (??) in C#?

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise, it returns the value of the first operand.
The following is an example −
 Live Demo
using System;

namespace Demo {

   class Program {

      static void Main(string[] args) {
         double? num1 = null;
         double? num2 = 6.32123;
         double num3;

         num3 = num1 ?? 9.77;
         Console.WriteLine(" Value of num3: {0}", num3);

         num3 = num2 ?? 9.77;
         Console.WriteLine(" Value of num3: {0}", num3);
         Console.ReadLine();
      }
   }
}
Value of num3: 9.77
Value of num3: 6.32123
Python - Delete rows/columns from DataFrame using Pandas.drop()

Pandas is one of the most popular python library for data analysis and data wrangling. In this article we will see how we can create a pandas dataframe and then delete some selective rows ort columns from this data frame.
In the below example we have the iris.csv file which is read into a data frame. We first have a look at the existing data frame and then apply the drop function to the index column by supplying the value we want to drop. As we can see at the bottom of the result set the number of rows has been reduced by 3.
import pandas as pd
# making data frame from csv file
data = pd.read_csv("E:\\iris1.csv",index_col ="Id")
print(data)
# dropping passed values
data.drop([6,9,10],inplace=True)
# display
print(data)
Running the above code gives us the following result −
   SepalLengthCm    SepalWidthCm    PetalLengthCm    PetalWidthCm    Species
Id
1    5.1                3.5             1.4             0.2       Iris-setosa
2    4.9                3.0             1.4             0.2       Iris-setosa
3    4.7                3.2             1.3             0.2       Iris-setosa
.   ..   ...   ....   ............
[150 rows x 5 columns]

After Dropping
   SepalLengthCm    SepalWidthCm    PetalLengthCm    PetalWidthCm    Species
Id
1      5.1                3.5             1.4             0.2       Iris-setosa
2      4.9                3.0             1.4             0.2       Iris-setosa
3      4.7                3.2             1.3             0.2       Iris-setosa
149    6.2                3.4             5.4             2.3       Iris-virginica
150    5.9                3.0             5.1             1.8       Iris-virginica
......................
[147 rows x 5 columns]
For dropping the columns form a pandas data frame, we use the axis parameter. Its value is set to one in the drop function and we supply the column names to be dropped. As you can see the number of columns in the result set gets reduced from 5 to 3.
import pandas as pd
# making data frame from csv file
data = pd.read_csv("E:\\iris1.csv",index_col ="Id")
print(data)
# dropping passed values
data.drop(['SepalWidthCm','PetalLengthCm'],axis=1,inplace=True)
print("After Dropping")
# display
print(data)
Running the above code gives us the following result −
   SepalLengthCm    SepalWidthCm    PetalLengthCm    PetalWidthCm    Species
Id
1       5.1          3.5                1.4             0.2          Iris-setosa
2       4.9          3.0                1.4             0.2          Iris-setosa
3       4.7          3.2                1.3             0.2          Iris-setosa
.   .   ....   ....   .....   .......
[150 rows x 5 columns]
After Dropping
   SepalLengthCm    PetalWidthCm    Species
Id
1    5.1             0.2             Iris-setosa
2    4.9             0.2             Iris-setosa
3    4.7             0.2             Iris-setosa
.........
[150 rows x 3 columns]
Python – Modulo of tuple elements

27 Dec, 2019
Sometimes, while working with records, we can have a problem in which we may need to perform modulo of tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of modulo using generator expression and mapping index of each tuple is done by zip().
# Python3 code to demonstrate working of# Tuple modulo# using zip() + generator expression  # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5)  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Tuple modulo# using zip() + generator expressionres = tuple(ele1 % ele2 for ele1, ele2 in zip(test_tup1, test_tup2))  # printing resultprint("The modulus tuple : " + str(res))
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 6, 7, 5)
The modulus tuple : (0, 4, 5, 1)

 
Method #2 : Using map() + modThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of modulus using mod and mapping is done by map().
# Python3 code to demonstrate working of# Tuple modulo# using map() + modfrom operator import mod  # initialize tuplestest_tup1 = (10, 4, 5, 6)test_tup2 = (5, 6, 7, 5)  # printing original tuplesprint("The original tuple 1 : " + str(test_tup1))print("The original tuple 2 : " + str(test_tup2))  # Tuple modulo# using map() + modres = tuple(map(mod, test_tup1, test_tup2))  # printing resultprint("The modulus tuple : " + str(res))
The original tuple 1 : (10, 4, 5, 6)
The original tuple 2 : (5, 6, 7, 5)
The modulus tuple : (0, 4, 5, 1)

Python tuple-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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
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 | Convert string dictionary to dictionary
How to open a website in Android’s web browser from any application?

This example demonstrates how do I open a website in Android’s web browser from any application.
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:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/btnAmazon"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Amazon"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Button button = findViewById(R.id.btnAmazon);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String url = "http://www.amazon.com";
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
         }
      });
   }
}
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="app.com.sample">
   <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.
How to convert Python date string mm/dd/yyyy to datetime?

You can convert a string to date object using the strptime function. Provide the date string and the format in which the date is specified. 
import datetime
date_str = '29/12/2017' # The date - 29 Dec 2017
format_str = '%d/%m/%Y' # The format
datetime_obj = datetime.datetime.strptime(date_str, format_str)
print(datetime_obj.date())
This will give the output −
2017-12-29
Python NLTK | tokenize.regexp()

07 Jun, 2019
With the help of NLTK tokenize.regexp() module, we are able to extract the tokens from string by using regular expression with RegexpTokenizer() method.
Syntax : tokenize.RegexpTokenizer()Return : Return array of tokens using regular expression
Example #1 :In this example we are using RegexpTokenizer() method to extract the stream of tokens with the help of regular expressions.
# import RegexpTokenizer() method from nltkfrom nltk.tokenize import RegexpTokenizer    # Create a reference variable for Class RegexpTokenizertk = RegexpTokenizer('\s+', gaps = True)    # Create a string inputgfg = "I love Python"    # Use tokenize methodgeek = tk.tokenize(gfg)    print(geek)
Output :
[‘I’, ‘love’, ‘Python’]
Example #2 :
# import RegexpTokenizer() method from nltkfrom nltk.tokenize import RegexpTokenizer    # Create a reference variable for Class RegexpTokenizertk = RegexpTokenizer('\s+', gaps = True)    # Create a string inputgfg = "Geeks for Geeks"    # Use tokenize methodgeek = tk.tokenize(gfg)    print(geek)
Output :
[‘Geeks’, ‘for’, ‘Geeks’]
Python-nltk
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Latches in Digital Logic

21 Jun, 2022
Latches are basic storage elements that operate with signal levels (rather than signal transitions). Latches controlled by a clock transition are flip-flops. Latches are level-sensitive devices. Latches are useful for the design of the asynchronous sequential circuit. Latches are sequential circuit with two stable states. These are sensitive to the input voltage applied and does not depend on the clock pulse. Flip flops that do not use clock pulse are referred to as latch.
SR (Set-Reset) Latch – They are also known as preset and clear states. The SR latch forms the basic building blocks of all other types of flip-flops.
SR Latch is a circuit with: (i) 2 cross-coupled NOR gate or 2 cross-coupled NAND gate. (ii) 2 input S for SET and R for RESET. (iii) 2 output Q, Q’. 
 
Under normal conditions, both the input remains 0. The following is the RS Latch with NAND gates: 
 
Case-1: S’=R’=1 (S=R=0) – If Q = 1, Q and R’ inputs for 2nd NAND gate are both 1. If Q = 0, Q and R’ inputs for 2nd NAND gate are 0 and 1 respectively. 
 
Case-2: S’=0, R’=1 (S=1, R=0) – As S’=0, the output of 1st NAND gate, Q = 1(SET state). In 2nd NAND gate, as Q and R’ inputs are 1, Q’=0. 
 
Case-3: S’= 1, R’= 0 (S=0, R=1) – As R’=0, the output of 2nd NAND gate, Q’ = 1. In 1st NAND gate, as Q and S’ inputs are 1, Q=0(RESET state). 
 
Case-4: S’= R’= 0 (S=R=1) – When S=R=1, both Q and Q’ becomes 1 which is not allowed. So, the input condition is prohibited. 
The SR Latch using NOR gate is shown below: 
 
Gated SR Latch – A Gated SR latch is a SR latch with enable input which works when enable is 1 and retain the previous state when enable is 0. 
 
Gated D Latch – D latch is similar to SR latch with some modifications made. Here, the inputs are complements of each other. The letter  in the D latch stands for “data” as this latch stores single bit temporarily.
The design of D latch with Enable signal is given below: 
 
The truth table for the D-Latch is shown below:  
As the output is same as the input D, D latch is also called as Transparent Latch. Considering the truth table, the characteristic equation for D latch with enable input can be given as:  
Q(n+1) = EN.D + EN'.Q(n)
Reference: DIGITAL ELECTRONICS – Atul P. Godse, Mrs. Deepali A. Godse 
manikandan20061999
animeshmaru16
dishaagrawal1
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Console.SetWindowPosition() Method in C#

14 Mar, 2019
Console.SetWindowPosition(Int32, Int32) Method in C# is used to set the position of the console window relative to the screen buffer.
Syntax: public static void SetWindowposition(int left, int top);
Parameters:left: It is the column position of the upper left corner of the console window.top: It is the row position of the upper left corner of the console window.
Exceptions:
ArgumentOutOfRangeException: When left or top is less than 0 or left + WindowWidth > BufferWidth or top + Windowheight > BufferHeight.
SecurityException: If the user doesn’t have the permission to perform this action.
Example:
// C# Program to illustrate the use of // Console.WindowPosition() methodusing System;using System.Text;using System.IO;  class GFG {       // Main Method    public static void Main(string[] args)    {        Console.SetWindowSize(20, 20);          // setting buffer size         Console.SetBufferSize(80, 80);          // using the method        Console.SetWindowPosition(0, 0);        Console.WriteLine("Hello GFG!");          Console.Write("Press any key to continue . . . ");        Console.ReadKey(true);    }}
Output:
When Console.WindowPosition() method is not used:
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.console.setwindowposition?view=netframework-4.7.2
CSharp-Console-Class
CSharp-method
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google Online Challenge for Summer Internship 2021

01 Oct, 2020
The Google online challenge 2020 for summer internships 2021 was held on Sept 26. It was a 60-minute online test having 2 questions to code.
First Question: You are given an array A with N integers. you are required to answer Q queries of the following types.
Determine the count of distinct prime numbers which divides all the numbers in a given range L to R. NOTE:1 based Indexing.
1 <=N,Q<= 10^5;
1 <= A[i] <= 10^5;
1 <= L <= R <= N
Input: 
No of test cases
Array size i.e N
N array elements
No of Queries i.e Q
Q queries
Output: Return count of distinct prime numbers which divides all the numbers in a given range for each query
Sample Input:  
1
6
4 6 3 18 36 54
3
1 2
3 6
4 6
Sample output:
1
1
2
I do not remember the second question exactly. But It was also based on arrays. Prepare for query-based array questions, MO’s algorithm, Segment tree(if possible) standard questions like range sum queries, update range queries, etc.
Google
Marketing
Internship
Interview Experiences
Google
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021
Zoho Interview Experience (Off-Campus ) 2022
Microsoft Interview Experience for SWE Intern
Microsoft Interview Experience for SWE Intern (On-Campus)
Cisco Interview Experience for Network Engineer (On-Campus) 2021
Amazon Interview Questions
Amazon Interview Experience for SDE 1
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience SDE-2 (3 Years Experienced)
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
How to Include *.so Library in Android Studio?

16 Jun, 2021
The SO file stands for Shared Library. You compile all C++ code into the.SO file when you write it in C or C++. The SO file is a shared object library that may be dynamically loaded during Android runtime. Library files are larger, often ranging from 2MB to 10MB in size. As a result, the app becomes bloated. Another thing to keep in mind is that several.SO files need to be included in the APK to support several architectures such as armeabi and x86. .so files are the ABI Files, ABI stands for Application Binary Interface. The ABI specifies how your app’s machine code should communicate with the OS during execution. The NDK is a software development kit. As a result, files are compared to these definitions.
So what if you want to include some .so files in your Android App or Android Project, well there are several ways to do that, but we will be finding out the perfect ones that can help you get the library included in no time! Keep on reading this article!
Create a folder called “jniLibs” in your app, along with the directories that contain your *.so. The “jniLibs” folder should be established alongside your “Java” and “Assets” directories.
It is feasible to avoid creating a new folder and maintain your *.so files in the libs folder! In that case, just place your *.so files in the libs folder (following the same architecture as Solution 1: libs/armeabi/.so, for example) and update your app’s build.gradle file to include the jniLibs source directory.
Put your .so files in the libs folder as shown in the folder to add them
Figure 1. Understanding the Structure of the .jar & so file
Then add this code to your project
compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')
task copyJniLibs(type: Copy) {
   from 'libs/armeabi'
   into 'src/main/jniLibs/armeabi'
}
tasks.withType(JavaCompile) {
   compileTask -> compileTask.dependsOn(copyJniLibs)
}
clean.dependsOn 'cleanCopyJniLibs'
If you’re using Android Studio 4.1.2, and have tried to specify the NDK
Path in File -> Project Structure -> SDK Location
Now you’ll need to manually configure the NDK version in local.properties and establish a jniLibs folder with the ABIs and their corresponding. so files in the build.gradle and defining the ABI filters and NDK version. That’s it for this article, hope you got your perfect solution on how to Include the .so file!
Android-Studio
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
How to Add Views Dynamically and Store Data in Arraylist in Android?
Introduction to Android Development
Animation in Android with Example
Fragment Lifecycle in Android
Data Binding in Android with Example
Keras - Permute Layers

Permute is also used to change the shape of the input using pattern. For example, if Permute with argument (2, 1) is applied to layer having input shape as (batch_size, 3, 2), then the output shape of the layer will be (batch_size, 2, 3)
Permute has one argument as follows −
keras.layers.Permute(dims)

A simple example to use Permute layers is as follows −
>>> from keras.models import Sequential 
>>> from keras.layers import Activation, Dense, Permute 
>>> 
>>> 
>>> model = Sequential() 
>>> layer_1 = Dense(16, input_shape = (8, 8)) 
>>> model.add(layer_1) 
>>> layer_2 = Permute((2, 1)) 
>>> model.add(layer_2) 
>>> layer_2.input_shape (None, 8, 16) 
>>> layer_2.output_shape (None, 16, 8)
>>>
where, (2, 1) is set as pattern.

    87 Lectures 
     11 hours 

 Abhilash Nelson

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    68 Lectures 
     2 hours 

 Mike West
 Print
 Add Notes
 Bookmark this page
What is the importance of jmod format in Java 9?

Java 9 has introduced a new format called "jmod" to encapsulate modules. The jmod files can be designed to handle more content types than jar files. It can also package local codes, configuration files, local commands, and other types of data. The "jmod" format hasn't support at runtime and can be based on zip format currently. The jmod format can be used at both compile and link time and can be found in JDK_HOME\jmods directory, where JDK_HOME is a directory. The files in jmod format have a ".jmod" extension.
Java 9 comes with a new tool called jmod, and it is located in the JDK_HOME\bin directory. It can be used to create a jmod file, list the contents of a jmod file, print a description of a module, and record the hash value of the module used.
jmod <subcommand> <options> <jmod-file>
The jmod command contains at least one of the following subcommands:
create
extract
list
describe
hash
The list and describe subcommands don't accept any options. The <jmod-file> is the jmod file to be created or the existing jmod file to be described.
Java public Keyword

❮ Java Keywords

Second accesses a public 
Main class with public attributes:
/* Code from filename: Main.java
public class Main {
  public String fname = "John";
  public String lname = "Doe";
  public String email = "john@doe.com";
  public int age = 24;
}
*/

class Second {
  public static void main(String[] args) {
    Main myObj = new Main();
    System.out.println("Name: " + myObj.fname + " " + myObj.lname);
    System.out.println("Email: " + myObj.email);
    System.out.println("Age: " + myObj.age);
  }
}


Try it Yourself »

The public keyword is an access modifier used for classes, attributes, methods and constructors, making them accessible by any other class.
Read more about modifiers in our Java Modifiers Tutorial.

❮ Java Keywords

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.
JavaScript | async function expression

08 Oct, 2021
Async function expression is used to define an async function inside an expression in JavaScript. The async function is declared using the async keyword. Syntax:  
async function [function_name]([param1[, param2[, ..., paramN]]]) {
    // Statements
}
Parameters:  
function_name: This parameter holds the function name. This function name is local to the function body. If function name is ommitted then it becomes anonymous function.
paramN: It is the name of parameter that to be passed into the function.
Statements: It contains the body of the function.
Return Value: It returns a promise to return the value or else throw an exception, whenever an error occurs.Example 1: In this example “GeeksforGeeks” is printed first and after an interval of 1000 ms, “GFG” is printed. 
javascript
<script>    function cb() {        return new Promise(function (resolve, reject) {            setTimeout(function () {                resolve("GFG")            }, 1000)         })    }    async function course() {        console.log("GeeksforGeeks");        const result = await cb();        console.log(result);    }     course();</script>
Output:  
GeeksforGeeks
GFG
Example 2: Here, a file is made gfg.txt and as soon as the file is read it prints “Read the file” in the console. Else it prints “error” when either the location of the file is wrong or it is not unable to read the file due to any other reason.  
javascript
<script>    async function gfg() {        try {            let f1 = await fs.promises.readFile("gfg.txt")            console.log("Read the file")        }        catch (err) {            console.log("error");        }    }    gfg();</script>
Output:  
When file read:  
Read the file
When file is not read(error thrown)  
error
Example 3: This is an example of async function working in parallel. 
javascript
<script>    function cb() {        return new Promise(function (resolve, reject) {            setTimeout(function () {                resolve("GFG")            }, 2000)         })    }     function cb1() {        return new Promise(function (resolve, reject) {            setTimeout(function () {                resolve("GFG1")            }, 1000)         })    }     async function course() {        console.log("GeeksforGeeks");        const result1 = await cb1();        const result = await cb();        console.log(result1);        console.log(result);    }     course();</script>
Output:  
GeeksforGeeks
GFG1
GFG
Supported Browsers:  
Google Chrome 55 and above
Edge 15 and above
Firefox 52 and above
Safari 10.1 and above
Opera 42 and above
 
riarawal99
ysachin2314
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Construct a Turing Machine for L = {a^n b^n | n>=1}

The Turing machine (TM) is more powerful than both finite automata (FA) and pushdown automata (PDA). They are as powerful as any computer we have ever built.
A Turing machine can be formally described as seven tuples
(Q,X, Σ, δ,q0,B,F)
Where,
Q is a finite set of states
Q is a finite set of states
X is the tape alphabet
X is the tape alphabet
Σ is the input alphabet
Σ is the input alphabet
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
δ is a transition function: δ:QxX→QxXx{left shift, right shift}
q0 is the initial state
q0 is the initial state
B is the blank symbol
B is the blank symbol
F is the final state.
F is the final state.
A Turing Machine (TM) is a mathematical model which consists of an infinite length tape divided into cells on which input is given. It consists of a head which reads the input tape. A state register stores the state of the Turing machine.
After reading an input symbol, it is replaced with another symbol, its internal state is changed, and it moves from one cell to the right or left. If the TM reaches the final state, the input string is accepted, otherwise rejected.
The Turing machine has a read/write head. So we can write on the tape.
Now, let us construct a Turing machine which accepts equal number of a’s and b’s,
The language it is generated is L ={ anbn | n>=1}, the strings that are accepted by the given language is −
L= {ab, aabb, aaabbb, aaaabbbb,.........}
Consider n=3 so, a3b3 , the tape looks like −
B= blank
We need to convert every ‘a’ as X and every ‘b’ as Y. If the Turing machine contains an equal number of X and Y then it reaches the final state.
Step 1 − Consider the initial state as q0. This state replace ‘a’ as X and move to right, now state changes for q0 toq1, so the transition function is −
δ(q0, a) = (q1,X,R)
Step 2 − Move right until you see the blank symbol.
δ(q1, a) = (q1,a,R)
δ(q1, b) = (q1,b,R)
After reaching the blank symbol B, move left and change the state to q2, because we need to change the last ‘b’ to Y.
δ(q1, B) = (q2,B,L) //1st iteration
δ(q1, Y) = (q2,Y,L) // remaining iterations
Step 3 − When we see the symbol ‘b’, replace it as Y and change the state to q3 and move left.
δ(q2, B) = (q3,Y,L)
Step 4 − Move to left until reach the symbol X.
δ(q3, a) = (q3,a,L)
δ(q3, b) = (q3,b,L)
When we reach X move right and change the state as q0, and the next iteration is started.
After replacing every ‘a’ and ‘b’ as X and Y by changing the states to q0 to q4, we get the following −
δ(q0, Y) = (q4,Y,N)
N represents No movement.
q4 is the final state and q0 is the initial state of the Turing Machine, the intermediate states are q1, q2, q3.
The transition diagram for Turing Machine is as follows −
C - nested switch statements

It is possible to have a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.
The syntax for a nested switch statement is as follows −
switch(ch1) {

   case 'A': 
      printf("This A is part of outer switch" );
		
      switch(ch2) {
         case 'A':
            printf("This A is part of inner switch" );
            break;
         case 'B': /* case code */
      }
	  
      break;
   case 'B': /* case code */
}

#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 100;
   int b = 200;
 
   switch(a) {
   
      case 100: 
         printf("This is part of outer switch\n", a );
      
         switch(b) {
            case 200:
               printf("This is part of inner switch\n", a );
         }
   }
   
   printf("Exact value of a is : %d\n", a );
   printf("Exact value of b is : %d\n", b );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

 Print
 Add Notes
 Bookmark this page
MySQL query to generate row index (rank) in SELECT statement?

To generate a row index, use ROW_NUMBER(). Let us first create a table −
mysql> create table DemoTable
(
   Name varchar(40)
);
Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values('Adam');
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+
| Name   |
+--------+
| Chris  |
| Chris  |
| Chris  |
| Robert |
| Robert |
| Adam   |
| Adam   |
| Adam   |
| Adam   |
+--------+
9 rows in set (0.00 sec)
Following is the query to generate a row index in MySQL SELECT statement. Here, we have set rank for duplicate names −
mysql> select Name,
row_number() over (partition by Name) as `Rank`
from DemoTable;
This will produce the following output −
+--------+------+
| Name   | Rank |
+--------+------+
| Adam   | 1    |
| Adam   | 2    |
| Adam   | 3    |
| Adam   | 4    |
| Chris  | 1    |
| Chris  | 2    |
| Chris  | 3    |
| Robert | 1    |
| Robert | 2    |
+--------+------+
9 rows in set (0.00 sec)
Difference between Servlet and JSP

In brief, it can be defined as Servlet are the java programs that run on a Web server and act as a middle layer between a request coming from HTTP client and databases or applications on the HTTP server.While JSP is simply a text document that contains two types of text: static text which is predefined and dynamic text which is rendered after server response is received.
The following are the important differences between ArrayList and HashSet.
JavaTester.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class JavaTester extends HttpServlet {
   private String message;
   public void init() throws ServletException {
      // Do required initialization
      message = "Hello World";
   }
   public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
      // Set response content type
      response.setContentType("text/html");
      // Actual logic goes here.
      PrintWriter out = response.getWriter();
      out.println(message);
   }
}
Hello World
"delete this" in C++ - GeeksforGeeks

11 Nov, 2021
Ideally delete operator should not be used for this pointer. However, if used, then following points must be considered.1) delete operator works only for objects allocated using operator new (See this post). If the object is created using new, then we can do delete this, otherwise behavior is undefined. 
CPP
class A{  public:    void fun()    {        delete this;    }}; int main(){  /* Following is Valid */  A *ptr = new A;  ptr->fun();  ptr = NULL; // make ptr NULL to make sure that things are not accessed using ptr.    /* And following is Invalid: Undefined Behavior */  A a;  a.fun();   getchar();  return 0;}
2) Once delete this is done, any member of the deleted object should not be accessed after deletion. 
CPP
#include<iostream>using namespace std; class A{  int x;  public:    A() { x = 0;}    void fun() {      delete this;       /* Invalid: Undefined Behavior */      cout<<x; // this is working    }}; int main(){  A* obj = new A;  obj->fun();  return 0;}
0
The best thing is to not do delete this at all.Thanks to Shekhu for providing above details.References: https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this http://en.wikipedia.org/wiki/This_%28computer_science%29This article is contributed by Rahul Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
DeepakTiwari2
hail2m15
cpp-pointer
secure-coding
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
Inheritance in C++
Constructors in C++
bar3d() function in C graphics - GeeksforGeeks

30 Jan, 2018
The header file graphics.h contains bar3d() function which is used to draw a 2-dimensional, rectangular filled in bar . Coordinates of left top and right bottom corner of bar are required to draw the bar.Syntax :
void bar3d(int left, int top, int right, 
    int bottom, int depth, int topflag);

where,
left specifies the X-coordinate of top left corner,
top specifies the Y-coordinate of top left corner, 
right specifies the X-coordinate of right bottom corner, 
bottom specifies the Y-coordinate of right bottom corner, 
depth specifies the depth of bar in pixels, 
topflag determines whether a 3 dimensional top is put on 
the bar or not ( if it is non-zero then it is put otherwise not ).

Example :
Input : left = 150, top = 250,
        right = 190, bottom = 350,
        depth = 20, topflag = 1
             
        left = 220, top = 150,
        right = 260, bottom = 350, 
        depth = 20, topflag = 0
             
        left = 290, top = 200, 
        right = 330, bottom = 350, 
        depth = 20, topflag = 1
Output : 


Below is the implementation of bar3d() function :
// C Implementation for bar3d() function#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // location of sides    int left, top, right, bottom;      // depth of the bar    int depth;      // top flag denotes top line.    int topflag;      // left, top, right, bottom,    // depth, topflag location's    bar3d(left = 150, top = 250,    right = 190, bottom = 350,    depth = 20, topflag = 1);      bar3d(left = 220, top = 150,    right = 260, bottom = 350,    depth = 20, topflag = 0);      bar3d(left = 290, top = 200,    right = 330, bottom = 350,    depth = 20, topflag = 1);      // y axis line    line(100, 50, 100, 350);      // x axis line    line(100, 350, 400, 350);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output:


c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Multithreading in C
Exception Handling in C++
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
Understanding "extern" keyword in C
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
Sorting Vector of Pairs in C++ | Set 1 (Sort by first and second)
Groovy - random()

The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic.
static double random() 

This is a default method and accepts no parameter.
This method returns a double.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      System.out.println( Math.random() ); 
      System.out.println( Math.random() ); 
   } 
}
When we run the above program, we will get the following result −
0.0543333676591804 
0.3223824169137166


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
TypeScript - String toLowerCase()

This method returns the calling string value converted to lowercase.
string.toLowerCase( )

Returns the calling string value converted to lowercase.
var str = "Apples are round, and Apples are Juicy."; 
console.log(str.toLowerCase( ))

On compiling, it will generate the same code in JavaScript.
Its output is as follows −
apples are round, and apples are juicy.


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
C++ Program to Reverse a Number

Reversing a number means storing its digits in reverse order.
For example: If the number is 6529, then 9256 is displayed in the output.
A program to reverse a number is given as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int num = 63972, rev = 0;
   while(num > 0) {
      rev = rev*10 + num%10;
      num = num/10;
   }
   cout<<"Reverse of number is "<<rev;
   return 0;
}
Reverse of number is 27936
In the above program, the number that needs to be reversed is 63972. It is stored in the variable num. The reversed number will be stored in the variable rev. The main logic of the program is in the while loop. The while loop will run till the number is greater than 0.
For each iteration of the while loop, rev is multiplied with 10 and added to num modulus 10. Then this is stored in rev. Also num is divided by 10 in each loop iteration.
This is demonstrated by the following code snippet.
while(num > 0) {
   rev = rev*10 + num%10;
   num = num/10;
}
Eventually, rev stores the reverse number of that in num and the value of num is zero. After that rev is displayed.
This can be seen in the following code snippet −
cout<<"Reverse of number is "<<rev;