code-rag-bench/online-tutorials huggingface dataset:
Where and how to use to static variables in android studio?

This example demonstrates about how and where do I use static variable in android studio.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="MainActivity">
   <TextView
      android:id="@+id/Question"
      android:layout_width="wrap_content"
      android:layout_height="93dp"
      android:padding="8dp"
      android:text="I'm a Static Variable"
      android:layout_marginTop="32sp"
      android:layout_marginLeft="8dp"
      android:textSize="32dp"
      tools:layout_editor_absoluteY="8dp" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
   public static final String TAG = "I'm a Static Variable";
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   protected void onStart() {
      super.onStart();
      Log.i(TAG, "onStart");
   }
   protected void onPause() {
      super.onPause();
      Log.i(TAG, "onPause");
   }
   protected void onStop() {
      super.onStop();
      Log.i(TAG, "onStop");
   }
}
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.
JavaScript String - length Property

This property returns the number of characters in a string.
Use the following syntax to find the length of a string −
string.length

Returns the number of characters in the string.
Try the following example.
<html>
   <head>
      <title>JavaScript String length Property</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = new String( "This is string" );
         document.write("str.length is:" + str.length); 
      </script>      
   </body>
</html>
str.length is:14 


    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
CakePHP - Redirect Routing

Redirect routing is useful when we want to inform client applications that this URL has been moved. The URL can be redirected using the following function.
static Cake\Routing\Router::redirect($route, $url, $options =[])

There are three arguments to the above function −
A string describing the template of the route.
A string describing the template of the route.
A URL to redirect to.
A URL to redirect to.
An array matching the named elements in the route to regular expressions which that element should match.
An array matching the named elements in the route to regular expressions which that element should match.
Make Changes in the config/routes.php file as shown below. Here, we have used controllers that were created previously.
config/routes.php
<?php
   use Cake\Core\Plugin;
   use Cake\Routing\RouteBuilder;
   use Cake\Routing\Router;

   Router::defaultRouteClass('DashedRoute');
   Router::scope('/', function (RouteBuilder $routes) {
      $routes->connect('/generate2', ['controller' => 'Tests', 'action' => 'index']);
      $routes->redirect('/generate1','http://tutorialspoint.com/');
      $routes->connect('/generate_url',['controller'=>'Generates','action'=>'index']);
      $routes->fallbacks('DashedRoute');
   });
   Plugin::routes();
Execute the above example by visiting the following URLs.
URL 1 — http://localhost:85/CakePHP/generate_url
URL 1 — http://localhost:85/CakePHP/generate_url
URL 2 — http://localhost:85/CakePHP/generate1
URL 2 — http://localhost:85/CakePHP/generate1
URL 3 — http://localhost:85/CakePHP/generate2
URL 3 — http://localhost:85/CakePHP/generate2
You will be redirected to http://tutorialspoint.com
 Print
 Add Notes
 Bookmark this page
clear() method in PyQt5 - GeeksforGeeks

26 Mar, 2020
While using PyQt5, there occur a need of removing or clearing labels in order to do so clear() method is used. This method belongs to the QLabel class, and can be used on only label widgets.
Syntax : label.clear()Argument : It takes no argument.Action Performed : It clears(remove) the label from main window.
Below is the implementation of this method.
Code :
# importing the required librariesfrom PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Move")          # setting  the geometry of window        self.setGeometry(0, 0, 500, 300)          # creating a label widget        self.label1 = QLabel('Label 1', self)          # moving the widget        # move(left, top)        self.label1.move(100, 100)          # creating a label widget        self.label2 = QLabel('Label 2 ', self)          # moving the widget        # move(left, top)        self.label2.move(100, 120)          # clearing label 2        self.label2.clear()          # creating a label widget        self.label3 = QLabel('Label 3', self)          # moving the widget        # move(left, top)        self.label3.move(100, 140)              # show all the widgets        self.show()  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :As on the above image we can see Label2 will not be seen because of clear() method.
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Hive - Built-in Functions

