code-rag-bench/online-tutorials huggingface dataset:
How to detect device is Android phone or Android tablet?

This example demonstrates how do I detect the device is an Android phone or Android tablet.
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">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="30dp"
      android:text="Detect device is Android phone or Android tablet"
      android:textAlignment="center"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TelephonyManager manager = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
      if (Objects.requireNonNull(manager).getPhoneType() == TelephonyManager.PHONE_TYPE_NONE) {
         Toast.makeText(MainActivity.this, "Detected... You're using a Tablet", Toast.LENGTH_SHORT).show();
      } else {
         Toast.makeText(MainActivity.this, "Detected... You're using a Mobile Phone", Toast.LENGTH_SHORT).show();
      }
   }
}
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 the 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.
IDE | GeeksforGeeks | A computer science portal for geeks

Please enter your email address or userHandle.
12345678910111213141516171819202122232425262728293031323334353637https://c.mi.com/thread-3967156-1-1.html https://forums.ubisoft.com/showthread.php/2371427-44-Free-Cookie-Run-Cookies-Generator-2022iwd?p=15523073#post15523073https://netflix-free-account-generator.tumblr.comhttps://psn-gift-card-code-2022.tumblr.comhttps://bingo-blitz-credit-generator.tumblr.comhttps://steamwalletgiftcardgenerator2022.tumblr.comhttps://vc-generator-nba-2k22.tumblr.comhttps://amazon-gift-card-generator-2022.tumblr.comhttps://psn-gift-card-code-generator.tumblr.comhttps://tiktok-fans-generator-2022.tumblr.comhttps://pes-22-free-coins-generator.tumblr.comhttps://amazon-giftcard-generator.tumblr.comhttps://itunes-code-generator-2022.tumblr.comhttps://forums.ubisoft.com/showthread.php/2371436-efeoif4r09300i9o-fr434effregfg?p=15523082#post15523082http://zacriley.ning.com/photo/albums/ewfeofii9ie0w4f09i4rifpo0re4gft4https://paiza.io/projects/YYVB5HSwv9k9R5PPMqz-VQ?language=phphttps://jsfiddle.net/5rpzs1o9/https://notes.io/ABARhttps://onecompiler.com/java/3xq2b2dhuhttps://paste2.org/E8Dge2zJhttps://pasteio.com/xONewfBwCzSQhttps://ideone.com/ydG5wEhttps://authors.curseforge.com/paste/6fefb8d1https://dev.bukkit.org/paste/4b1359b9https://paste.feed-the-beast.com/view/ab65547fhttp://cpp.sh/2x2wnhttps://brainly.co.id/tugas/47544448https://pasteall.org/Ncsmhttps://ide.geeksforgeeks.org/VYvlOsqxzVhttps://pastebin.com/GTE8fuA6https://paste.centos.org/view/c981ea12https://paste.in/3GwtxUhttps://ctxt.io/2/AABgGfJQEghttps://wow.curseforge.com/pastehttp://paste.jp/1c144e86/https://paste.ofcode.org/ZhrNdFC8ymGieRHZWyy7HAhttps://www.onfeetnation.com/profiles/blogs/iuuwduweoidewfocdefr34rההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
https://ide.geeksforgeeks.org/sztAdrcNtF
prog.c:1:6: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â before â:â token
JavaScript for...in loop

The for...in loop is used to loop through an object's properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.
for (variablename in object) {
   statement or block to execute
}

In each iteration, one property from object is assigned to variablename and this loop continues till all the properties of the object are exhausted.
Try the following example to implement ‘for-in’ loop. It prints the web browser’s Navigator object.
<html>
   <body>      
      <script type = "text/javascript">
         <!--
            var aProperty;
            document.write("Navigator Object Properties<br /> ");        
            for (aProperty in navigator) {
               document.write(aProperty);
               document.write("<br />");
            }
            document.write ("Exiting from the loop!");
         //-->
      </script>      
      <p>Set the variable to different object and then try...</p>
   </body>
</html>
Navigator Object Properties 
serviceWorker 
webkitPersistentStorage 
webkitTemporaryStorage 
geolocation 
doNotTrack 
onLine 
languages 
language 
userAgent 
product 
platform 
appVersion 
appName 
appCodeName 
hardwareConcurrency 
maxTouchPoints 
vendorSub 
vendor 
productSub 
cookieEnabled 
mimeTypes 
plugins 
javaEnabled 
getStorageUpdates 
getGamepads 
webkitGetUserMedia 
vibrate 
getBattery 
sendBeacon 
registerProtocolHandler 
unregisterProtocolHandler 
Exiting from the loop!
Set the variable to different object and then try...


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Set variable point size in Matplotlib

To set the variable point size in matplotlib, we can take the following steps−
Initialize the coordinates of the point.
Make a variable to store the point size.
Plot the point using scatter method, with marker=o, color=red, s=point_size.To display the figure, use show() method.
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xy = (3, 4)
point_size = 100
plt.scatter(x=xy[0], y=xy[1], marker='o', c='red', s=point_size)
plt.show()
How to find the mean of multiple columns based on a character column in R?

