code-rag-bench/online-tutorials huggingface dataset:
NumPy - Array Attributes

In this chapter, we will discuss the various array attributes of NumPy.
This array attribute returns a tuple consisting of array dimensions. It can also be used to resize the array.
import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 
print a.shape
The output is as follows −
(2, 3)

# this resizes the ndarray 
import numpy as np 

a = np.array([[1,2,3],[4,5,6]]) 
a.shape = (3,2) 
print a 
The output is as follows −
[[1, 2] 
 [3, 4] 
 [5, 6]]

NumPy also provides a reshape function to resize an array.
import numpy as np 
a = np.array([[1,2,3],[4,5,6]]) 
b = a.reshape(3,2) 
print b
The output is as follows −
[[1, 2] 
 [3, 4] 
 [5, 6]]

This array attribute returns the number of array dimensions.
# an array of evenly spaced numbers 
import numpy as np 
a = np.arange(24) 
print a
The output is as follows −
[0 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16 17 18 19 20 21 22 23] 

# this is one dimensional array 
import numpy as np 
a = np.arange(24) 
a.ndim  

# now reshape it 
b = a.reshape(2,4,3) 
print b 
# b is having three dimensions
The output is as follows −
[[[ 0,  1,  2] 
  [ 3,  4,  5] 
  [ 6,  7,  8] 
  [ 9, 10, 11]]  
  [[12, 13, 14] 
   [15, 16, 17]
   [18, 19, 20] 
   [21, 22, 23]]] 

This array attribute returns the length of each element of array in bytes.
# dtype of array is int8 (1 byte) 
import numpy as np 
x = np.array([1,2,3,4,5], dtype = np.int8) 
print x.itemsize
The output is as follows −
1

# dtype of array is now float32 (4 bytes) 
import numpy as np 
x = np.array([1,2,3,4,5], dtype = np.float32) 
print x.itemsize
The output is as follows −
4

The ndarray object has the following attributes. Its current values are returned by this function.
C_CONTIGUOUS (C)
The data is in a single, C-style contiguous segment
F_CONTIGUOUS (F)
The data is in a single, Fortran-style contiguous segment
OWNDATA (O)
The array owns the memory it uses or borrows it from another object
WRITEABLE (W)
The data area can be written to. Setting this to False locks the data, making it read-only
ALIGNED (A)
The data and all elements are aligned appropriately for the hardware
UPDATEIFCOPY (U)
This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array
The following example shows the current values of flags.
import numpy as np 
x = np.array([1,2,3,4,5]) 
print x.flags
The output is as follows −
C_CONTIGUOUS : True 
F_CONTIGUOUS : True 
OWNDATA : True 
WRITEABLE : True 
ALIGNED : True 
UPDATEIFCOPY : False


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Recursively loop through an array and return number of items with JavaScript?

We have to write a function, say searchRecursively() that takes in an array and a search query
and returns the count of that search query in the nested array.
For example, if the array is given by −
const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james", ["michael", "nathan", "rakesh", "george"]]];
Then −
searchRecursively(names, ‘’rakesh’);
Should return 3 because it makes a total of 3 appearances in the array. Therefore, let’s write the
code for this recursive function −
const names = ["rakesh", ["kalicharan", "krishna", "rakesh", "james",
["michael", "nathan", "rakesh", "george"]]];
const searchRecursively = (arr, query, count = 0, len = 0) => {
   if(len < arr.length){
      if(Array.isArray(arr[len])){
         return searchRecursively(arr[len], query, count, 0);
      };
      if(arr[len] === query){
         return searchRecursively(arr, query, ++count, ++len);
      };
      return searchRecursively(arr, query, count, ++len);
   };
   return count;
};
console.log(searchRecursively(names, "rakesh"));
The output in the console will be −
3
Java Examples - create a banner using Applet

How to create a banner using Applet?
Following example demonstrates how to play a sound using an applet image using Thread class. It also uses drawRect(), fillRect(), drawString() methods of Graphics class.
import java.awt.*;
import java.applet.*;

public class SampleBanner extends Applet implements Runnable {
   String str = "This is a simple Banner ";
   Thread t ;
   boolean b;
   
   public void init() {
      setBackground(Color.gray);
      setForeground(Color.yellow);
   }
   public void start() {
      t = new Thread(this);
      b = false;
      t.start();
   }
   public void run () {
      char ch;
      for( ; ; ) {
      try {
         repaint();
         Thread.sleep(250);
         ch = str.charAt(0);
         str = str.substring(1, str.length());
         str = str + ch;
      }
      catch(InterruptedException e) {}
      }
   }
   public void paint(Graphics g) {
      g.drawRect(1,1,300,150);
      g.setColor(Color.yellow);
      g.fillRect(1,1,300,150);
      g.setColor(Color.red);
      g.drawString(str, 1, 150);
   }
}
The above code sample will produce the following result in a java enabled web browser.
View in Browser. 