This chapter explains the built-in functions available in Hive. The functions look quite similar to SQL functions, except for their usage.
Hive supports the following built-in functions:
The following queries demonstrate some built-in functions:
hive> SELECT round(2.6) from temp;
On successful execution of query, you get to see the following response:
3.0

hive> SELECT floor(2.6) from temp;
On successful execution of the query, you get to see the following response:
2.0

hive> SELECT ceil(2.6) from temp;
On successful execution of the query, you get to see the following response:
3.0

Hive supports the following built-in aggregate functions. The usage of these functions is as same as the SQL aggregate functions.

    50 Lectures 
     4 hours 

 Navdeep Kaur

    67 Lectures 
     4 hours 

 Bigdata Engineer

    109 Lectures 
     2 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
random.choices() method in Python - GeeksforGeeks

27 Jan, 2022
The choices() method returns multiple random elements from the list with replacement. You can weigh the possibility of each result with the weights parameter or the cum_weights parameter. The elements can be a string, a range, a list, a tuple or any other kind of sequence.
Syntax : random.choices(sequence, weights=None, cum_weights=None, k=1)
Parameters :1. sequence is a mandatory parameter that can be a list, tuple, or string.2. weights is an optional parameter which is used to weigh the possibility for each value.3. cum_weights is an optional parameter which is used to weigh the possibility for each value but in this the possibility is accumulated4. k is an optional parameter that is used to define the length of the returned list.
Note: This method is different from random.choice().
Example:
import random  mylist = ["geeks", "for", "python"]  print(random.choices(mylist, weights = [10, 1, 1], k = 5))
Note: Every time output will be different as the system returns random elements.Output:
['geeks', 'geeks', 'geeks', 'for', 'for']

Practical application: Print a random list with 6 items.
import random  mylist = ["apple", "banana", "mango"]  print(random.choices(mylist, weights = [10, 1, 1], k = 6))
Note: The output changes every time as choices() function is used.Output:
['apple', 'banana', 'apple', 'apple', 'apple', 'banana']

harsh khanna
Python-random
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Convert integer to string in Python
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Matplotlib.pyplot.title() in Python
Rexx - Best Programming Practices

Every programmer wants their program to be the best when it comes to quality and efficiency. The following are some of the best programming practices or hints when writing Rexx programs which can help one achieve these goals.
Use the address command before you issue any command to the operating system or command prompt. This will help you get the address space beforehand in memory and cause your program to run more efficiently.
An example of the address command is shown below.
/* Main program */ 
address system dir 
The output of the command is as follows, but it could vary from system to system.
Volume in drive H is Apps 
Volume Serial Number is 8E66-AC3D  
Directory of H:\  
06/30/2016  01:28 AM    <DIR>          Apps 
07/05/2016  03:40 AM               463 main.class 
07/07/2016  01:30 AM                46 main.nrx 
07/07/2016  01:42 AM                38 main.rexx 
3 File(s)            547 bytes 
Dir(s)  313,085,173,760 bytes free

Ensure all commands to the operating system are in upper case and in quotes wherever possible.
An example for the same is shown below.
/* Main program */ 
options arexx_bifs 
say chdir('\REXXML100') 
say directory()
When we run the above program, we will get the following result.
0 
D:\rexxxml100 

Avoid creating big comment blocks as shown in the following program.
/******/ 
/* */ 
/* */ 
/* */ 
/******/ 
/* Main program */ 
address system dir
Use the Parse statement to assign default values. An example for the same is shown below.
parse value 0 1 with 
a, 
b 
Use the "Left(var1,2)" statement wherever possible instead of the “substr(var1,1,2)" statement.
Use the "Right(var1,2)" statement wherever possible instead of the “substr(var1,length(var1),2)" statement.
 Print
 Add Notes
 Bookmark this page
Python unittest - assertIsNotNone() function - GeeksforGeeks