If we have a character column that means we are more likely to have duplicated values in that column hence finding the mean of numerical columns based on the values in character column cannot be done directly. For this purpose, we can use aggregate function as shown in the below examples.
Consider the below data frame −
 Live Demo
set.seed(214)
x1<−sample(c("A","B","C"),20,replace=TRUE)
x2<−rnorm(20,2,0.25)
x3<−rnorm(20,524,32.14)
x4<−rnorm(20,0.4,0.007)
df1<−data.frame(x1,x2,x3,x4)
df1
  x1    x2      x3        x4
1 C 1.798039 483.1139 0.4105840
2 A 2.044579 574.3082 0.3970706
3 B 1.563161 517.0169 0.3983528
4 A 1.722058 546.6778 0.4049876
5 C 2.279675 527.9437 0.3959229
6 C 1.721763 549.1909 0.4096398
7 A 1.903552 486.4005 0.4091737
8 C 2.268382 502.0860 0.3998178
9 B 1.637324 540.1949 0.3970408
10 B 2.204911 433.7537 0.4003291
11 A 2.124006 521.2464 0.3935380
12 C 1.830028 525.4325 0.3937420
13 C 1.353421 553.7063 0.3974116
14 B 2.067984 547.9531 0.3958582
15 C 1.849775 537.0034 0.3986610
16 C 1.763957 531.4417 0.4015034
17 A 1.932413 545.7784 0.4215530
18 B 2.147503 491.7046 0.3918060
19 C 2.222639 563.4852 0.3902110
20 A 1.979280 483.2847 0.3820964
Finding the column means based on values in x1 −
aggregate(.~x1,data=df1,mean)
  x1    x2      x3       x4
1 A 1.950981 526.2827 0.4014032
2 B 1.924176 506.1246 0.3966774
3 C 1.898631 530.3782 0.3997215
 Live Demo
y1<−sample(c("Male","Female"),20,replace=TRUE)
y2<−rpois(20,2)
y3<−rpois(20,5)
y4<−rpois(20,3)
y5<−rpois(20,2)
y6<−rpois(20,1)
y7<−rpois(20,4)
df2<−data.frame(y1,y2,y3,y4,y5,y6,y7)
df2
   y1     y2 y3 y4 y5 y6 y7
1  Male   1  6  1  1  1  4
2  Male   4  2  1  4  0 5
3  Male   2  6  5  3  1 2
4  Male   4  4  0  3  2  0
5  Male   1  2  6  2  2 2
6  Female 5  4  2  4  0 5
7  Male   2  4  3  1  2 3
8  Male   3  8  1  2  1 5
9  Male   0  3  2  1  2 5
10 Female 3  5  1  2  1 3
11 Female 2  5  3  2  1 2
12 Female 3  8  1  0  1 6
13 Female 1  2  5  2  1 3
14 Male   2  7  1  1  0 3
15 Male   3  5  2  4  2 4
16 Female 5  6  2  4  1 0
17 Female 2  3  1  0  1 3
18 Male   2  6  3  0  1 6
19 Female 2  6  5  1  0 0
20 Female 2  6  4  5  0 3
Finding the column means based on values in y1 −
aggregate(.~y1,data=df2,mean)
    y1      y2      y3       y4       y5        y6 y7
1 Female 2.777778 5.000000 2.666667 2.222222 0.6666667 2.777778
2 Male 2.181818 4.818182 2.272727 2.000000 1.2727273 3.545455
How can I create a stored procedure to delete values from a MySQL table?

We can create a stored procedure with IN operator to delete values from a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 100  | Aarav   | Delhi      | Computers  |
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
+------+---------+------------+------------+
4 rows in set (0.00 sec)
Now, by creating the procedure named ‘delete_studentinfo’ as follow, we can delete the values from ‘student_info’ table −
mysql> DELIMITER // ;
mysql> Create Procedure Delete_studentinfo ( IN p_id INT)
    -> BEGIN
    -> DELETE FROM student_info
    -> WHERE ID=p_id;
    -> END //
Query OK, 0 rows affected (0.11 sec)

mysql> DELIMITER ; //
Now, invoke the procedure with the values we want to delete from the table as follows −
mysql> CALL Delete_studentinfo(100);
Query OK, 1 row affected (1.09 sec)

mysql> Select * from student_info;
+------+---------+------------+------------+
| id   | Name    | Address    | Subject    |
+------+---------+------------+------------+
| 101  | YashPal | Amritsar   | History    |
| 105  | Gaurav  | Jaipur     | Literature |
| 110  | Rahul   | Chandigarh | History    |
| 125  | Raman   | Bangalore  | Computers  |
+------+---------+------------+------------+
4 rows in set (0.01 sec)
The above result set shows that the record having id = 100 deleted from the table.
C++ String Library - find_first_not_of

It searches the string for the first character that does not match any of the characters specified in its arguments.
Following is the declaration for std::string::find_first_not_of.
size_t find_first_not_of (const string& str, size_t pos = 0) const;
size_t find_first_not_of (const string& str, size_t pos = 0) const noexcept;
size_t find_first_not_of (const string& str, size_t pos = 0) const noexcept;
str − It is a string object.
str − It is a string object.
len − It is used to copy the characters.
len − It is used to copy the characters.
pos − Position of the first character to be copied.
pos − Position of the first character to be copied.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::find_first_not_of.
#include <iostream>
#include <string>
#include <cstddef>

int main () {
   std::string str ("It looks for non-alphabetic characters...");

   std::size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");

   if (found!=std::string::npos) {
      std::cout << "The first non-alphabetic character is " << str[found];
      std::cout << " at position " << found << '\n';
   }

   return 0;
}
The sample output should be like this −
The first non-alphabetic character is I at position 0

 Print
 Add Notes
 Bookmark this page
How to Multiply Two Matrices using Python?

Multiplication of two matrices is possible only when number of columns in first matrix equals number of rows in second matrix.
Multiplication can be done using nested loops. Following program has two matrices x and y each with 3 rows and 3 columns. The resultant z matrix will also have 3X3 structure. Element of each row of first matrix is multiplied by corresponding element in column of second matrix.
X = [[1,2,3],  
       [4,5,6],  
       [7,8,9]]  
 
Y = [[10,11,12],  
      [13,14,15],  
      [16,17,18]]  
 
result = [[0,0,0],  
               [0,0,0],  
              [0,0,0]]  
 
# iterate through rows of X  
for i in range(len(X)):  
   for j in range(len(Y[0])):  
       for k in range(len(Y)):  
           result[i][j] += X[i][k] * Y[k][j]  
for r in result:  
   print(r)  
The result:
[84, 90, 96]
[201, 216, 231]
[318, 342, 366]
Select last day of current year in MySQL?

In order to get last day of current year, you can use LAST_DAY() from MySQL. The syntax is as follows−
SELECT LAST_DAY(DATE_ADD(CURDATE(), INTERVAL 12-MONTH(CURDATE()) MONTH));
Let us implement the above syntax to know the last day of current year−
mysql> SELECT LAST_DAY(DATE_ADD(CURDATE(), INTERVAL 12-MONTH(CURDATE()) MONTH));
This will produce the following output −
+-------------------------------------------------------------------+
| LAST_DAY(DATE_ADD(CURDATE(), INTERVAL 12-MONTH(CURDATE()) MONTH)) |
+-------------------------------------------------------------------+
| 2019-12-31                                                        |
+-------------------------------------------------------------------+
1 row in set (0.00 sec)
Python Program for 0-1 Knapsack Problem

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given weights and values of n items, we need to put these items in a bag of capacity W up to the maximum capacity w. We need to carry a maximum number of items and return its value.
Now let’s observe the solution in the implementation below −
# Brute-force approach
 Live Demo
#Returns the maximum value that can be stored by the bag
def knapSack(W, wt, val, n):
   # initial conditions
   if n == 0 or W == 0 :
      return 0
   # If weight is higher than capacity then it is not included
   if (wt[n-1] > W):
      return knapSack(W, wt, val, n-1)
   # return either nth item being included or not
   else:
      return max(val[n-1] + knapSack(W-wt[n-1], wt, val, n-1),
         knapSack(W, wt, val, n-1))
# To test above function
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64
n = len(val)
print (knapSack(W, wt, val, n))
350
#dynamic approach
 Live Demo
# a dynamic approach
# Returns the maximum value that can be stored by the bag
def knapSack(W, wt, val, n):
   K = [[0 for x in range(W + 1)] for x in range(n + 1)]
   #Table in bottom up manner
   for i in range(n + 1):
      for w in range(W + 1):
         if i == 0 or w == 0:
            K[i][w] = 0
         elif wt[i-1] <= w:
            K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
         else:
            K[i][w] = K[i-1][w]
   return K[n][W]
#Main
val = [50,100,150,200]
wt = [8,16,32,40]
W = 64
n = len(val)
print(knapSack(W, wt, val, n))
350
All the variables are declared in the local scope and their references are seen in the figure above.
In this article, we have learned about how we can make a Python Program for 0-1 Knapsack Problem
How to find the length of an array in JavaScript?

To find the length of an array, use the JavaScript length property. JavaScript array length property returns an unsigned, 32-bit integer that specifies the number of elements in an array.
You can try to run the following code to find the length of an array −
Live Demo
<html>
   <head>
      <title>JavaScript Array length Property</title>
   </head>
   <body>
      <script>
         var arr = new Array( 50, 60, 70, 80 );
         document.write("arr.length is : " + arr.length);
      </script>
   </body>
</html>
arr.length is : 4
C program to generate an electricity bill