The following is an another sample example to create a banner using Applet.
import java.awt.*;
import java.applet.*;

public class NewApplet extends Applet implements Runnable {
   String msg = " It is a moving Banner. ";
   char cha;
   boolean stopFlag = true;
   Thread t = null;
   
   public void start() {
      t = new Thread(this);
      stopFlag = false; 
      t.start();
   } 
   public void run() {
      for(;;) { 
         try { 
            repaint();
            Thread.sleep(250);
            cha = msg.charAt(0);
            msg = msg.substring(1,msg.length());
            msg = msg + cha;
            if(stopFlag) break;
         } 
         catch(InterruptedException e) {}
      } 
   } 
   public void stop(){
      stopFlag = true; 
      t = null;
   } 
   public void paint(Graphics g) { 
      g.drawString(msg,60,30);
   }
}
 Print
 Add Notes
 Bookmark this page
Java String toUpperCase() Method With Examples

04 Oct, 2021
The java string toUpperCase() method of String class has converted all characters of the string into an uppercase letter. There is two variant of toUpperCase() method. The key thing that is to be taken into consideration is toUpperCase() method worked same as to UpperCase(Locale.getDefault()) method as internally default locale is used. 
Syntax:
public String toUpperCase(Locale loc)
public String toUpperCase()
Parameter:  
Type 1: Locale value to be applied as it converts all the characters into
Type 2: NA
Return Type: It returns the string in uppercase letters.
Note: Lowercase is done using the rules of the given Locale.
Example 1:
java
// Java Program to Demonstrate Working of toUpperCase()// method  // Main classclass GFG {      // Main driver method    public static void main(String args[])    {          // Custom input string        String str = "Welcome! to Geeksforgeeks";          // Converting above input string to        // uppercase letters using UpperCase() method        String strup = str.toUpperCase();          // Print the uppercased string        System.out.println(strup);    }}
WELCOME! TO GEEKSFORGEEKS
Example 2:
java
// Java program to demonstrate Working of toUpperCase()// method of Locale class  // Importing Locale class from java.util packageimport java.util.Locale;  // Main classclass GFG {      // Main driver method    public static void main(String args[])    {          // Custom input string        String str = "Geeks for Geeks";          // Locales with the language "tr" for TURKISH        //"en" for ENGLISH is created        Locale TURKISH = Locale.forLanguageTag("tr");        Locale ENGLISH = Locale.forLanguageTag("en");          // Converting string str to uppercase letter        // using TURKISH and ENGLISH language        String strup1 = str.toUpperCase(TURKISH);        String strup2 = str.toUpperCase(ENGLISH);        System.out.println(strup1);        System.out.println(strup2);    }}
GEEKS FOR GEEKS
GEEKS FOR GEEKS
mihir89
solankimayank
Java-Functions
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Stack Class in Java
Python List list() Method

Python list method list() takes sequence types and converts them to lists. This is used to convert a given tuple into list.
Note − Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket.
Following is the syntax for list() method −
list( seq )

seq − This is a tuple to be converted into list.
seq − This is a tuple to be converted into list.
This method returns the list.
The following example shows the usage of list() method.
#!/usr/bin/python

aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print "List elements : ", aList
When we run above program, it produces following result −
List elements :  [123, 'xyz', 'zara', 'abc']
LOCATE() function in MySQL

17 Dec, 2020
LOCATE() function in MySQL is used for finding the location of a substring in a string. It will return the location of the first occurrence of the substring in the string. If the substring is not present in the string then it will return 0. When searching for the location of a substring in a string it does not perform a case-sensitive search.
Syntax :
LOCATE(substring, string, start)
Parameters :
This method accepts three parameter.
substring –The string whose position is to be retrieved.
string –The string within which the position of the substring is to be retrieved.
start –The starting position for the search. It is optional .Position 1 is default.
Returns :The location of the first occurrence of the substring in the string.
Example-1 : Searching the String ‘f’ in the string ‘geeksforgeeks’ with the help of LOCATE Function.
SELECT LOCATE('f', 'geeksforgeeks') AS MatchLocation;
Output :
Example-2 : Searching the String ‘MYSQL’ in the string ‘Learning SQL is fun’ with the help of LOCATE Function.So, it will return 0.
SELECT LOCATE('MYSQL', 'Learning SQL is fun') AS MatchLocation;
Output :
Example-3 :Searching the String ‘g’ in the string ‘geeksforgeeks’ with the help of LOCATE Function starting from position 3.
SELECT LOCATE('g', 'geeksforgeeks', 3) AS MatchLocation;
Output :
Example-4 :LOCATE Function can also be used on column data. To demonstrate create a table named Student.
CREATE TABLE Student
(
Student_id INT AUTO_INCREMENT,  
Student_name VARCHAR(100) NOT NULL,
Roll INT NOT NULL,
Department VARCHAR(10) NOT NULL,
PRIMARY KEY(Student_id )
);
Inserting some data to the Student table :
INSERT INTO Student
(Student_name, Roll, Department )
VALUES
('Anik Biswas ', 10100, 'CSE'),
('Bina Mallick', 11000, 'ECE' ),
('Aniket Sharma', 12000, 'IT' ),
('Sayani Samanta', 13000, 'ME'  ),
('Riyanka Shah ', 14000, 'EE' ),
('Bipin Kohli', 15000, 'CE' );
So, the Student Table is as follows.
SELECT  * from Student ;
Now, we will find the first occurrence of string ‘a’ in the Student_name column with the help of LOCATE function.
SELECT *, LOCATE('a', Student_name ) AS FirstOccurrenceOfA  
FROM STUDENT;
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Redis - Strings

Redis strings commands are used for managing string values in Redis. Following is the syntax for using Redis string commands.
redis 127.0.0.1:6379> COMMAND KEY_NAME 

redis 127.0.0.1:6379> SET tutorialspoint redis 
OK 
redis 127.0.0.1:6379> GET tutorialspoint 
"redis" 

In the above example, SET and GET are the commands, while tutorialspoint is the key.
Following table lists some basic commands to manage strings in Redis.
This command sets the value at the specified key.
Gets the value of a key.
Gets a substring of the string stored at a key.
Sets the string value of a key and return its old value.
Returns the bit value at the offset in the string value stored at the key.
Gets the values of all the given keys
Sets or clears the bit at the offset in the string value stored at the key
Sets the value with the expiry of a key
Sets the value of a key, only if the key does not exist
Overwrites the part of a string at the key starting at the specified offset
Gets the length of the value stored in a key
Sets multiple keys to multiple values
Sets multiple keys to multiple values, only if none of the keys exist
Sets the value and expiration in milliseconds of a key
Increments the integer value of a key by one
Increments the integer value of a key by the given amount
Increments the float value of a key by the given amount
Decrements the integer value of a key by one
Decrements the integer value of a key by the given number
Appends a value to a key
Python & MySQL - Connect Database Example

Python MySQLdb provides MySQLdb.connect() function to open a database connection. This function takes multiple parameters and returns a connection object to do database operations.
db = MySQLdb.connect(host, username, passwd, dbName, port, socket);

host
Optional − The host name running the database server. If not specified, then the default value will be localhost:3306.
username
Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process.
passwd
Optional − The password of the user accessing the database. If not specified, then the default will be an empty password.
dbName
Optional − database name on which query is to be performed.
port
Optional − the port number to attempt to connect to the MySQL server..
socket
Optional − socket or named pipe that should be used.
There are several other properties as well. Refer MySQLdb for complete reference.
You can disconnect from the MySQL database anytime using another connection object function close().
db.close()

Try the following example to connect to a MySQL server −
Copy and paste the following example as mysql_example.py −
#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root@123")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
if data:
   print('Version available: ', data)
else:
   print('Version not retrieved.')

# disconnect from server
db.close()
Execute the mysql_example.py script using python and verify the output.
py mysql_example.py
Version available:  ('8.0.23',)
MongoDB – getIndexes() Method

05 Feb, 2021
In MongoDB, the getIndexes() method returns an array that contains a list of documents that identify and describe the existing indexes on the specified collection. It also includes hidden indexes as well. 
This method does not take any parameters.
The index information return by this method contains the keys and the options used to create an index.
In this method, the hidden index available starting from MongoDB 4.4. Only if the value is true.
Syntax:
db.Collection_name.getIndexes()
Return:
This method returns an array that contains a list of documents that identify and describe the existing indexes on the specified collection. It also includes hidden indexes as well.
Examples:
In the following examples, we are working with:
Database: gfg
Collection: student
Documents: Three documents contains name and the language in which the students are interested.
Return an array of documents that hold index information for the student collection:
db.student.getIndexes()
Create an index using createIndex() method:
db.student.createIndex({name:1, language:-1})
Here, we first create an index using createIndex() method.
After creating a new index we use greateIndex() method to find the index information for the student collection.
db.student.getIndexes()
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - sort() Method
MongoDB - FindOne() Method
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Regex
MongoDB - Compound Indexes
MongoDB updateMany() Method - db.Collection.updateMany()
MongoDB Cursor
Mongoose | update() Function
How to remove all white spaces from a String in Java?

07 Nov, 2018
Given a String with white spaces, the task is to remove all white spaces from a string using Java built-in methods.
Examples:
Input: str = "       Geeks     for    Geeks   "            
Output: GeeksforGeeks

Input:  str = "    A  Computer  Science   Portal"
Output: AComputerSciencePortal

To remove all white spaces from String, use replaceAll() method of String class with two arguments, i.e.
replaceAll("\\s", "");
where \\s is a single space in unicode
Program:
class BlankSpace {    public static void main(String[] args)    {        String str = "      Geeks     for    Geeks        ";               // Call the replaceAll() method        str = str.replaceAll("\\s", "");               System.out.println(str);    }}
GeeksforGeeks

Java-Strings
Java Programs
Strings
Java-Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Iterate through List in Java
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
mktime() function in C++ STL

20 Jul, 2021
The mktime() is an inbuilt C++ function which converts the local calendar time to the time since epoch and returns the value as an object of type time_t.
Syntax : 
time_t  mktime( struct tm  *time_ptr )
Parameters: The function accepts a mandatory parameter pointer time_ptr that points to a tm object structure that contains a calendar time which is to be converted. 
Return Value: The function returns two type of values as described below: 
It returns the time since epoch as an object of type time_t if the parameter passed is a success.
It returns -1 on failure.
Below program illustrates the mktime() function: 
C++
// C++ program to demonstrate the// mktime() function #include <bits/stdc++.h>using namespace std; int main(){    time_t tim;    tm* time_ptr;    char weekday[7][20] = { "Sunday",                            "Monday",                            "Tuesday",                            "Wednesday",                            "Thursday",                            "Friday",                            "Saturday" };     // Date    int year = 2018;    int month = 6;    int day = 18;     time(&tim);    time_ptr = localtime(&tim);     // tm_year is time since 1900    time_ptr->tm_year = year - 1900;     // Months calculated since January    time_ptr->tm_mon = month - 1;     // Day calculated in the month    time_ptr->tm_mday = day;     // time_ptr pointer to be pass    mktime(time_ptr);     cout << "The Day on 18th June 2018 was "         << weekday[time_ptr->tm_wday];     return 0;}
The Day on 18th June 2018 was Monday
manikarora059
CPP-Functions
CPP-Library
date-time-program
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
process.cpuUsage() Method in Node.js

The process.argv() method is used for getting the user and its cpu usage for the current running process. The data is returned in an object with the properties user and system. The values obtained are in microseconds,i.e.10^-6 seconds. The values returned may be greater than the actual elapsed time if multiple cores are performing work for the running process.
process.cpuUsage([previousValue])
The method only accepts a single parameter which is defined below −
previousValue – This is an optional parameter. This is the previous return value by calling the process.cpuUsage() method.
previousValue – This is an optional parameter. This is the previous return value by calling the process.cpuUsage() method.
Create a file with name – cpuUsage.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −
node cpuUsage.js
cpuUsage.js
 Live Demo
// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Getting the cpu usage details by calling the below method
const usage = process.cpuUsage();

// Printing the cpu usage values
console.log(usage);
admin@root:~/node/test$ node cpuUsage.js
{ user: 352914, system: 19826 }
Let's take a look at one more example.
 Live Demo
// Node.js program to demonstrate the use of process.argv

// Importing the process module
const process = require('process');

// Getting the cpu usage details by calling the below method
var usage = process.cpuUsage();
// Printing the cpu usage values
console.log("cpu usage before: ", usage);

// Printing the current time stamp
const now = Date.now();

// Looping to delay the process for 100 milliseconds
while (Date.now() - now < 100);

// After using the cpu for nearly 100ms
// calling the process.cpuUsage() method again...
usage = process.cpuUsage(usage);

// Printing the new cpu usage values
console.log("Cpu usage by this process: ", usage);
admin@root:~/node/test$ node cpuUsage.js
cpu usage before: { user: 357675, system: 32150 }
Cpu usage by this process: { user: 93760, system: 95 }
JavaScript Prompt Example

The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it enables you to interact with the user. The user needs to fill in the field and then click OK. This dialog box is displayed using a method called prompt()
Following is the code for showing prompt in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
   font-size: 18px;
   font-weight: 500;
   color: blueviolet;
}
</style>
</head>
<body>
<h1>JavaScript Prompt() method</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to get the prompt dialogue box</h3>
<script>
let resultEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
   let res = prompt("Are you sure");
   if (res === null) {
      resultEle.innerHTML = "You pressed cancel";
   } else {
      resultEle.innerHTML = "You entered " + res + " in the prompt box";
   }
});
</script>
</body>
</html>
On clicking on ‘CLICK HERE’ button and typing something in the promt box −
On clicking OK on the prompt box −
Sorting an associative array in ascending order - JavaScript