29 Aug, 2020
assertIsNotNone() in Python is a unittest library function that is used in unit testing to check that input value is not None. This function will take two parameters as input and return a boolean value depending upon assert condition. If input value is not equal to None assertIsNotNone() will return true else return false.
Syntax: assertIsNotNone(testValue, message)
Parameters: assertIsNotNone() accept two parameters which are listed below with explanation:
testValue:  test variable as the input value to check equality with None
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest  class TestMethods(unittest.TestCase):    # test function     def test_negative(self):        firstValue = None        # error message in case if test case got failed        message = "Test value is none."        # assertIsNotNone() to check that if input value is not none        self.assertIsNotNone(firstValue, message)  if __name__ == '__main__':    unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "p1.py", line 11, in test_negative
    self.assertIsNotNone(firstValue, message)
AssertionError: unexpectedly None : Test value is none.

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)



Example 2: Positive Test case
Python3
# unit test caseimport unittest  class TestMethods(unittest.TestCase):    # test function     def test_positive(self):        firstValue = "geeks"        # error message in case if test case got failed        message = "Test value is  none."        # assertIsNotNone() to check that if input value is not none        self.assertIsNotNone(firstValue, message)  if __name__ == '__main__':    unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
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 ?
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 | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to create a table in a database using JDBC API?

A. You can create a table in a database using the CREATE TABLE query.
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
To create a table in a database using JDBC API you need to:
Register the driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.
Establish a connection: Connect ot the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.
Create Statement: Create a Statement object using the createStatement() method of the Connection interface.
Execute the Query: Execute the query using the execute() method of the Statement interface.
Following JDBC program establishes connection with MySQL and creates a table named customers in the database named SampleDB:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreateTableExample {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/SampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating the Statement
      Statement stmt = con.createStatement();
      //Query to create a table
      String query = "CREATE TABLE CUSTOMERS("
         + "ID INT NOT NULL, "
         + "NAME VARCHAR (20) NOT NULL, "
         + "AGE INT NOT NULL, "
         + "SALARY DECIMAL (18, 2), "
         + "ADDRESS CHAR (25) , "
         + "PRIMARY KEY (ID))";
      stmt.execute(query);
      System.out.println("Table Created......");
   }
}
Connection established......
Table Created......
The show tables command gives you the list of tables in the current database in MySQL.
If you verify the list of tables in the database named sampledb, you can observe the newly created table in it as:
mysql> show tables;
+--------------------+
| Tables_in_sampledb |
+--------------------+
| articles           |
| customers          |
| dispatches         |
| technologies       |
| tutorial           |
+--------------------+
5 rows in set (0.00 sec)
Select and sum with grouping in MySQL?

To sum, use the aggregate function SUM(). With that, group using MySQL GROUP BY. Let us first create a table −
mysql> create table DemoTable
   -> (
   -> ProductName varchar(20),
   -> ProductQuantity int,
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Product-1',2,50);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Product-2',3,80);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Product-2',4,100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Product-1',4,150);
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output−
+-------------+-----------------+--------------+
| ProductName | ProductQuantity | ProductPrice |
+-------------+-----------------+--------------+
| Product-1   |               2 |           50 |
| Product-2   |               3 |           80 |
| Product-2   |               4 |          100 |
| Product-1   |               4 |          150 |
+-------------+-----------------+--------------+
4 rows in set (0.00 sec)
Following is the query to select with grouping in MySQL −
mysql> select *,sum(ProductQuantity*ProductPrice) as Total from DemoTable
   -> group by ProductName;
This will produce the following output−
+-------------+-----------------+--------------+-------+
| ProductName | ProductQuantity | ProductPrice | Total |
+-------------+-----------------+--------------+-------+
| Product-1   |               2 |           50 |   700 |
| Product-2   |               3 |           80 |   640 |
+-------------+-----------------+--------------+-------+
2 rows in set (0.00 sec)
Can we declare a static variable within a method in java?