Based on the units consumed by the user, the electricity bill is generated. If number of units consumed are more then, the rate of a unit charge will also increase.
The logic applied if minimum units are consumed by the user is as follows −
if (units < 50){
   amt = units * 3.50;
   unitcharg = 25;
}
The logic applied if units are in between 50 to 100 is given below −
else if (units <= 100){
   amt = 130 + ((units - 50 ) * 4.25);
   unitcharg = 35;
}
The logic applied if units are in between 100 to 200 is as stated below −
else if (units <= 200){
   amt = 130 + 162.50 + ((units - 100 ) * 5.26);
   unitcharg = 45;
}
The logic applied if number of units are more than 200 is mentioned below −
amt = 130 + 162.50 + 526 + ((units - 200 ) * 7.75);
unitcharg = 55;
Therefore, the final amount will be generated with the logic as given below −
total= amt+ unitcharg;
Following is the C Program to generate an electricity bill −
 Live Demo
#include <stdio.h>
int main(){
   int units;
   float amt, unitcharg, total;
   printf(" Enter no of units consumed : ");
   scanf("%d", &units);
   if (units < 50){
      amt = units * 3.50;
      unitcharg = 25;
   }else if (units <= 100){
      amt = 130 + ((units - 50 ) * 4.25);
      unitcharg = 35;
   }else if (units <= 200){
      amt = 130 + 162.50 + ((units - 100 ) * 5.26);
      unitcharg = 45;
   }else{
      amt = 130 + 162.50 + 526 + ((units - 200 ) * 7.75);
      unitcharg = 55;
   }
   total= amt+ unitcharg;
   printf("electricity bill = %.2f", total);
   return 0;
}
When the above program is executed, it produces the following result −
Enter no of units consumed: 280
electricity bill = 1493.50
Perl | substr() function

25 Jun, 2019
substr() in Perl returns a substring out of the string passed to the function starting from a given index up to the length specified. This function by default returns the remaining part of the string starting from the given index if the length is not specified. A replacement string can also be passed to the substr() function if you want to replace that part of the string with some other substring.This index and length value might be negative as well which changes the direction of index count in the string.For example, if a negative index is passed then substring will be returned from the right end of the string and if we pass the negative length then the function will leave that much of the characters from the rear end of the string.
Syntax: substr(string, index, length, replacement)Parameters:
string: string from which substring is to be extracted
index: starting index of the substring
length: length of the substring
replacement: replacement substring(if any)
Returns: the substring of the required length
Note: The parameters ‘length’ and ‘replacement’ can be omitted.
Example 1
#!/usr/bin/perl  # String to be passed$string = "GeeksForGeeks";  # Calling substr() to find string # without passing length$sub_string1 = substr($string, 4);  # Printing the substringprint "Substring 1 : $sub_string1\n";  # Calling substr() to find the # substring of a fixed length$sub_string2 = substr($string, 4, 5);  # Printing the substringprint "Substring 2 : $sub_string2 ";
Output :
Substring 1 : sForGeeks
Substring 2 : sForG 

Example 2
#!/usr/bin/perl  # String to be passed$string = "GeeksForGeeks";  # Calling substr() to find string # by passing negative index$sub_string1 = substr($string, -4);  # Printing the substringprint "Substring 1 : $sub_string1\n";  # Calling substr() to find the # substring by passing negative length$sub_string2 = substr($string, 4, -2);  # Printing the substringprint "Substring 2 : $sub_string2 ";
Output :
Substring 1 : eeks
Substring 2 : sForGee 

Perl-function
Perl-String-Functions
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
re.MatchObject.span() Method in Python – regex

02 Sep, 2020
re.MatchObject.span() method returns a tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1).
Syntax: re.MatchObject.span()
Parameters: group (optional) By default this is 0.
Return: A tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1).
AttributeError: If a matching pattern is not found then it raises AttributeError.
Consider the below example:
Example 1:
Python3
# import libraryimport re  """We create a re.MatchObject and store it in  match_object variable, '()' parenthesis are used to define a specific group"""match_object = re.match(r'(\d+)',                        '128935')  """ d in above pattern stands for numerical character+ is used to match a consecutive set of characters satisfying a given condition so d+ will match aconsecutive set of numerical characters"""  # generating the tuple with the # starting and ending indexprint(match_object.span())
Output:
(0, 6)    

It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘128935‘) the ‘d‘ indicates that we are searching for a numerical character and the ‘+‘ indicates that we are searching for continuous numerical characters in the given string. Note the use of ‘()‘ the parenthesis is used to define different subgroups.
Example 2: If a match object is not found then it raises AttributeError.
Python3
# import libraryimport re  """We create a re.MatchObject and store it in match_object variable,'()' parenthesis are used to define a specific group"""     match_object = re.match(r'(\d+)',                        'geeks')  """ d in above pattern stands for numerical character+ is used to match a consecutive set of characters  satisfying a given condition so d+ will match aconsecutive set of numerical characters"""  # generating the tuple with the# starting and ending indexprint(match_object.span())
Output:
Traceback (most recent call last):
  File "/home/18a058de83529572f8d50dc9f8bbd34b.py", line 17, in 
    print(match_object.span())
AttributeError: 'NoneType' object has no attribute 'span'

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

Reading the XML file in PowerShell is easy. We have the below XML file for our example,
<Animals>
     <Animal Name="Elephant" Type="Wild">
            <Residence>Forest</Residence>
            <Color>Brown</Color>
      </Animal>

     <Animal Name="Dog" Type="Pet">
            <Residence>Street</Residence>
            <color>Multi</color>
      </Animal>

     <Animal Name="Tiger" Type="Wild">
            <Residence>Forest</Residence>
            <color>Yellow</color>
    </Animal>
</Animals>
Suppose this file is saved as Animals.xml to our current path and to read this XML file we will first get the content of the file using Get-Content command and then we will perform type conversion into XML. For example,
[XML]$xmlfile = Get-Content .\Animals.xml

When you check the $xmlfile output,
PS E:\scripts\Powershell> $xmlfile

Animals
-------
Animals
Animals tag is called element here and to get the attributes from the element, we need to use that element, for example,
$xmlfile.Animals

PS E:\scripts\Powershell> $xmlfile.Animals

Animal
------
{Elephant, Dog, Tiger}


Similarly, you can use Animal elements to expand further attributes, and so on. For example,
$xmlfile.Animals.Animal

PS E:\scripts\Powershell> $xmlfile.Animals.Animal

Name     Type Residence Color
----     ---- --------- -----
Elephant Wild Forest    Brown
Dog      Pet  Street    Multi
Tiger    Wild Forest    Yellow
To get a specific attribute like Name, Type, etc.
$xmlfile.Animals.Animal.name

PS E:\scripts\Powershell> $xmlfile.Animals.Animal.name
Elephant
Dog
Tiger
To get the Type of the animal.
$xmlfile.Animals.Animal.Type

PS E:\scripts\Powershell> $xmlfile.Animals.Animal.Type
Wild
Pet
Wild
If you want two or more attributes together in the table format then you can use PowerShell traditional Select or Format-Table command. For example,
$xmlfile.Animals.Animal | Select Name, Type

PS E:\scripts\Powershell> $xmlfile.Animals.Animal | Select Name, Type

Name     Type
----     ----
Elephant Wild
Dog      Pet
Tiger    Wild
Transpose a matrix in Java

A transpose of a matrix is the matrix flipped over its diagonal i.e. the row and column indices of the matrix are switched. An example of this is given as follows −
Matrix = 
1 2 3
4 5 6
7 8 9
Transpose = 
1 4 7
2 5 8
3 6 9
A program that demonstrates this is given as follows.
 Live Demo
public class Example {
   public static void main(String args[]) {
      int i, j;
      int row = 3;
      int col = 2;
      int arr[][] = {{2, 5}, {1, 8}, {6, 9} };
      System.out.println("The original matrix is: ");
      for(i = 0; i < row; i++) {
         for(j = 0; j < col; j++) {
            System.out.print(arr[i][j] + " ");
         }
         System.out.print("\n");
      }
      System.out.println("The matrix transpose is: ");
      for(i = 0; i < col; i++) {
         for(j = 0; j < row; j++) {
            System.out.print(arr[j][i] + " ");
         }
         System.out.print("\n");
      }
   }
}
The original matrix is:
2 5
1 8
6 9
The matrix transpose is:
2 1 6
5 8 9
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks

28 Jun, 2021
Consider a software project with the following information domain characteristic for calculation of function point metric.
  Number of external inputs (I) = 30
  Number of external output (O) = 60
  Number of external inquiries (E) = 23
  Number of files (F) = 08
  Number of external interfaces (N) = 02 
It is given that the complexity weighting factors for I, O, E, F and N are 4, 5, 4, 10 and 7, respectively. It is also given that, out of fourteen value adjustment factors that influence the development effort, four factors are not applicable, each of he other four factors have value 3, and each of the remaining factors have value 4. The computed value of function point metric is ____________(A) 612.06(B) 212.05(C) 305.09(D) 806.9Answer: (A)Explanation: Function point metrics provide a standardized method for measuring the various functions of a software application
The value of function point metric = UPF * VAF

Here,
   UPF: Unadjusted Function Point (UFP) count 
   VAF: Value Adjustment Factor


UPF  = 4*30 + 60*5 + 23*4 + 8*10 + 7*2 = 606

VAF = (TDI * 0.01) + 0.65

Here TDI is Total Degree of Influence
TDI = 3*4 + 0*4 + 4*6 = 36

VAF = (TDI * 0.01) + 0.65
    = 36*0.01 + 0.65
    = 0.36 + 0.65
    = 1.01

FP = UPF * VAF
   = 1.01 * 606 
   = 612.06 