Suppose, we have an array of objects like this −
const people = [
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}  
];
We are required to write a JavaScript function that takes in one such array and sorts the array in place, according to the age property of each object in increasing order.
Therefore, the output should look something like this −
const output = [
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"},
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"}
];
Following is the complete code −
const people = [
   {"id":1, "name":"Andrew", "age":30, "gender":"m", "category":"G"},
   {"id":2, "name":"Brandon", "age":25, "gender":"m", "category":"G"},
   {"id":3, "name":"Christine", "age":20, "gender":"m", "category":"G"},
   {"id":4, "name":"Elena", "age":29, "gender":"W", "category":"M"}
];
const sorter = (a, b) => {
   return a.age - b.age;
};
const sortByAge = arr => {
   arr.sort(sorter);
};
sortByAge(people);
console.log(people);
This will produce the following output in console −
[
   { id: 3, name: 'Christine', age: 20, gender: 'm', category: 'G' },
   { id: 2, name: 'Brandon', age: 25, gender: 'm', category: 'G' },
   { id: 4, name: 'Elena', age: 29, gender: 'W', category: 'M' },
   { id: 1, name: 'Andrew', age: 30, gender: 'm', category: 'G' }
]
java.lang.reflect.Field.get() Method Example

The java.lang.reflect.Field.get(Object obj) method returns the value of the field represented by this Field, on the specified object. The value is automatically wrapped in an object if it has a primitive type.
Following is the declaration for java.lang.reflect.Field.get(Object obj) method.
public Object get(Object obj)
   throws IllegalArgumentException, IllegalAccessException

obj − object from which the represented field's value is to be extracted.
the value of the represented field in object obj; primitive values are wrapped in an appropriate object before being returned.
IllegalAccessException − if this Field object is enforcing Java language access control and the underlying field is inaccessible.
IllegalAccessException − if this Field object is enforcing Java language access control and the underlying field is inaccessible.
IllegalArgumentException − if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).
IllegalArgumentException − if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof).
NullPointerException − if the specified object is null and the field is an instance field.
NullPointerException − if the specified object is null and the field is an instance field.
ExceptionInInitializerError − if the initialization provoked by this method fails.
ExceptionInInitializerError − if the initialization provoked by this method fails.
The following example shows the usage of java.lang.reflect.Field.get(Object obj) method.
package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Field;

public class FieldDemo {

   public static void main(String[] args) throws NoSuchFieldException, 
      SecurityException, IllegalArgumentException, IllegalAccessException {
          
      SampleClass sampleObject = new SampleClass();
      sampleObject.setSampleField("data");
      
      Field field = SampleClass.class.getField("sampleField");
      System.out.println(field.get(sampleObject));
   }
}

@CustomAnnotation(name = "SampleClass",  value = "Sample Class Annotation")
class SampleClass {

   @CustomAnnotation(name="sampleClassField",  value = "Sample Field Annotation")
   public String sampleField;
    
   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   }
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
   public String name();
   public String value();
}
Let us compile and run the above program, this will produce the following result −
data

 Print
 Add Notes
 Bookmark this page
How to split last n digits of each value in the array with JavaScript?

We have an array of literals like this −
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223, 20191224, 20191225];
We are required to write a JavaScript function that takes in this array and a number n and if the
corresponding element contains more than or equal to n characters, then the new element
should contain only the last n characters otherwise the element should be left as it is.
Let's write the code for this function −
const arr = ["", 20191219, 20191220, 20191221, 20191222, 20191223,
20191224, 20191225];
const splitElement = (arr, num) => {
   return arr.map(el => {
      if(String(el).length <= num){
         return el;
      };
      const part = String(el).substr(String(el).length - num, num);
      return +part || part;
   });
};
console.log(splitElement(arr, 2));
console.log(splitElement(arr, 1));
console.log(splitElement(arr, 4));
The output in the console will be −
[
   '', 19, 20, 21,
   22, 23, 24, 25
]
[
   '', 9, '0', 1,
   2, 3, 4, 5
]
[
   '', 1219, 1220,
   1221, 1222, 1223,
   1224, 1225
]
Python - WebForm Submission

Often the interaction with a webpage needs some data to be submitted to the server through the forms present in the html page. These webforms are typically used 
for processes like signing up for a new account or supplying some information like name or roll number to retrieve the result of an examination. The requests module
handles this gracefully using the POST method with the required parameters.
In the below example we use the sign up form of a website by supplying the userid and password value. After the submission of the values we print the response.
import requests

ID_USERNAME = 'signup-user-name'
ID_PASSWORD = 'signup-user-password'
USERNAME = 'username'
PASSWORD = 'yourpassword'
SIGNUP_URL = 'http://codepad.org/login'
def submit_form():
    """Submit a form"""
    payload = {ID_USERNAME : USERNAME, ID_PASSWORD : PASSWORD,}

    resp = requests.get(SIGNUP_URL)
    print "Response to GET request: %s" %resp.content

    resp = requests.post(SIGNUP_URL, payload)
    print "Headers from a POST request response: %s" %resp.headers