A static filed/variable belongs to the class and it will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference). There is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword.
public class Sample{
   static int num = 50;
   public void demo(){
      System.out.println("Value of num in the demo method "+ Sample.num);
   }
   public static void main(String args[]){
      System.out.println("Value of num in the main method "+ Sample.num);
      new Sample().demo();
   }
}
Value of num in the main method 50
Value of num in the demo method 50
The variables with in a method are local variables and their scope lies within the method and they get destroyed after the method execution. i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated.
In the following Java program, we are trying to declare a static variable inside a method
import java.io.IOException;
import java.util.Scanner;
public class Sample {
   static int num;
   public void sampleMethod(Scanner sc){
      static int num = 50;
   }
   public static void main(String args[]) throws IOException {
      static int num = 50;
   }
}
If you try to execute the above program it generates the following error −
Sample.java:6: error: illegal start of expression
   static int num = 50;
  ^
Sample.java:9: error: illegal start of expression
   static int num = 50;
^
2 errors
Check if a large number is divisible by 11 or not in java

A number is divisible by 11 if the difference between the sum of its alternative digits is divisible by 11.
i.e. if (sum of odd digits) – ( sum of even digits) is 0 or divisible by 11 then the given number is divisible by 11.
import java.util.Scanner;

public class DivisibleBy11 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a number :");
      String num = sc.nextLine();
      int digitSumEve = 0;
      int digitSumOdd = 0;
     
     for(int i = 0; i<num.length(); i++) {
         if(i%2 == 0) {
            digitSumEve = digitSumEve + num.charAt(i)-'0';
         } else {
            digitSumOdd = digitSumOdd + num.charAt(i)-'0';
         }
      }
      int res = digitSumOdd-digitSumEve;
      if(res % 11 == 0) {
         System.out.println("Given number is divisible by 11");
      } else {
         System.out.println("Given number is not divisible by 11");
      }
   }
}
Enter a number :
121
Given number is divisible by 11
PHP program to calculate the sum of square of first n natural numbers

To calculate the sum of square of first n natural numbers in PHP, the code is as follows −
 Live Demo
<?php
function sum_of_squares($limit)
{
   $ini_sum = 0;
   for ($i = 1; $i <= $limit; $i++)
      $ini_sum += ($limit * $limit);
   return $ini_sum;
}
$limit = 5;
print_r("The sum of square of first 5 natural numbers is ");
echo sum_of_squares ($limit);
?>
The sum of square of first 5 natural numbers is 125
A function named ‘sum_of_squares’ is defined that takes the limit up to which square of natural number needs to be found. In this function, a sum value is initialized to 0. A ‘for’ loop is run over the elements ranging from 1 to the limit. Every time, to the ‘sum’ variable, square of the iterated value is
added. When the control reaches the end, the value of sum is returned as the output. Outside the function, a limit value is specified and the function is called by passing the limit value to it.
Annotate data points while plotting from Pandas DataFrame

To annotate data points while plotting from pandas data frame, we can take the following steps −
Create df using DataFrame with x, y and index keys.
Create df using DataFrame with x, y and index keys.
Create a figure and a set of subplots using subplots() method.
Create a figure and a set of subplots using subplots() method.
Plot a series of data frame using plot() method, kind='scatter', ax=ax, c='red' and marker='x'.
Plot a series of data frame using plot() method, kind='scatter', ax=ax, c='red' and marker='x'.
To annotate the scatter point with the index value, iterate the data frame.
To annotate the scatter point with the index value, iterate the data frame.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import string
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame({'x': np.random.rand(10), 'y': np.random.rand(10)}, index=list(string.ascii_lowercase[:10]))
fig, ax = plt.subplots()
df.plot('x', 'y', kind='scatter', ax=ax, c='red', marker='x')
for k, v in df.iterrows():
   ax.annotate(k, v)
plt.show()
Get distinct values from a column in MongoDB?