Refer https://cs.uwaterloo.ca/~apidduck/CS846/Seminars/abbas.pdf
Quiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
Matplotlib - 3D Wireframe plot

Wireframe plot takes a grid of values and projects it onto the specified three-dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize. The plot_wireframe() function is used for the purpose −
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
def f(x, y):
   return np.sin(np.sqrt(x ** 2 + y ** 2))
	
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe')
plt.show()
The above line of code will generate the following output −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How can we convert subqueries to INNER JOIN?

To make it understand we are using the data from the following tables −
mysql> Select * from customers;
+-------------+----------+
| Customer_Id | Name     |
+-------------+----------+
|           1 | Rahul    |
|           2 | Yashpal  |
|           3 | Gaurav   |
|           4 | Virender |
+-------------+----------+
4 rows in set (0.00 sec)

mysql> Select * from reserve;
+------+------------+
| ID   | Day        |
+------+------------+
|    1 | 2017-12-30 |
|    2 | 2017-12-28 |
|    2 | 2017-12-25 |
|    1 | 2017-12-24 |
|    3 | 2017-12-26 |
+------+------------+
5 rows in set (0.00 sec)
Now, the following is a subquery which will find the name of all the customers who have reserved a car.
mysql> Select Name from customers WHERE customer_id IN (Select id from reserve);
+----------+
| Name     |
+----------+
| Rahul    |
| Yashpal  |
| Gaurav   |
+----------+
3 rows in set (0.00 sec)
Now, with the help of followings steps, we can convert the above subquery into inner join −
Move the ‘Reserve’ table named in the subquery to the FROM clause.
Move the ‘Reserve’ table named in the subquery to the FROM clause.
The WHERE clause compares the customer_id column to the ids returned from the subquery. 
The WHERE clause compares the customer_id column to the ids returned from the subquery. 
Hence convert the expression to an explicit direct comparison between id columns of two tables.
mysql> SELECT Name from customers, reserve WHERE customer_id = id;
+----------+
| Name     |
+----------+
| Rahul    |
| Yashpal  |
| Yashpal  |
| Rahul    |
| Gaurav   |
+----------+
5 rows in set (0.00 sec)
As we can see that the above result is not exactly the same as the result of subquery so use DISTINCT keyword to get the same result as follows:
mysql> SELECT DISTINCT name from customers,reserve WHERE customer_id = id;
+----------+
| Name     |
+----------+
| Rahul    |
| Yashpal  |
| Gaurav   |
+----------+
3 rows in set (0.03 sec)
Python - Log Gamma Distribution in Statistics - GeeksforGeeks

10 Jan, 2020
scipy.stats.loggamma() is a log gamma continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution.
Parameters :
q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : log gamma continuous random variable
Code #1 : Creating log gamma continuous random variable
# importing library  from scipy.stats import loggamma      numargs = loggamma.numargs a, b = 4.32, 3.18rv = loggamma(a, b)     print ("RV : \n", rv)  
Output :
RV : 
 scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D6AE0588

Code #2 : log gamma continuous variates and probability distribution
import numpy as np quantile = np.arange (0.01, 1, 0.1)   # Random Variates R = loggamma.rvs(a, b) print ("Random Variates : \n", R)   # PDF R = loggamma.pdf(a, b, quantile) print ("\nProbability Distribution : \n", R) 
Output :
Random Variates : 
 3.941580350134656

Probability Distribution : 
 [1.76757240e-27 1.53388070e-24 6.78322725e-22 1.62994246e-19
 2.25532281e-17 1.89389591e-15 1.01217167e-13 3.59400367e-12
 8.81510518e-11 1.54700389e-09]


Code #3 : Graphical Representation.
import numpy as np import matplotlib.pyplot as plt      distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution)      plot = plt.plot(distribution, rv.pdf(distribution)) 
Output :
Distribution : 
 [0.         0.06122449 0.12244898 0.18367347 0.24489796 0.30612245
 0.36734694 0.42857143 0.48979592 0.55102041 0.6122449  0.67346939
 0.73469388 0.79591837 0.85714286 0.91836735 0.97959184 1.04081633
 1.10204082 1.16326531 1.2244898  1.28571429 1.34693878 1.40816327
 1.46938776 1.53061224 1.59183673 1.65306122 1.71428571 1.7755102
 1.83673469 1.89795918 1.95918367 2.02040816 2.08163265 2.14285714
 2.20408163 2.26530612 2.32653061 2.3877551  2.44897959 2.51020408
 2.57142857 2.63265306 2.69387755 2.75510204 2.81632653 2.87755102
 2.93877551 3.        ]
 
Code #4 : Varying Positional Arguments
import matplotlib.pyplot as plt import numpy as np      x = np.linspace(0, 5, 100)      # Varying positional arguments y1 = loggamma .pdf(x, 1, 3) y2 = loggamma .pdf(x, 1, 4) plt.plot(x, y1, "*", x, y2, "r--") 
Output :
Python scipy-stats-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
What is the size of void pointer in C/C++?

The size of void pointer varies system to system. If the system is 16-bit, size of void pointer is 2 bytes. If the system is 32-bit, size of void pointer is 4 bytes. If the system is 64-bit, size of void pointer is 8 bytes.
Here is an example to find the size of void pointer in C language,
 Live Demo
#include <stdio.h>
int main() {
   void *ptr;
   printf("The size of pointer value : %d", sizeof(ptr));
   return 0;
}
The size of pointer value : 8
In the above example, a void type pointer variable is created and by using sizeof() function, the size of void pointer is found out.
void *ptr;
printf("The size of pointer value : %d", sizeof(ptr));
Save the plots into a PDF in matplotlib

Using plt.savefig("myImagePDF.pdf", format="pdf", bbox_inches="tight") method, we can save a figure in PDF format.
Create a dictionary with Column 1 and Column 2 as the keys and Values are like i and i*i, where i is from 0 to 10, respectively.
Create a dictionary with Column 1 and Column 2 as the keys and Values are like i and i*i, where i is from 0 to 10, respectively.
Create a data frame using pd.DataFrame(d), d created in step 1.
Create a data frame using pd.DataFrame(d), d created in step 1.
Plot the data frame with ‘o’ and ‘rx’ style.
Plot the data frame with ‘o’ and ‘rx’ style.
To save the file in PDF format, use savefig() method where the image name is myImagePDF.pdf, format = ”pdf”.
To save the file in PDF format, use savefig() method where the image name is myImagePDF.pdf, format = ”pdf”.
To show the image, use the plt.show() method.
To show the image, use the plt.show() method.
import pandas as pd
from matplotlib import pyplot as plt

d = {'Column 1': [i for i in range(10)], 'Column 2': [i * i for i in range(10)]}

df = pd.DataFrame(d)

df.plot(style=['o', 'rx'])
plt.savefig("myImagePDF.pdf", format="pdf", bbox_inches="tight")
plt.show()
numpy.ndarray.size() method | Python - GeeksforGeeks

26 Mar, 2020
numpy.ndarray.size() function return the number of elements in the array. it equal to np.prod(a.shape), i.e., the product of the array’s dimensions.
Syntax : numpy.ndarray.size(arr)
Parameters :arr : [array_like] Input array.
Return : [int] The number of elements in the array.
Code #1 :
# Python program explaining# numpy.ndarray.size() function  # importing numpy as geek import numpy as geek  arr = geek.zeros((3, 4, 2), dtype = geek.complex128)  gfg = arr.size  print (gfg)
Output :
24

 Code #2 :
# Python program explaining# numpy.ndarray.size() function  # importing numpy as geek import numpy as geek  arr = geek.zeros((3, 4, 2), dtype = geek.complex128)  gfg = geek.prod(arr.shape)  print (gfg)
Output :
24

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
How to create a rectangle with rounded corners in HTML5 SVG?

SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG.
To draw a rectangle in HTML SVG, use the SVG <rect> element. For rounded corners, set the rx and ry attribute, which rounds the corners of the rectangle.
You can try to run the following code to learn how to draw a rectangle with rounded corners in HTML5 SVG.
<!DOCTYPE html>
<html>
   <head>
      <style>
         #svgelem {
            position: relative;
            left: 10%;
            -webkit-transform: translateX(-20%);
            -ms-transform: translateX(-20%);
            transform: translateX(-20%);
         }
      </style>
      <title>SVG</title>
   </head>

   <body>
      <h2>HTML5 SVG Rectangle</h2>
      <svg id="svgelem" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
         <rect x="50" y="20" rx="30" ry="30" width="150" height="150"
            style="fill:blue;/">
      </svg>
   </body>
</html>
Auto adjust font size in Seaborn heatmap using Matplotlib

To adjust font size in Seaborn, we can take followig steps−
Create a dictionary with some mathematical expressions
Create a dataframe using Pandas data frame.
Create a heatmap using heatmap() method.
To adjust the font size in Seaborn heatmap, change the fontsize value.
To display the figure, use show() method.
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
import pandas as pd
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
d = {
   'y=1/x': [1 / i for i in range(1, 10)],
   'y=x': [i for i in range(1, 10)],
   'y=x^2': [i * i for i in range(1, 10)],
   'y=x^3': [i * i * i for i in range(1, 10)]
}
df = pd.DataFrame(d)
ax = sns.heatmap(df, vmax=1)
plt.xlabel('Mathematical Expression', fontsize=16)
plt.show()
Powershell - Alias

PowerShell alias is another name for the cmdlet or for any command element.
Use New-Alias cmdlet to create a alias. In the below example, we've created an alias help for Get-Help cmdlet.
New-Alias -Name help -Value Get-Help  
Now invoke the alias.
help Get-WmiObject -Detailed  
You will see the following output.
NAME
   Get-WmiObject
    