#print "HTML Response: %s" %resp.read()

if __name__ == '__main__':
    submit_form()
When we run the above program, we get the following output −
Response to GET request: <!DOCTYPE html>
<html>

<head>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Expires" CONTENT="-1">

    <title>Login - codepad</title>

    

    <link href="/main.css" media="screen" rel="stylesheet" type="text/css" />
    <style type="text/css">
    

    </style>
    <script src='https://www.google.com/recaptcha/api.js'></script>
    <script>
       function onRecaptcha(token) {
         document.getElementById("editor-form").submit();
       }
    </script>
</head>


    <body >

	.....................
	.....................



    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Count the number of occurrences of a string in a VARCHAR field in MySQL?

To count the number of occurrences of a string in a VARCHAR, we can use the logic of subtraction with length. First, we will create a table with the help of create command.
mysql> create table StringOccurrenceDemo
   -> (
   -> Cases varchar(100),
   -> StringValue varchar(500)
   -> );
Query OK, 0 rows affected (0.56 sec) 
After executing the above table, we will insert records into the table. The query is as follows −
mysql> insert into StringOccurrenceDemo values('First','This is MySQL Demo and MySQL is an open source RDBMS');
Query OK, 1 row affected (0.07 sec)

mysql> insert into StringOccurrenceDemo values('Second','There is no');
Query OK, 1 row affected (0.20 sec)

mysql> insert into StringOccurrenceDemo values('Third','There is MySQL,Hi MySQL,Hello MySQL');
Query OK, 1 row affected (0.17 sec)
Display all records with the help of select statement.
mysql> select *From StringOccurrenceDemo;
The following is the output.
+--------+------------------------------------------------------+
| Cases  | StringValue                                          |
+--------+------------------------------------------------------+
| First  | This is MySQL Demo and MySQL is an open source RDBMS |
| Second | There is no                                          |
| Third  | There is MySQL,Hi MySQL,Hello MySQL                  |
+--------+------------------------------------------------------+
3 rows in set (0.00 sec)

The following is the query to count the occurrences of string “MySQL”. The result will get displayed in the  column ‘NumberOfOccurrenceOfMySQL’
mysql> SELECT Cases,StringValue,
   -> ROUND (
   -> (
   -> LENGTH(StringValue)- LENGTH( REPLACE (StringValue, "MySQL", "") )
   -> ) / LENGTH("MySQL")
   ->  ) AS NumberOfOccurrenceOfMySQL
   -> from StringOccurrenceDemo;
Here is the output.
+--------+------------------------------------------------------+---------------------------+
| Cases  | StringValue                                          |  NumberOfOccurrenceOfMySQL|
+--------+------------------------------------------------------+---------------------------+
| First  | This is MySQL Demo and MySQL is an open source RDBMS |                         2 |
| Second | There is                                             |                         0 |
| Third  | There is MySQL,Hi MySQL,Hello MySQL                  |                         3 |
+--------+------------------------------------------------------+---------------------------+
3 rows in set (0.05 sec)

The above output shows that we have found the count for occurrences of string ‘MySQL’.
Microsoft Azure - Find Orphaned Disks - GeeksforGeeks

16 Dec, 2021
In this article, you will see that how to find the unattached disks also known as orphaned disks in Azure. The main objective or purpose of deleting the orphaned resources is to save the cost of unused resources. When you delete a VM in Azure, the disks will not be deleted automatically and they will be left as orphaned disks.
Follow the below steps to find orphaned disks in Azure:
Step 1: Login to Azure Portal.
Step 2: Go to Azure Resource Graph Explorer >> select the Resource Graph Explorer
Step 3: Select Scope >> Subscription >> Select your subscriptions (You can select single or multiple subscriptions of your choice at once)
For Example: Here, I have selected 8 Subscriptions from Scope.
Step 4: Paste the below query in the query box and click on the Run query to get the list/report of unattached disks.
Example:
Resources
| where type has "microsoft.compute/disks"
| extend diskState = tostring(properties.diskState)
| where  diskState == 'Unattached' or managedBy == ""
| project name, diskState, managedBy, subscriptionId, resourceGroup, location
Output:
Example 1: If you have selected multiple subscriptions in scope then you will be getting many results >> In this case, you can add where subscriptionId has “_SubscriptionId_Value” to get the results in a particular select subscription.
Resources
| where type has "microsoft.compute/disks"
| extend diskState = tostring(properties.diskState)
| where  diskState == 'Unattached' or managedBy == ""
| where subscriptionId has ""  
| project name, diskState, managedBy, subscriptionId, resourceGroup, location
Output:
Example 2: If you want results of tagged values to that orphaned disks then you can use the following kql command.
Resources
| where type has "microsoft.compute/disks"
| extend diskState = tostring(properties.diskState)
| where  diskState == 'Unattached' or managedBy == ""
| where subscriptionId == "" 
| where tags.Environment == "Production" // "Dev", "Prod", "Test",...etc.
| project name, diskState, managedBy, subscriptionId, resourceGroup, location, tags
Output:
That’s it you are done.
azure-virtual-machine
Cloud-Computing
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Microsoft Azure - Azure VM Disk Space in Percentage using Azure KQL
Microsoft Azure - Rebooting an Application Gateway
Microsoft Azure - Installation of Service Bus Explorer
Microsoft Azure - Handling Orphaned NSGs
Microsoft Azure - Check Resource Owner in Azure using KQL
Microsoft Azure - Query System Event Log Data Using Azure KQL
Microsoft Azure - Get Azure VM Properties using Azure PowerShell
Microsoft Azure - KQL Query to Get the VM Computer Properties
Microsoft Azure - Graph Query to Get Properties of Azure VM Resource
Microsoft Azure - Mount Azure Storage in Container App In App Service
How to parse JSON input using Python?