To get distinct values from a column, use distinct() in MongoDB. Let us first create a collection with documents −
> db.demo128.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e30583d68e7f832db1a7f5d")
}
> db.demo128.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e30584068e7f832db1a7f5e")
}
> db.demo128.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e30584368e7f832db1a7f5f")
}
> db.demo128.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e30584668e7f832db1a7f60")
}
> db.demo128.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e30584c68e7f832db1a7f61")
}
Display all documents from a collection with the help of find() method −
> db.demo128.find();
This will produce the following output −
{ "_id" : ObjectId("5e30583d68e7f832db1a7f5d"), "Name" : "Chris" }
{ "_id" : ObjectId("5e30584068e7f832db1a7f5e"), "Name" : "David" }
{ "_id" : ObjectId("5e30584368e7f832db1a7f5f"), "Name" : "David" }
{ "_id" : ObjectId("5e30584668e7f832db1a7f60"), "Name" : "Bob" }
{ "_id" : ObjectId("5e30584c68e7f832db1a7f61"), "Name" : "Chris" }
Following is the query to get distinct values from a column in MongoDB −
> db.demo128.distinct("Name");
This will produce the following output −
[ "Chris", "David", "Bob" ]
Sum of array using pointer arithmetic in C

In this program, we need to find sum of array elements using pointer arithmetic.
Here we use * which denotes the value stored at the memory address and this address will remain stored in the variable. Thus “int *ptr” means, ptr is a variable which contains an address and content of the address is an integer quantity.
*p means it is a pointer variable. Using this and sum() we will find out sum of the elements of array.
#include <stdio.h>
void s(int* a, int len) {
   int i, s_of_arr = 0;
   for (i = 0; i < len; i++)
      s_of_arr = s_of_arr + *(a + i);
   printf( "sum of array is = %d" ,s_of_arr);
}
int main() {
   int arr[] = { 1,2,4,6,7,-5,-3 };
   s(arr, 7);
   return 0;
}
Sum of array = 12
Begin
   Initialize array to hold the variables.
   Call function s to get the sum of the variables.
   Print the sum.
End.
JavaScript | array.values() - GeeksforGeeks

18 Nov, 2021
The array.values() function is an inbuilt function in JavaScript which is used to returns a new array Iterator object that contains the values for each index in the array i.e, it prints all the elements of the array. Syntax:  
arr.values()
Return values: It returns a new array iterator object i.e, elements of the given array. Examples:  
Input:
A = ['a', 'b', 'c', 'd']
Output:
a, b, c, d
Here as we see that input array contain some 
elements and in output same elements get printed.
Let’s see JavaScript program on array.values() function:  
JavaScript
// Input array contain some elementsvar A = [ 'Ram', 'Z', 'k', 'geeksforgeeks' ]; // Here array.values() function is called.var iterator = A.values(); // All the elements of the array the array// is being printed.console.log(iterator.next().value);console.log(iterator.next().value);console.log(iterator.next().value);console.log(iterator.next().value);
Output:
> Ram, z, k, geeksforgeeks
Application: This array.values() function in JavaScript is used to print the elements of the given array. Let’s see JavaScript program on array.values() function:  
JavaScript
// Input array contain some elements.var array = [ 'a', 'gfg', 'c', 'n' ]; // Here array.values() function is called.var iterator = array.values(); // Here all the elements of the array is being printed.for (let elements of iterator) {  console.log(elements);}
Output:
> a, gfg, c, n
Supported Browser:
Google Chrome 66 and above
Microsoft Edge 12 and above
Firefox 60 and above
Opera 53 and above
Safari 9 and above 
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
 
ysachin2314
javascript-array
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Set the value of an input field in JavaScript
Difference Between PUT and PATCH Request
Form validation using HTML and JavaScript
Node.js | fs.writeFileSync() Method
How to Use the JavaScript Fetch API to Get Data?
How to get character array from string in JavaScript?
Create a Responsive Navbar using ReactJS
SQL Query for Finding Maximum Values in Rows

07 Apr, 2021
SQL stands for Structured Query Language and is used to create, maintain and retrieve the data from relational databases. Relational Database Management Systems (RDBMS) like MySQL, MS Access, Oracle, and SQL Server use SQL as their standard database language. Here we are going to see the SQL query for Finding Maximum Values in Rows. Let us understand it by creating a database named “CSEportal”. 
Creating Database :
Syntax : 
CREATE DATABASE <DatabaseName>;
Example :
CREATE DATABASE CSEportal;
Output :
Query returned successfully in 3 secs 817 msec.
Using the Database :
Syntax :
USE <DatabaseName>;
Example :
USE CSEportal;
Using the above commands, we have successfully created our database named “CSEportal”, now we need to create a table(Relation) named “GeeksforGeeks” in this database. 
Creating table :
Syntax :
CREATE TABLE TableName (field1 dataType1 , field2 dataType2...fieldN dataTypeN);
Example : 
CREATE TABLE GeeksforGeeks(
sno int, 
Description VARCHAR(40), 
courses VARCHAR(40));
This will create an empty table, so let us populate our table with some records using the INSERT INTO command to perform the actual operations on the tables. 
Inserting records in the table :
Syntax :
INSERT INTO tablename (field1,field2,...fieldN) VALUES (value1,value2...valueN);
Example :
INSERT INTO GeeksforGeeks(sno,Description,Courses) VALUES(1,'Cse Portal','DBMS');
Similarly, we can fill our table using this INSERT INTO command. To see the created table, we can run the SELECT command which is shown below:
SELECT * from GeeksforGeeks;
Output :
Our Table “GeeksforGeeks”
Now we can move ahead to write our SQL query for finding maximum values in all the rows, This can be done using MAX(field) function in SQL. Let us try to retrieve the maximum value of the field “Description” as shown below:
Select max(Description) as Maximum from GeeksforGeeks;
Here we have used the ‘as ‘ keyword just to change the name of the resulting field as shown in the output below:
Output : 
Here we have got ‘well explained’ as the output since it is the maximum value out of all the rows of the table. Let us try to apply this on the field holding some numeric values to get a more clear idea. 
 Select max(sno) from GeeksforGeeks;
Output : 
Clearly, 4 is the maximum value out of all the rows of the table, hence we have got 4 as our output. Also, here we have not used the ‘as’ keyword, so in the resulting field, we have got ‘max(sno)’ as its name. It is an optional step and can be done in the same manner as shown above. We can also retrieve maximum values of more than one field out of all the rows using a single query as shown below:
Query:
Select max(sno),max(description) from GeeksforGeeks;

Output:
max(sno)    max(description)

4            well explained
So here, we have retrieved the maximum value of two fields (out of all the rows) using a single query only.
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash _.pickBy() Method - GeeksforGeeks

09 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.pickBy() method is used to return a copy of the object that composed of the object properties predicate returns truthy for.
Syntax:
_.pickBy( object, predicate )
Parameters: This method accepts two parameters as mentioned above and described below:
object: This parameter holds the source object.
predicate: This parameter holds the function that is invoked for every property. It is an optional value.
Return Value: This method returns the new object.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source objectvar obj = {     Name: "GeeksforGeeks",     password: 123456,     username: "your_geeks"}  // Using the _.pickBy() method console.log(_.pickBy(obj, _.isLength));
Output:
{'password': 123456}
Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source objectvar obj = { 'x': 1, 'y': '2', 'z': 3 };  // Using the _.pickBy() method console.log(_.pickBy(obj, _.isNumber));
Output:
{'x': 1, 'z': 3}
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
GATE | GATE-CS-2014-(Set-2) | Question 65 - GeeksforGeeks

28 Jun, 2021
An IP machine Q has a path to another IP machine H via three IP routers R1, R2, and R3.
Q—R1—R2—R3—H 
H acts as an HTTP server, and Q connects to H via HTTP and downloads a file. Session layer encryption is used, with DES as the shared key encryption protocol. Consider the following four pieces of information:
[I1] The URL of the file downloaded by Q
[I2] The TCP port numbers at Q and H
[I3] The IP addresses of Q and H
[I4] The link layer addresses of Q and H 
Which of I1, I2, I3, and I4 can an intruder learn through sniffing at R2 alone?
(A) Only I1 and I2(B) Only I1(C) Only I2 and I3(D) Only I3 and I4Answer: (C)Explanation:
An Intruder can’t learn [I1] through sniffing at R2 because 
URLs and Download are functioned at Application layer of OSI Model.

An Intruder can learn [I2] through sniffing at R2 because
Port Numbers are encapsulated in the payload field of IP Datagram.

An Intruder can learn [I3] through sniffing at R2 because IP 
Addresses and Routers are functioned at network layer of OSI Model.