SYNOPSIS
   Gets instances of Windows Management Instrumentation (WMI) classes or information about the available classes.    
    
SYNTAX
   Get-WmiObject [
...

Use get-alias cmdlet to get all the alias present in current session of powershell.
Get-Alias
You will see the following output.
CommandType     Name                     Definition
-----------     ----                     ----------  
Alias           %                        ForEach-Object
Alias           ?                        Where-Object
Alias           ac                       Add-Content
Alias           asnp                     Add-PSSnapIn 
...


    15 Lectures 
     3.5 hours 

 Fabrice Chrzanowski

    35 Lectures 
     2.5 hours 

 Vijay Saini

    145 Lectures 
     12.5 hours 

 Fettah Ben
 Print
 Add Notes
 Bookmark this page
Rexx - left String

This method returns a certain number of characters from the left of the string.
left(str,count) 

str − The source string.
str − The source string.
count − The number of characters to return from the left of the string.
count − The number of characters to return from the left of the string.
This method returns a certain number of characters from the left of the string.
/* Main program */ 
a = "Hello World" 
say left(a,5) 
When we run the above program, we will get the following result.
Hello 

 Print
 Add Notes
 Bookmark this page
How to Update multiple documents in a MongoDB collection using Java?

Using the updateMany() method you can update all the documents of a collection.
db.COLLECTION_NAME.update(<filter>, <update>)
In Java the com.mongodb.client.MongoCollection interface provides you a method with the same name. Using this method you can update multiple documents in a
collection at once, to this method you need to pass the filter and values for the update.
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoClient;
public class UpdatingMultipleDocuments {
   public static void main( String args[] ) {
      // Creating a Mongo client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Connecting to the database
      MongoDatabase database = mongo.getDatabase("myDatabase");
      //Creating a collection object
      MongoCollection<Document>collection =
      database.getCollection("myCollection");
      //Preparing documents
      Document document1 = new Document("name", "Ram").append("age", 26).append("city", "Hyderabad");
      Document document2 = new Document("name", "Robert").append("age", 27).append("city", "Delhi");
      Document document3 = new Document("name", "Rahim").append("age", 30).append("city", "Delhi");
      //Inserting the created documents
      List<Document> list = new ArrayList<Document>();
      list.add(document1);
      list.add(document2);
      list.add(document3);
      collection.insertMany(list);
      System.out.println("List of the documents: ");
      FindIterable<Document> iterDoc = collection.find();
      Iterator it = iterDoc.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }
      //Updating multiple documents
      Bson filter = new Document("city", "Delhi");
      Bson newValue = new Document("city", "Vijayawada");
      Bson updateOperationDocument = new Document("$set", newValue);
      collection.updateMany(filter, updateOperationDocument);
      System.out.println("Document update successfully...");
      System.out.println("List of the documents after update");
      iterDoc = collection.find();
      it = iterDoc.iterator();
      while (it.hasNext()) {
         System.out.println(it.next());
      }
   }
}
List of the documents:
Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Delhi}}
Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Delhi}}
Document update successfully...
List of the documents after update
Document{{_id=5e88a61fe7a0124a4fc51b2c, name=Ram, age=26, city=Hyderabad}}
Document{{_id=5e88a61fe7a0124a4fc51b2d, name=Robert, age=27, city=Vijayawada}}
Document{{_id=5e88a61fe7a0124a4fc51b2e, name=Rahim, age=30, city=Vijayawada}}
React Native - ListView

In this chapter, we will show you how to create a list in React Native. We will import List in our Home component and show it on screen.
App.js
import React from 'react'
import List from './List.js'

const App = () => {
   return (
      <List />
   )
}
export default App
To create a list, we will use the map() method. This will iterate over an array of items, and render each one.
List.js
import React, { Component } from 'react'
import { Text, View, TouchableOpacity, StyleSheet } from 'react-native'
   
class List extends Component {
   state = {
      names: [
         {
            id: 0,
            name: 'Ben',
         },
         {
            id: 1,
            name: 'Susan',
         },
         {
            id: 2,
            name: 'Robert',
         },
         {
            id: 3,
            name: 'Mary',
         }
      ]
   }
   alertItemName = (item) => {
      alert(item.name)
   }
   render() {
      return (
         <View>
            {
               this.state.names.map((item, index) => (
                  <TouchableOpacity
                     key = {item.id}
                     style = {styles.container}
                     onPress = {() => this.alertItemName(item)}>
                     <Text style = {styles.text}>
                        {item.name}
                     </Text>
                  </TouchableOpacity>
               ))
            }
         </View>
      )
   }
}
export default List

const styles = StyleSheet.create ({
   container: {
      padding: 10,
      marginTop: 3,
      backgroundColor: '#d9f9b1',
      alignItems: 'center',
   },
   text: {
      color: '#4f603c'
   }
})
When we run the app, we will see the list of names.
You can click on each item in the list to trigger an alert with the name.

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page