You can parse JSON files using the JSON module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −
{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
         {"value": "New", "onclick": "CreateNewDoc()"},
         {"value": "Open", "onclick": "OpenDoc()"},
         {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}
You can load it in your python program and loop over its keys in the following way −
import json
f = open('data.json')
data = json.load(f)
f.close()
# Now you can use data as a normal dict −
for (k, v) in data.items():
   print("Key: " + k)
   print("Value: " + str(v))
This will give the output −
Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
How to use custom headers in the PowerShell output table?

If you want the specific properties in PowerShell, you need to use the Select-Object (Alias − Select) as a pipeline.
In the below example, we will retrieve the specific properties of the Spooler service.
Get-Service Spooler | Select Name, DisplayName, Starttype, Status
Name       DisplayName    StartType    Status
----       -----------    ---------    ------
Spooler    Print Spooler  Automatic    Running
Now we will customize the header by renaming the “Name” property to the “Alias Name” by the Name and the Expression syntax inside the Select-object.
Get-
Service Spooler | Select @{N='Alias Name';E={$_.Name}}, DisplayName, Starttype, Status
You can also use other commands as well inside the expression.
Get-ComputerInfo | Select Csname, WindowsProductName, Csworkgroup
CsName             WindowsProductName       CsWorkgroup
------             ------------------       -----------
DESKTOP-9435KM9    Windows 10 Pro           WORKGROUP
In the above example, we need to add property “Computer Uptime” and for that, we need to add new command to the existing command using Expression syntax.
Get-
ComputerInfo | Select Csname, WindowsProductName, Csworkgroup, @{N='Days Uptime';E={((Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime).Days}}
CsName             WindowsProductName             CsWorkgroup       Days Uptime
------             ------------------             -----------       -----------
DESKTOP-9435KM9    Windows 10 Pro                 WORKGROUP             1
Finding the longest string in an array in JavaScript

We are required to write a JavaScript function that takes in an array of strings. Our function should iterate through the array and find and return the longest string from the array.
Our function should do this without changing the content of the input array.
The code for this will be −
const arr = ["aaaa", "aa", "aa", "aaaaa", "acc", "aaaaaaaa"];
const findLargest = (arr = []) => {
   if(!arr?.length){
      return '';
   };
   let res = '';
   res = arr.reduce((acc, val) => {
      return acc.length >= val.length ? acc : val;
   });
   return res;
};
console.log(findLargest(arr));
And the output in the console will be −
aaaaaaaa
How to create an ordinal variable in R?

An ordinal variable is a type of categorical variable which has natural ordering. For example, an ordinal variable could be level of salary something defined with Low, Medium, and High categories here we have three categories but there exists a natural order in these categories as low salary is always less than the medium, medium is always less than high. To create an ordinal variable in R, we can use the order argument along with factor function while creating the variable. Follow the below steps to create an ordinal variable in R −
Create a categorical column with factor function where order argument is set to TRUE
Look at the structure of the data frame
Let's create a data frame as shown below −
 Live Demo
x<-
factor(sample(c("Low","Medium","High"),20,replace=TRUE),order=TRUE,levels=c("Lo
w","Medium","High"))
df<-data.frame(x)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
    x
1 Medium
2 Medium
3 Low
4 Medium
5 Low
6 Medium
7 High
8 Low
9 Medium
10 High
11 Medium
12 High
13 Medium
14 Medium
15 Low
16 Low
17 Low
18 Medium
19 Low
20 Medium
Use str function to check the structure of data frame df −
 Live Demo
x<-
factor(sample(c("Low","Medium","High"),20,replace=TRUE),order=TRUE,levels=c("Lo
w","Medium","High"))
df<-data.frame(x)
str(df)
'data.frame': 20 obs. of 1 variable:
$ x: Ord.factor w/ 3 levels "Low"<"Medium"<..: 2 2 1 2 1 2 3 1 2 3 ...
Here we can see that x is an ordered factor which means it is an ordinal variable.
Lodash | _.clone() Method

02 Feb, 2022
The _.clone() method is used to create a shallow copy of the value. This method supports cloning arrays, array buffers, booleans, date objects, maps, numbers, Object objects, regexes, sets, strings, symbols, and typed arrays. It is loosely based on the structured clone algorithm.
Syntax:
_.clone( value )
Parameters: This method accepts single parameter as mentioned above and described below:
value: This parameter holds the value that need to be clone.
Return Value: This method returns the shallow copy of value.
Example 1: Cloning Simple Object
javascript
const _ = require('lodash');  var obj = {    x: 23};  // Shallow copyvar shallowCopy = _.clone(obj);  console.log('Comparing original with'    + ' shallow ', obj === shallowCopy);  obj.x = 10; // Changing original value  console.log('After changing original value');  console.log("Original value ", obj);  console.log("Shallow Copy value ", shallowCopy);
Here, const _ = require('lodash') is used to import the lodash library into the file.
Output:
Comparing original with shallow  false
After changing original value
Original value  { x: 10 }
Shallow Copy value  { x: 23 }
Example 2: Cloning complex object
javascript
const _ = require('lodash');   var obj = [{  x: 1 }, {y: 2}];  // Shallow copyvar shallowCopy = _.clone(obj);   console.log('Comparing original with shallow ',            obj[0] === shallowCopy[0]);   // Changing original valueobj[0].x = 10;   // Values after changing original valueconsole.log("After changing original value");   console.log("Original value ", obj);   console.log("Shallow Copy value ", shallowCopy);
Output:
Comparing original with shallow  true
After changing original value
Original value  [ { x: 10 }, { y: 2 } ]
Shallow Copy value  [ { x: 10 }, { y: 2 } ]
So, here we have seen that after changing original value the shallow copy value also changed because _.clone() doesn’t copy deeply it just passed the reference.
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Reference: https://lodash.com/docs/4.17.15#clone
sagar0719kumar
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
What is DNS TXT Record?

19 Oct, 2021
Domain Name System (DNS) plays an essential role in maintaining the whole Internet infrastructure, so its failure makes the system unreachable for the user. DNS connects data with various domain names for each participating entity. This application or model was developed using Microsoft visual basic 6.0 and the access databases. DNS maintains a directory of domain names (just like our phonebook) and translates them to IPs (Internet Protocol) addresses. This makes the domain names easy for people to remember so that they can easily access websites (GOOGLE, YOUTUBE, GMAIL) on computers or machines rather than accessing the websites by searching the IP addresses.
TXT Records :A TXT record is used to provide the capacity of the domain administrator to connect the text with a zone. The text can be either human or machine-readable. One can add these records to their respective domain setting. This record permits area heads to insert any text content into DNS records. These records are utilized for different purposes. 
One model is ownership validation: To demonstrate you own the area, a supplier might expect you to add a TXT record with a specific worth to your space and email security. One domain can have many TXT records. TXT records contain a large amount of text up to 255 characters per string with special characters and spaces.
Format of DNS TXT Record :
 Record: geeksforgeeks.com  /  type: TXT /  value: "attribute=value"  / TTL(Time to Live)
To prove that you are the actual owner of that particular domain name. Numerous suppliers, for example, Google, Office 365, and so forth, regularly require an uncommon verification code through TXT record to be included in DNS (Domain Name System) zone.
TXT records can be checked using $ dig txt your-domain.com or $ nslookup -type=txt your-domain.com
Common uses of DNS TXT Records :
Site Verification Records –This record demonstrates responsibility for domain and can be utilized to relate administrations, for example, Microsoft 365 and G-Suite to a particular area.
DKIM records –This record stores significant data utilized in the approval of email on the way. Kindly note that business email doesn’t uphold giving a private key expected to DKIM records.
SPF record –This record is utilized to demonstrate to mail trades which hosts are approved to send letters for a domain. This diminishes spam by letting getting mail servers check a message’s sending address against the area’s SPF record.
DMARC records –Domain-based Message Authentication Reporting and Conformance records improve phishing and spoofing email attacks.
Picked
TrueGeek-2021
Computer Networks
TrueGeek
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design Issues of Distributed System
What is P2P(Peer-to-peer process) ?
Secure Socket Layer (SSL)
IP security (IPSec)
IPSec Architecture
How to Convert Char to String in Java?
Types of Network Firewall
How to redirect to another page in ReactJS ?
Basics of API Testing Using Postman
Monotonic Reasoning vs Non-Monotonic Reasoning