code-rag-bench/online-tutorials huggingface dataset:
Get Nth Column of Matrix in Python

When it is required to get the ‘n’th column of a matrix, the ‘any’ method can be used.
Below is a demonstration of the same −
 Live Demo
my_list = [[34, 67, 89], [16, 27, 86], [48, 30, 0]]

print("The list is : ")
print(my_list)

N = 1
print("The value of N has been initialized to -")
print(N)
elem = 30

my_result = any(sub[N] == elem for sub in my_list)

print("Does the element exist in a particular column ? ")
print(my_result)
The list is :
[[34, 67, 89], [16, 27, 86], [48, 30, 0]]
The value of N has been initialized to -
1
Does the element exist in a particular column ?
True
A list of list is defined, and is displayed on the console.
A list of list is defined, and is displayed on the console.
The value of N is initialized.
The value of N is initialized.
This is displayed on the console.
This is displayed on the console.
An elem variable is assigned an integer value.
An elem variable is assigned an integer value.
The any method is used to see if any element in the list matches the elem variable previously defined.
The any method is used to see if any element in the list matches the elem variable previously defined.
The results are stored in a variable.
The results are stored in a variable.
This is displayed as output on the console.
This is displayed as output on the console.
How to calculate the nth root of a number in JavaScript?

To calculate the end root of a number, use Math.abs() method. Here, we’re using the Match.pow method also. You can try to run the following code to calculate the square root of numbers in JavaScript −
Live Demo
<html>
   <head>
      <title>Calculate root</title>
   </head>

   <body>
      <script>
         function displayRoot(x, num) {
            val = num % 2;
            if((val == 1) || x < 0)
            x = -x;
            var a, num;
            a = Math.pow(x, 1 / num);
            num = Math.pow(a, num);
            if(Math.abs(x - num) < 1 &amp;&amp; (x > 0 === num > 0))
            return val ? -a : a;
         }
         document.write(displayRoot(36, 2));
         document.write("<br>"+displayRoot(49, 2));
         document.write("<br>"+displayRoot(36, -2));
         document.write("<br>"+displayRoot(216, -2));
      </script>
   -+
   </body>
</html>
Raise x to the power n using Recursion in Java

The power of a number can be calculated using recursion. Here the number is x and it is raised to power n.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   static double pow(double x, int n) {
      if (n != 0)
         return (x * pow(x, n - 1));
      else
         return 1;
   }
   public static void main(String[] args) {
      System.out.println("7 to the power 3 is " + pow(7, 3));
      System.out.println("4 to the power 1 is " + pow(4, 1));
      System.out.println("9 to the power 0 is " + pow(9, 0));
   }
}
7 to the power 3 is 343.0
4 to the power 1 is 4.0
9 to the power 0 is 1.0
Now let us understand the above program.
The method pow() calculates x raised to the power n. If n is not 0, it recursively calls itself and returns x * pow(x, n - 1). If n is 0, it returns 1. A code snippet which demonstrates this is as follows:
static double pow(double x, int n) {
   if (n != 0)
      return (x * pow(x, n - 1));
   else
      return 1;
}
In main(), the method pow() is called with different values. A code snippet which demonstrates this is as follows:
public static void main(String[] args) {
   System.out.println("7 to the power 3 is " + pow(7, 3));
   System.out.println("4 to the power 1 is " + pow(4, 1));
   System.out.println("9 to the power 0 is " + pow(9, 0));
}
C++ Program for Inorder Tree Traversal without Recursion

If a binary tree is traversed in-order, the left subtree is visited first, then the root and later the right sub-tree. The output the key in ascending order in in_order traversal. This is a C++ Program for Inorder Tree Traversal without Recursion.
Begin  
   Function inOrder():
      Declare a stack s.
      Declare the current node as root.
      While current node is not null and stack is not empty do
         While current node is not null do
            Push the current node on the top of the stack
            Make the left child node as current node
         Point the current node at the top of the stack.
         Pop the top most node from the stack
         Print the current node.
         Make the right node as current node.  
      Insert some elements at root, left node and right node in stack.
      Call the inOrder() function to traverse the tree. 
End.
 Live Demo
#include<bits/stdc++.h>
using namespace std;

struct n {
   int d;
   struct n* l;
   struct n* r;
   n (int d) {
      this->d = d;
      l = r = NULL;
   }
};