An Intruder can’t learn [I4] through sniffing at R2 because 
it is related to Data Link Layer of OSI Model.

Quiz of this Question
GATE-CS-2014-(Set-2)
GATE-GATE-CS-2014-(Set-2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2000 | Question 43
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | Gate IT 2007 | Question 30
Adding millisecond to date in SAP HANA

Try using ADD_SECONDS function as below:
SELECT ADD_SECONDS (TO_TIMESTAMP('2017-07-15 02:17:15'), 0.1) FROM TEST
This will add seconds as fraction value as requested. Below is syntax and example:
ADD_SECONDS

Syntax
ADD_SECONDS (t, n)
Description
Computes the time t plus n seconds.
Example:
SELECT ADD_SECONDS (TO_TIMESTAMP ('2012-01-01 23:30:45'), 60*30) "add seconds" FROM DUMMY;

add seconds
2012-01-02 00:00:45.0
To know more about ADD_SECONDS function, you can also refer this link:
datetime function in SAP HANA
To know more about SQL functions in SAP HANA system, you can also refer our HANA tutorial:
SAP HANA SQL Functions
Constructor Chaining In Java programming

Constructor chaining refers to calling a constructor from other constructor. It is of two types.
Within same Class − Use this() keyword to refer to current class constructor. Make sure that this() is the first statement of the constructor and there should be at least one constructor without using this() statement.
Within same Class − Use this() keyword to refer to current class constructor. Make sure that this() is the first statement of the constructor and there should be at least one constructor without using this() statement.
From super/base Class − Use super() keyword to refer to parent class constructor. Make sure that super() is the first statement of the constructor.
From super/base Class − Use super() keyword to refer to parent class constructor. Make sure that super() is the first statement of the constructor.
 Live Demo
class A {
   public int a;
   public A() {
      this(-1);
   }
   public A(int a) {
      this.a = a;
   }
   public String toString() {
      return "[ a= " + this.a + "]";
   }
}
class B extends A {
   public int b;
   public B() {
      this(-1,-1);
   }
   public B(int a, int b) {
      super(a);
      this.b = b;
   }
   public String toString() {
      return "[ a= " + this.a + ", b = " + b + "]";
   }
}
public class Tester {
   public static void main(String args[]) {
      A a = new A(10);
      System.out.println(a);
      B b = new B(11,12);
      System.out.println(b);
      A a1 = new A();
      System.out.println(a1);
      B b1 = new B();
      System.out.println(b1);
   }
}
[ a= 10]
[ a= 11, b = 12]
[ a= -1]
[ a= -1, b = -1]
How to search for files using the wildcard character (*) in PowerShell?

You can also search for files with a specific name or using the wildcard (*) character.
Below command will search for the files (including hidden files) starting with “Bac”.
Get-ChildItem D:\Temp -Recurse -Force -Include Bac*
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp -Recurse -Force -Include Bac*
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       24-11-2018     11:34           6215 Backup.xml
When you use the wildcard character (*) at both the ends, file name containing that string will be displayed. For example, the below command will display all the files which contain the word “tmp”.
Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp*

PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Recurse -Force -Include *tmp*
    Directory: D:\Temp\GPO_backup\{C9C3DB4C-2E51-4201-B3C3-7C0F1ACECBE9}\DomainSysvol\GPO\Machine\microsoft\windows
    nt\SecEdit
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       24-11-2018     11:34          16028 GptTmpl.inf
Python PIL | ImageDraw.Draw.multiline_textsize() - GeeksforGeeks

17 Sep, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageDraw module provide simple 2D graphics for Image objects. You can use this module to create new images, annotate or retouch existing images, and to generate graphics on the fly for web use.
ImageDraw.Draw.multiline_textsize() Return the size of the given string, in pixels.
Syntax:ImageDraw.Draw.multiline_textsize(text, font=None, spacing=0)
Parameters:text – Text to be measured.font – An ImageFont instance.spacing – The number of pixels between lines.
Return Type:returns an image with text.
Image Used:
Code : Using ImageDraw.Draw.multiline_textsize
     # Importing Image and ImageFont, ImageDraw module from PIL package from PIL import Image, ImageFont, ImageDraw       # creating a image object image = Image.open(r'C:\Users\System-Pc\Desktop\rose.jpg')   draw = ImageDraw.Draw(image)   #specified font sizefont = ImageFont.truetype(r'C:\Users\System-Pc\Desktop\arial.ttf',30)  text =u"""\ALWAYS BE HAPPY(LAUGHING IS THE \n BEST MEDICINE)"""  # drawing text sizedraw.text((20,18), text,font = None,spacing=0)   image.show() 
Output:
Image-Processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
Tryit Editor v3.7

Tryit: two classes
Python Tkinter - Message - GeeksforGeeks

26 Mar, 2020
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
Note: For more information, refer to Python GUI – tkinter
The Message widget is used to show the message to the user regarding the behavior of the python application. The message text contains more than one line.
Syntax:The syntax to use the message is given below.
w = Message( master, options)
Parameters:
master: This parameter is used to represents the parent window.
options:There are many options which are available and they can be used as key-value pairs separated by commas.
Options:Following are commonly used Option can be used with this widget :-
anchor: This option is used to decide the exact position of the text within the space .Its default value is CENTER.
bg: This option used to represent the normal background color.
bitmap: This option used to display a monochrome image.
bd: This option used to represent the size of the border and the default value is 2 pixels.
cursor: By using this option, the mouse cursor will change to that pattern when it is over type.
font: This option used to represent the font used for the text.
fg: This option used to represent the color used to render the text.
height: This option used to represent the number of lines of text on the message.
image: This option used to display a graphic image on the widget.
justify: This option used to control how the text is justified: CENTER, LEFT, or RIGHT.
padx: This option used to represent how much space to leave to the left and right of the widget and text. It’s default value is 1 pixel.
pady: This option used to represent how much space to leave above and below the widget. It’s default value is 1 pixel.
relief: The type of the border of the widget. It’s default value is set to FLAT.
text: This option used use newlines (“\n”) to display multiple lines of text.
variable: This option used to represents the associated variable that tracks the state of the widget.
width: This option used to represents the width of the widget. and also represented in the number of characters that are represented in the form of texts.
wraplength: This option will be broken text into the number of pieces.
Example:
from tkinter import *  root = Tk()root.geometry("300x200")  w = Label(root, text ='GeeksForGeeks', font = "50") w.pack()    msg = Message( root, text = "A computer science portal for geeks")      msg.pack()    root.mainloop() 
Output:
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
How to remove empty rows from R dataframe? - GeeksforGeeks

26 Mar, 2021
A dataframe can contain empty rows and here with empty rows we don’t mean NA, NaN or 0, it literally means empty with absolutely no data. Such rows are obviously wasting space and making data frame unnecessarily large. This article will discuss how can this be done.
To remove rows with empty cells we have a syntax in the R language, which makes it easier for the user to remove as many numbers of empty rows in the data frame automatically.
Syntax:
data <- data[!apply(data == “”, 1, all),]
Approach
Create dataframe
Select empty rows
Remove those rows
Copy the resultant dataframe
Display dataframe
Example 1:
R
gfg <- data.frame(a=c('i','','iii','iv','','vi','','viii','','x'),                  b=c('I','','III','IV','','VI','','VIII','','X'),                   c=c('1','','3','4','','6','','8','','10'),                   d=c('a','','c','d','','f','','h','','j'))  print('Original dataframe:-')gfg  gfg <- gfg[!apply(gfg == "", 1, all),]print('Modified dataframe:-')gfg
Output:
Example 2:
R
gfg <- data.frame( A=c('a','','c','','e'),                   B=c('5','','5','','5'),                   C=c('1','','1','','1'),                   D=c('3','','3','','3'),                   E=c('#','','#','','#'),                   F=c('@','','@','','@'),                   H=c('8','','8','','8'))                     print('Original dataframe:-')gfg  gfg <- gfg[!apply(gfg == "", 1, all),]print('Modified dataframe:-')gfg
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R