void inOrder(struct n *root) {
   stack<n *> s;
   n *current = root;

   while (current != NULL || s.empty() == false) {
      while (current != NULL) {
         s.push(current);
         current = current->l;
      }

      current = s.top();
      s.pop();

      cout << current->d << " ";
      current = current->r;
   }
}

int main() {
   struct n *root = new n(7);

   root->l = new n(6);
   root->r = new n(2);
   root->l->l = new n(1);
   root->l->r = new n(9);

   inOrder(root);
   return 0;
}
1 6 9 7 2
How can I remove a button or make it invisible in Android using Kotlin?

This example demonstrates how to remove a button or make it invisible in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Tutorials Point"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:background="@android:color/white"
      android:padding="4dp"
      android:text="Click to hide me "
      android:textColor="@android:color/holo_red_dark"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val button: Button = findViewById(R.id.button)
      button.setOnClickListener {
         button.visibility = View.INVISIBLE
         Toast.makeText(baseContext, "Button is hidden", 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="com.example.q11">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Resolve Syntax error near “ORDER BY order DESC” in MySQL?

The word order is a reserved order in MySQL and you have used it in the query. To get rid of the syntax error, you need to use backticks(` `) around the order.
The correct syntax is as follows −
select *from yourTableName ORDER BY `order` DESC;
Let us first create a table −
mysql> create table DemoTable
   (
   `order` int
   );
Query OK, 0 rows affected (0.58 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(67);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(90);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+-------+
| order |
+-------+
| 89    |
| 67    |
| 90    |
| 56    |
+-------+
4 rows in set (0.00 sec)
Following is the query to remove syntax error near ORDER BY −
mysql> select *from DemoTable ORDER BY `order` DESC;
+-------+
| order |
+-------+
| 90    |
| 89    |
| 67    |
| 56    |
+-------+
4 rows in set (0.00 sec)
hash command in Linux with examples - GeeksforGeeks

21 May, 2019
hash command in Linux system is the built-in command of bash which is used to maintain a hash table of recently executed programs. It remembers and shows the program locations. It will give the full pathname of each command name.
Syntax:
hash [-lr] [-p pathname] [-dt] [name ...]
Options:
-d: This is used to forget the remembered location of each NAME.
-l: It will display in a format that may be reused as input.
-p: pathname use PATHNAME as the full pathname of NAME.
-r: Forget all remembered locations.
-t: To display the remembered location of each NAME, preceding each location with the corresponding NAME if multiple NAMEs are given.
Example 1: hash command without any option
hash
Example 2: hash command with -r option
Example 3: hash command with -l command
hash -l
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
mv command in Linux with examples
nohup Command in Linux with Examples
scp command in Linux with Examples
Docker - COPY Instruction
chown command in Linux with Examples
nslookup command in Linux with Examples
SED command in Linux | Set 2
Named Pipe or FIFO with example C program
uniq Command in LINUX with examples
C++ Program to check if input is an integer or a string

Given with an input by the user and the task is to check whether the given input is an integer or a string.
Integer can be any combination of digits between 0 -9 and string can be any combination excluding 0 – 9.
Input-: 123
Output-: 123 is an integer
Input-: Tutorials Point
Output-: Tutorials Point is a string
Approach used below is as follows −
Input the data.
Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.
Print the resultant output.
Start
Step 1->declare function to check if number or string
   bool check_number(string str)
   Loop For int i = 0 and i < str.length() and i++
      If (isdigit(str[i]) == false)
         return false
      End
   End
   return true
step 2->Int main()
   set string str = "sunidhi"
      IF (check_number(str))
         Print " is an integer"
      End
      Else
         Print " is a string"
      End
      Set string str1 = "1234"
         IF (check_number(str1))
            Print " is an integer"
         End
         Else
            Print " is a string"
         End
Stop
 Live Demo
#include <iostream>
using namespace std;
//check if number or string
bool check_number(string str) {
   for (int i = 0; i < str.length(); i++)
   if (isdigit(str[i]) == false)
      return false;
      return true;
}
int main() {
   string str = "sunidhi";
   if (check_number(str))
      cout<<str<< " is an integer"<<endl;
   else
      cout<<str<< " is a string"<<endl;
      string str1 = "1234";
   if (check_number(str1))
      cout<<str1<< " is an integer";
   else
      cout<<str1<< " is a string";
}
sunidhi is a string
1234 is an integer
VB.Net - Select Case Statement

A Select Case statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each select case.
The syntax for a Select Case statement in VB.Net is as follows −
Select [ Case ] expression
   [ Case expressionlist
      [ statements ] ]
   [ Case Else
      [ elsestatements ] ]
End Select

Where,
expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort.
expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort.
expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are separated by commas.
expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are separated by commas.
statements − statements following Case that run if the select expression matches any clause in expressionlist.
statements − statements following Case that run if the select expression matches any clause in expressionlist.
elsestatements − statements following Case Else that run if the select expression does not match any clause in the expressionlist of any of the Case statements.
elsestatements − statements following Case Else that run if the select expression does not match any clause in the expressionlist of any of the Case statements.
Module decisions
   Sub Main()
      'local variable definition
      Dim grade As Char
      grade = "B"
      Select grade
          Case "A"
              Console.WriteLine("Excellent!")
          Case "B", "C"
              Console.WriteLine("Well done")
          Case "D"
              Console.WriteLine("You passed")
          Case "F"
              Console.WriteLine("Better try again")
          Case Else
              Console.WriteLine("Invalid grade")
      End Select
      Console.WriteLine("Your grade is  {0}", grade)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B


    63 Lectures 
     4 hours 

 Frahaan Hussain

    103 Lectures 
     12 hours 

 Arnold Higuit

    60 Lectures 
     9.5 hours 

 Arnold Higuit

    97 Lectures 
     9 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
TypeScript - Parameterized a Function

Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined.
While calling a function, there are two ways that arguments can be passed to a function −
Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Call by pointer
This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter
Following are the ways in which parameters can be used by functions −
function func_name( param1 [:datatype], ( param2 [:datatype]) {   
}

function test_param(n1:number,s1:string) { 
   console.log(n1) 
   console.log(s1) 
} 
test_param(123,"this is a string")

The snippet declares a function test_param with three parameters namely, n1, s1 and p1.
The snippet declares a function test_param with three parameters namely, n1, s1 and p1.
It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameter is considered to be of the type any. In the above example, the third parameter will be of the type any.
It is not mandatory to specify the data type of the parameter. In the absence of a data type, the parameter is considered to be of the type any. In the above example, the third parameter will be of the type any.
The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error.
The data type of the value passed must match the type of the parameter during its declaration. In case the data types don’t match, the compiler throws an error.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
function test_param(n1, s1) {
   console.log(n1);
   console.log(s1);
}
test_param(123, "this is a string");

The output of the above code is as follows −
123 
this is a string


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Go - break statement

The break statement in Go programming language has the following two usages −
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
It can be used to terminate a case in a switch statement.
It can be used to terminate a case in a switch statement.
If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.
The syntax for a break statement in Go is as follows −
break;

package main

import "fmt"

func main() {
   /* local variable definition */
   var a int = 10

   /* for loop execution */
   for a < 20 {
      fmt.Printf("value of a: %d\n", a);
      a++;
      if a > 15 {
         /* terminate the loop using break statement */
         break;
      }
   }
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Tk - Canvas Polygon Widget

Polygon widget is used to draw a polygon shape in canvas. The syntax for polygon widget is shown below −
canvasName create polygon x1 y1 x2 y2 ... xn yn options
x1 y1 and x2 y2 ... xn yn are used to determine the end points of a polygon.
The options available for the  polygon widget are listed below in the following table −
-outline color
Determines the outline color.
-fill color
The fill color fills the oval with the color.
-stipple bitmap
The stipple pattern to use if the -fill option is being used.
-width number
Determines the width.
-smooth boolean
This can be set to true make the line segments to be rendered with a set of Bezier splines.
-splinesteps number
Determines the number of line segment for bezier splines.
A simple example for polygon widget is shown below −
#!/usr/bin/wish

canvas .myCanvas -background red -width 200 -height 200 
pack .myCanvas
.myCanvas create polygon 50 50 100 80 120 120 100 190 -fill yellow -outline green
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
How to create an index in MongoDB using Java?

In MongoDB to create an index, you need to use createIndex() method.
db.COLLECTION_NAME.createIndex({KEY:1})
Where the key is the name of the file on which you want to create index and 1 is for ascending order. To create an index in descending order you need to use -1.
In Java, you can create an Index using the createIndex() method, to this method you need to pass the type of the index (ascending or descending) and the field name on which you want to create the index, as −
createIndex(Indexes.descinding("name"));
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import com.mongodb.MongoClient;
public class CreatingIndex {
   public static void main( String args[] ) {
      //Creating a MongoDB client
      MongoClient mongo = new MongoClient( "localhost" , 27017 );
      //Accessing the database
      MongoDatabase database = mongo.getDatabase("myDatabase");
      //Creating a collection
      database.createCollection("sampleCollection");
      //Retrieving the collection on which you want to create the index
      MongoCollection<Document> coll = database.getCollection("sampleCollection");
      //Creating an index
      coll.createIndex(Indexes.ascending("age"));
      System.out.println("Index created successfully");
      //Printing the list of indices in the collection
      for (Document index : coll.listIndexes()) {
         System.out.println(index.toJson());
      }
   }
}
Index created successfully
{"v": 2, "key": {"_id": 1}, "name": "_id_", "ns": "myDatabase.sampleCollection"}
{"v": 2, "key": {"age": 1}, "name": "age_1", "ns": "myDatabase.sampleCollection"}
C++ Program to Find Factorial of a Number using Recursion

Factorial of a non-negative integer n is the product of all the positive integers that are less than or equal to n.
For example: The factorial of 4 is 24.
4! = 4 * 3 * 2 *1
4! = 24
The factorial of an integer can be found using a recursive program or an iterative program.
The following program demonstrates a recursive program to find the factorial of a number −
 Live Demo
#include <iostream>
using namespace std;
int fact(int n) {
   if ((n==0)||(n==1))
   return 1;
   else
   return n*fact(n-1);
}
int main() {
   int n = 4;
   cout<<"Factorial of "<<n<<" is "<<fact(n);
   return 0;
}
Factorial of 4 is 24
In the above program, the function fact() is a recursive function. The main() function calls fact() using the number whose factorial is required. This is demonstrated by the following code snippet.
cout<<"Factorial of "<<n<<" is "<<fact(n);
If the number is 0 or 1, then fact() returns 1. If the number is any other, then fact() recursively calls itself with the value n-1.
This is demonstrated using the following code snippet.
int fact(int n) {
   if ((n==0)||(n==1))
   return 1;
   else
   return n*fact(n-1);
}
Use MySQL concat() and lower() effectively

The contact() method is used to concatenate. However, lower() is used to change the case to lowercase. For our example, let us create a table.
The query to create a table is as follows
mysql> create table concatAndLowerDemo
   -> (
   -> FirstValue varchar(10),
   -> SecondValue varchar(10),
   -> ThirdValue varchar(10),
   -> FourthValue varchar(10)
   -> );
Query OK, 0 rows affected (0.55 sec)
Now you can insert some records in the table using insert command.
The query is as follows
mysql> insert into concatAndLowerDemo values('John','12345','Java','MySQL');
Query OK, 1 row affected (0.21 sec)
mysql> insert into concatAndLowerDemo values('Hi','12345','98764','MongoDB');
Query OK, 1 row affected (0.24 sec)
mysql> insert into concatAndLowerDemo values('9485','746464','903940','cpp');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from concatAndLowerDemo;
The following is the output
+------------+-------------+------------+-------------+
| FirstValue | SecondValue | ThirdValue | FourthValue |
+------------+-------------+------------+-------------+
| John       | 12345       | Java       | MySQL       |
| Hi         | 12345       | 98764      | MongoDB     |
| 9485       | 746464      | 903940     | cpp         |
+------------+-------------+------------+-------------+
3 rows in set (0.00 sec)
Here is the query to use concat() and lower() in the same query
mysql> select lower(concat(FirstValue,SecondValue,ThirdValue,FourthValue)) AS lowerDemo from concatAndLowerDemo;
The following is the output
+---------------------+
| lowerDemo           |
+---------------------+
| john12345javamysql  |
| hi1234598764mongodb |
| 9485746464903940cpp |
+---------------------+
3 rows in set (0.00 sec)
How to validate email using jQuery?

To validate email using jQuery, use the regex pattern. You can try to run the following code to learn how to validate email using jQuery −
Live Demo
<!DOCTYPE html>
<html>
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>  
    $(document).ready(function() {
      $('.error').hide();
      $('#submit').click(function(){
        var name = $('#name').val();
        var email = $('#email').val();

        if(name== ''){
          $('#name').next().show();
          return false;
        }
        if(email== ''){
          $('#email').next().show();
          return false;
        }
        if(IsEmail(email)==false){
          $('#invalid_email').show();
          return false;
        }
        $.post("", $("#myform").serialize(),  function(response) {
          $('#myform').fadeOut('slow',function(){
          $('#correct').html(response);
          $('#correct').fadeIn('slow');
       });
     });
    return false;
  });
 });
 function IsEmail(email) {
  var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  if(!regex.test(email)) {
    return false;
  }else{
    return true;
  }
}
</script>
</head>
<body>
  <form action="" method="post" id="contactform">
  <table class="mytable">
    <tr>
     <td><label for="name">Name :</label></td>
     <td class="name"> <input name="name" id="name" type="text" placeholder="Please enter your name" class="contact-input"><span class="error">Enter your name here</span></td>
    </tr>
    <tr>
     <td><label for="email">Email :</label></td>
       <td class="email"><input name="email" id="email" type="text" placeholder="Please enter your email" class="contact-input"><span class="error">Enter your email-id here</span>
         <span class="error" id="invalid_email">Email-id is invalid</span>
       </td>
     </td>
    </tr>
    <tr>
     <input type="submit" class="contactform-buttons" id="submit"value="Send" />
     <input type="reset" class="contactform-buttons" id="" value="Clear" />
   </tr>
  </tr>
</table>
</form>
  <div id="correct" style="color:gray;"></div>
</body>
</html>
2 Key keyboard problem in JavaScript

Suppose the following situation −
Initially on a notepad only one character 'A' is present. We can perform two operations on this notepad for each step −
Copy All − We can copy all the characters present on the notepad (partial copy is not allowed).
Copy All − We can copy all the characters present on the notepad (partial copy is not allowed).
Paste − We can paste the characters which were copied last time.
Paste − We can paste the characters which were copied last time.
We are required to write a JavaScript function that takes in a number, let's call it num as the only argument. Our function is required to compute and return the minimum number of steps (copy all or paste) required to print 'A' num times.
For example −
If the input number is −
const num = 3;
Then the output should be −
const output = 3;
because, the steps are −
copy all (result: 'A')
copy all (result: 'A')
paste all (result: 'AA')
paste all (result: 'AA')
paste all (result: 'AAA')
paste all (result: 'AAA')
The code for this will be −
 Live Demo
const num = 3;
const minimumSteps = (num = 1) => {
   let [curr, copy, steps] = [1, 0, 0];
   while(curr != num){
      if((copy < curr) && ((num - curr) % curr) == 0) {
         copy = curr;
      }else{
         curr += copy;
      };
      steps += 1;
   };
   return steps;
};
console.log(minimumSteps(num));
And the output in the console will be −
3
C Program to print all permutations of a given string

In this problem, we are given a string. Our task is to create a c program to print all permutations of a given string.
This program will find all possible combinations of the given string and print them.
Permutation is the arrangement of all parts of an object, in all possible orders of arrangement.
Let’s take an example to understand the problem,
xyz
xyz, xzy, yxz, yzx, zxy, zyx
These are all permutations take in order.
To solve this problem, we will use backtracking i.e. taking each character of the string as the first character of the permutation and then sequentially choosing all remaining characters of the string one by one. And thus, printing all the permutations of the string.
//Program to print all permutations of a given string −
 Live Demo
#include <iostream>
using namespace std;
void findPermutations(string str, int l, int r){
   if (l == r)
   cout<<str<<" ";
   else{
      for (int i = l; i <= r; i++){
         swap(str[l], str[i]);
         findPermutations(str, l+1, r);
         swap(str[l], str[i]);
      }
   }
}
int main(){
   string str = "WXYZ";
   int n = str.size();
   findPermutations(str, 0, n-1);
   return 0;
}
WXYZ WXZY WYXZ WYZX WZYX WZXY XWYZ XWZY XYWZ XYZW XZYW XZWY YXWZ YXZW YWXZ 
YWZX YZWX YZXW ZXYW ZXWY ZYXW ZYWX ZWYX ZWXY
Difference between Constructors and Methods in Java

Constructors are special methods used to initialize objects whereas methods are used to execute certain statements. Following are the important differences between Constructors and Methods.
public class JavaTester {
   int num;
   JavaTester(){
      num = 3;
      System.out.println("Constructor invoked. num: " + num);
   }
   public void init(){
      num = 5;
      System.out.println("Method invoked. num: " + num);
   }
   public static void main(String args[]) {
      JavaTester tester = new JavaTester();
      tester.init();
   }
}
Constructor invoked. num: 3
Method invoked. num: 5
Style input type reset with CSS

The input type button can be a submit button or reset button. With CSS, we can style any button on a web page.
You can try to run the following code to style input type button:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         input[type = submit], input[type = reset] {
            background-color: orange;
            border: none;
            text-decoration: none;
            color: white;
            padding: 20px 20px;
            margin: 20px 20px;
            cursor: pointer;
         }
      </style>
   </head>
   <body>
      <p>Fill the below form,</p>
      <form>
         <label for = "subject">Subject</label>
         <input type = "text" id = "subject" name = "sub"><br><br>
         <label for = "student">Student</label>
         <input type = "text" id = "student" name = "stu"><br>
         <input type = "reset" value = "Reset">
         <input type = "submit" value = "Submit">
      </form>
   </body>
</html>
Tryit Editor v3.7

Tryit: HTML font-family
Codenation Interview Experience | Online Test - GeeksforGeeks

28 Sep, 2020
Recently, on-campus drive was held for Codenation for Software Development Engineer Intern.
The process was:
1. Online Test
2. Telephonic Interview
3. Skype Interview
Online test for on-campus was held on September 15th 2020. The off-campus coding challenge known as CodeAgon for the hiring of same position is going to be held on 28th of September. So, I just wanted to share questions asked in online test.
There were three questions:
First Question:
Alice has got a Random Number Generator. The generator generates a random number from 1 to N. 
Now Alice wants to know the expected number of turns until K distinct elements are generated. 
Help Alice find this value modulo 109+7. 
Problem Constraints:
1<=K<=N<=105
Input format:
Input consists of 2 arguments, N=A and K=B in this order.
Output format:
Return a single integer , the expected value modulo 109+7.
Second Question:
Given a grid A of size N*M, 2 players are playing a game on it taking alternate turns. 
In each turn, a player chooses a subset of elements from any row and replaces each one of them with their proper divisor. 
A proper divisor of a number N is any divisor of N, not equal to N. 
The player who is unable to move, loses. Determine the winner of the game.
Problem Constraints:
1<=N, M<=103
1<=A[i][j]<=106
Input format:
The only line of argument contains the grid A.
Output format:
Return a single integer, 1 or 2 , depending upon which player wins.
Third Question:
Given a tree of N nodes numbers 0 to N-1. Each node have binary value i.e 0 or 1 denoted by integer array A. 
The beauty of a ith node is 2i*A[i]. The total beauty of the Tree is sum of beauty of each node.
Aman is superstitious and will accept the tree only its total beauty is 2N -1 or 0. 
He asked you to make the tree acceptable but you can only use the following operation.
In each operation, select any node X and call flip(X).
Python
flip(X):  for (v: 0 to N-1):    if(all nodes in path from X to node v have same value)        A[v] = 1 - A[v]
Find the minimum number of operation required to make the tree acceptable.
Problem Constraints:
1<=N<=105
0<=A[i] <=1
0<=B[i][0], B[i][1]<=N-1
Input format:
First argument is an integer array A of size N denoting the node value.
Second argument is a 2D array B of size (N-1)*2 where ith edge is between B[i][0] and B[i][1] node
Output format:
Return an integer denoting the minimum number of operations required.
Codenation
Marketing
Interview Experiences
Codenation
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Interview Experience for Internship (Via Engage)
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
Amazon Interview Experience for SDE-1
Oracle Interview Experience | Set 69 (Application Engineer)
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Amazon Interview Experience for SDE-1(Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1
Infosys DSE Interview Experience 2021
Create a striped Bootstrap progress bar

Follow the below given steps to create a striped progress bar in Bootstrap −
Add a <div> with a class of .progress and .progress-striped.
Next, inside the above <div>, add an empty <div> with a class of .progress-bar and class progress-bar-* where * could be success, info, warning, danger.
Add a style attribute with the width expressed as a percentage. Say, for example, style = "60%"; indicates that the progress bar was at 60%.
You can try to run the following code to form a striped progress bar −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <h2>Striped Progress Bars</h2>
      <h3>Warning Progress Bar</h3>
      <div class = "progress progress-striped">
         <div class = "progress-bar progress-bar-warning" role = "progressbar"
         aria-valuenow = "45" aria-valuemin = "0" aria-valuemax = "100" style="width: 45%;">
            <span class = "sr-only">45%Complete (warning)</span>
         </div>
      </div>
      <h3>Danger Progress Bar</h3>
      <div class = "progress progress-striped">
         <div class = "progress-bar progress-bar-danger" role = "progressbar"
            aria-valuenow = "80" aria-valuemin = "0" aria-valuemax = "100" style = "width: 80%;">
            <span class = "sr-only">80% Complete (danger)</span>
         </div>
      </div>
   </body>
</html>
sympy.stats.Reciprocal() in Python - GeeksforGeeks

08 Jun, 2020
With the help of sympy.stats.Reciprocal() method, we can get the continuous random variable which represents the Reciprocal distribution.
Syntax : sympy.stats.Reciprocal(name, a, b)Where, a and b are real number and a, b > 0.
Return : Return the continuous random variable.
Example #1 :In this example we can see that by using sympy.stats.Reciprocal() method, we are able to get the continuous random variable representing reciprocal distribution by using this method.
# Import sympy and Reciprocalfrom sympy.stats import Reciprocal, densityfrom sympy import Symbol, pprint  z = Symbol("z")a = Symbol("a", positive = True)b = Symbol("b", positive = True)  # Using sympy.stats.Reciprocal() methodX = Reciprocal("x", a, b)gfg = density(X)(z)  print(gfg)
Output :
1/(x*(-log(a) + log(b)))
Example #2 :
# Import sympy and Reciprocalfrom sympy.stats import Reciprocal, densityfrom sympy import Symbol, pprint  z = 0.35a = 1b = 2  # Using sympy.stats.Reciprocal() methodX = Reciprocal("x", a, b)gfg = density(X)(z)  print(gfg)
Output :
0.0861703622690834
Python SymPy-Stats
SymPy
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
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
SQLite - ALTER TABLE Command

SQLite ALTER TABLE command modifies an existing table without performing a full dump and reload of the data. You can rename a table using ALTER TABLE statement and additional columns can be added in an existing table using ALTER TABLE statement.
There is no other operation supported by ALTER TABLE command in SQLite except renaming a table and adding a column in an existing table.
Following is the basic syntax of ALTER TABLE to RENAME an existing table.
ALTER TABLE database_name.table_name RENAME TO new_table_name;

Following is the basic syntax of ALTER TABLE to add a new column in an existing table.
ALTER TABLE database_name.table_name ADD COLUMN column_def...;

Consider the COMPANY table with the following records −
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
Now, let's try to rename this table using ALTER TABLE statement as follows −
sqlite> ALTER TABLE COMPANY RENAME TO OLD_COMPANY;
The above SQLite statement will rename COMPANY table to OLD_COMPANY. Now, let's try to add a new column in OLD_COMPANY table as follows −
sqlite> ALTER TABLE OLD_COMPANY ADD COLUMN SEX char(1);
COMPANY table is now changed and following will be the output from SELECT statement.
ID          NAME        AGE         ADDRESS     SALARY      SEX
----------  ----------  ----------  ----------  ----------  ---
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
It should be noted that newly added column is filled with NULL values.

    25 Lectures 
     4.5 hours 

 Sandip Bhattacharya

    17 Lectures 
     1 hours 

 Laurence Svekis

    5 Lectures 
     51 mins

 Vinay Kumar
 Print
 Add Notes
 Bookmark this page
How to read a line from the console in C#?

The ReadLine() method is used to read a line from the console in C#.
str = Console.ReadLine();
The above will set the line in the variable str.
 Live Demo
using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      string str;

      // use ReadLine() to read the entered line
      str = Console.ReadLine();

      // display the line
      Console.WriteLine("Input = {0}", str);
   }
}
Input =
Above, we displayed a line using the Console.ReadLine() method. The string is entered by the user from the command line.
Adjust the width of box in boxplot in Python Matplotlib

To adjust the width of box in boxplot in Python matplotlib, we can use width in the boxplot()
method.
Set the figure size and adjust the padding between and around the subplots.
Make a Pandas dataframe, i.e., two-dimensional, size-mutable, potentially heterogeneous tabular data.
Make a box and whisker plot, using boxplot() method with width tuple to adjust the box in boxplot.
To display the figure, use show() method.
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = pd.DataFrame({"Box1": np.random.rand(10), "Box2": np.random.rand(10)})
ax = plt.boxplot(data, widths=(0.25, 0.5))

plt.show()
Python - Odd Frequency Characters - GeeksforGeeks

10 May, 2020
Sometimes, while working with Python strings, we can have a problem in which we need to extract all the string characters which have odd number of occurrences. This problem can have applications in domains such as data domain and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_str = ‘geekforgeeks’Output : [‘r’, ‘o’, ‘f’, ‘s’]
Input : test_str = ‘g’Output : [‘g’]
Method #1 : Using defaultdict() + list comprehension + loopThe combination of above functions can be used to solve this problem. In this, we initialize the defaultdict() with integer and then perform frequency count. List comprehension is used to extract all the odd frequencies.
# Python3 code to demonstrate working of # Odd Frequency Characters# Using list comprehension + defaultdict()from collections import defaultdict  # helper_functiondef hlper_fnc(test_str):    cntr = defaultdict(int)    for ele in test_str:        cntr[ele] += 1    return [val for val, chr in cntr.items() if chr % 2 != 0]  # initializing stringtest_str = 'geekforgeeks is best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # Odd Frequency Characters# Using list comprehension + defaultdict()res = hlper_fnc(test_str)  # printing result print("The Odd Frequency Characters are : " + str(res))
The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']

 
Method #2 : Using list comprehension + Counter()The combination of above functionalities can be used to solve this problem. In this, we use Counter() to count the frequency.
# Python3 code to demonstrate working of # Odd Frequency Characters# Using list comprehension + Counter()from collections import Counter  # initializing stringtest_str = 'geekforgeeks is best for geeks'  # printing original stringprint("The original string is : " + str(test_str))  # Odd Frequency Characters# Using list comprehension + Counter()res =  [ chr for chr, count in Counter(test_str).items() if count & 1 ]  # printing result print("The Odd Frequency Characters are : " + str(res))
The original string is : geekforgeeks is best for geeks
The Odd Frequency Characters are : ['k', 'i', 't', 'g', 'e', 'b']

Python string-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
Python - Legendre polynomials using Recursion relation - GeeksforGeeks

11 Dec, 2019
Legendre polynomials are a type of orthogonal polynomials which occur often in science and engineering. Hence, their generation is crucial to those fields. There are different ways to evaluate a Legendre polynomial, using generating functions, Rodrigues formula, recurrence relation, Gram-Schmidt orthogonalization etc. One of the easiest and alsoone of the most accurate, method is using recurrence relation.
Here we use Bonnet’s recurrence relation of legendre polynomials, i.e, –
    
It can be implemented using Python by proceeding as follows-
We define Legendre polynomials as a function named P(n, x), where n is called the order of the polynomial and x is the point of evaluation. The base cases are if n is 0, then The value of the polynomial is always 1, and it is x when order is 1. These are the seed values required for the recurrence relation.For other values of n, the function is recursively defined, directly from the Bonnet’s recurrence. Thus, P(n, x) returns values of the Legendre polynomial, by recursion method (A function effectively defined with other base cases of the same function itself.)
Below is the Python implementation –
# Legendre polynomialdef P(n, x):     if(n == 0):        return 1 # P0 = 1    elif(n == 1):        return x # P1 = x    else:        return (((2 * n)-1)*x * P(n-1, x)-(n-1)*P(n-2, x))/float(n)  # Suppose, we want to find the value of # 3rd order legendre polynomial at x = 5# We can display the value by--  # Driver programn = 3X = 5print("The value of the polynomial at given point is:", P(n, X))
The value of the polynomial at given point is: 305.0

We can now also plot the Legendre polynomials (say from 1st order to 4th order) using matplotlib.
import matplotlib  # This is for use in webbrowser, can be ignored.matplotlib.use('Agg')   import matplotlib.pyplot as pltimport numpy as np  # Creating an array of x valuesx = np.linspace(-1, 1, 200)   # for which polynomial values are evaluated and plottedfor i in range(1, 5):      # Labelling according to order    plt.plot(x, P(i, x), label ="P"+str(i))   plt.legend(loc ="best")plt.xlabel("X")plt.ylabel("Pn")plt.show()
Engineering Mathematics
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Activation Functions
Difference between Propositional Logic and Predicate Logic
Proof that vertex cover is NP complete
Mathematics | Matrix Introduction
Logic Notations in LaTeX
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe