code-rag-bench/online-tutorials huggingface dataset:
Python regex | Check whether the input is Floating point number or not

29 Dec, 2020
Prerequisite: Regular expression in Python
Given an input, write a Python program to check whether the given Input is Floating point number or not.
Examples:
Input:  1.20
Output: Floating point number

Input: -2.356
Output: Floating point number

Input: 0.2
Output: Floating point number

Input: -3
Output: Not a Floating point number

In this program, we are using search() method of re module.
re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data.
Let’s see the Python program for this :
# Python program to check input is# Floating point number or not  # import re module  # re module provides support# for regular expressionsimport re  # Make a regular expression for# identifying Floating point number regex = '[+-]?[0-9]+\.[0-9]+'  # Define a function to# check Floating point number def check(floatnum):        # pass the regular expression     # and the string in search() method    if(re.search(regex, floatnum)):         print("Floating point number")               else:         print("Not a Floating point number")         # Driver Code if __name__ == '__main__' :           # Enter the floating point number    floatnum = "1.20"          # calling run function     check(floatnum)      floatnum = "-2.356"    check(floatnum)      floatnum = "0.2"    check(floatnum)      floatnum = "-3"    check(floatnum)
Floating point number
Floating point number
Floating point number
Not a Floating point number

Python Regex-programs
python-regex
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
PHP | urlencode() Function

31 Jul, 2021
The urlencode() function is an inbuilt function in PHP which is used to encode the url. This function returns a string which consist all non-alphanumeric characters except -_. and replace by the percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs.
Syntax:
string urlencode( $input )
Parameters: This function accepts single parameter $input which is used to hold the url to be encoded.
Return Value: This function returns an encoded string on success.
Below programs illustrate the urlencode() function in PHP:
Program 1:
<?php  // PHP program to illustrate urlencode functionecho urlencode("https://geeksforgeeks.org/") . "\n";  ?>
https%3A%2F%2Fgeeksforgeeks.org%2F

Program 2 :
<?php  // PHP program to illustrate urlencode functionecho urlencode("https://ide.geeksforgeeks.org/") . "\n";echo urlencode("https://write.geeksforgeeks.org/") . "\n";echo urlencode("https://practice.geeksforgeeks.org/") . "\n";echo urlencode("https://geeksforgeeks.org/") . "\n";  ?>
https%3A%2F%2Fide.geeksforgeeks.org%2F
https%3A%2F%2Fwrite.geeksforgeeks.org%2F
https%3A%2F%2Fpractice.geeksforgeeks.org%2F
https%3A%2F%2Fgeeksforgeeks.org%2F

Reference: http://php.net/manual/en/function.urlencode.php
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
julthep
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert an object to associative array in PHP

To convert an object to associative array in PHP, the code is as follows−
 Live Demo
<?php
   class department {
      public function __construct($deptname, $deptzone) {
         $this->deptname = $deptname;
         $this->deptzone = $deptzone;
      }
   }
   $myObj = new department("Marketing", "South");
   echo "Before conversion:"."\n";
   var_dump($myObj);
   $myArray = json_decode(json_encode($myObj), true);
   echo "After conversion:"."\n";
   var_dump($myArray);
?>
This will produce the following output−
Before conversion:
object(department)#1 (2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}
After conversion:
array(2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}
Let us now see another example −
 Live Demo
<?php
   class department {
      public function __construct($deptname, $deptzone) {
         $this->deptname = $deptname;
         $this->deptzone = $deptzone;
      }
   }
   $myObj = new department("Marketing", "South");
   echo "Before conversion:"."\n";
   var_dump($myObj);
   $arr = (array)$myObj;
   echo "After conversion:"."\n";
   var_dump($arr);
?>
This will produce the following output−
Before conversion:
object(department)#1 (2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}
After conversion:
array(2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}
Get database data size in MongoDB?

To get the database data size in MongoDB, you can use stats() method. The syntax is as follows −
db.stats();
Let us use the database with the name ‘test’.
Now, check the current database with the help of the following query −
> db;
The following is the output −
test
Here is the query to get database data size in MongoDB −
> db.stats()
The following is the output −
{
   "db" : "test",
   "collections" : 114,
   "views" : 0,
   "objects" : 391,
   "avgObjSize" : 83.0076726342711,
   "dataSize" : 32456,
   "storageSize" : 3211264,
   "numExtents" : 0,
   "indexes" : 120,
   "indexSize" : 2494464,
   "fsUsedSize" : 126172377088,
   "fsTotalSize" : 199229435904,
   "ok" : 1
}
Switch to the database ‘sample’. The query is as follows −
> use sample;
switched to db sample
Let us check the currently used database name using db command. The query is as follows −
> db;
The following is the output −
Sample
Let us check the database ‘sample’ data size in MongoDB. The query is as follows −
> db.stats();
The following is the output −
{
   "db" : "sample",
   "collections" : 25,
   "views" : 0,
   "objects" : 67,
   "avgObjSize" : 85.32835820895522,
   "dataSize" : 5717,
   "storageSize" : 626688,
   "numExtents" : 0,
   "indexes" : 24,
   "indexSize" : 610304,
   "fsUsedSize" : 126173016064,
   "fsTotalSize" : 199229435904,
   "ok" : 1
}
Solidity - Enums

Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums.
With the use of enums it is possible to reduce the number of bugs in your code.
For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large.
Try the following code to understand how the enum works in Solidity.
pragma solidity ^0.5.0;

contract test {
   enum FreshJuiceSize{ SMALL, MEDIUM, LARGE }
   FreshJuiceSize choice;
   FreshJuiceSize constant defaultChoice = FreshJuiceSize.MEDIUM;

   function setLarge() public {
      choice = FreshJuiceSize.LARGE;
   }
   function getChoice() public view returns (FreshJuiceSize) {
      return choice;
   }
   function getDefaultChoice() public pure returns (uint) {
      return uint(defaultChoice);
   }
}
Run the above program using steps provided in Solidity First Application chapter.
First Click setLarge Button to set the value as LARGE then click getChoice to get the selected choice.
uint8: 2

Click getDefaultChoice Button to get the default choice.
Python | Sort list of lists by the size of sublists

05 Apr, 2022
Given a list of lists, the task is to sort a list on the basis of size of sublists. Let’s discuss a few methods to do the same. Method #1: Using sort 
Python3
# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],                [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of size of listini_list.sort(key = len) # printing final resultprint("final list", str(ini_list))
  Method #2: Using lambda 
Python3
# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],                [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of size of listini_list.sort(key = lambda x:len(x)) # printing final resultprint("final list", str(ini_list))
  Method #3: Using sorted 
Python3
# Python code to demonstrate# sort list of list# on the basis of size of sublist ini_list = [[1, 2, 3], [1, 2], [1, 2, 3, 4],                [1, 2, 3, 4, 5], [2, 4, 6]] # printing initial ini_listprint ("initial list", str(ini_list)) # sorting on basis of size of listresult = sorted(ini_list, key = len) # printing final resultprint("final list", str(result))
simmytarika5
Python list-programs
python-list
Python-list-of-lists
Python-sort
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python List Comprehension | Segregate 0’s and 1’s in an array list

07 Jan, 2018
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array.
Examples:
Input  :  arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 
Output :  [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 

We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python using List Comprehension. Traverse given list and separate out two different lists, one contains all 0’s and another one contains all 1’s. Now concatenate both lists together.
# Function to Segregate 0's and 1's in an array list  def segregate(arr):    res = ([x for x in arr if x==0] + [x for x in arr if x==1])    print(res)  # Driver programif __name__ == "__main__":    arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0]     segregate(arr)
Output:
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 

python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Introduction To PYTHON
Can private methods of a class be accessed from outside of a class in Java?

You can access the private methods of a class using java reflection package.
Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.
Step2 − Set the method accessible by passing value true to the setAccessible() method.
Step3 − Finally, invoke the method using the invoke() method.
import java.lang.reflect.Method;

public class DemoTest {
   private void sampleMethod() {
      System.out.println("hello");
   }
}

public class SampleTest {
   public static void main(String args[]) throws Exception {
      Class c = Class.forName("DemoTest");
      Object obj = c.newInstance();
      Method method = c.getDeclaredMethod("sampleMethod", null);
      method.setAccessible(true);
      method.invoke(obj, null);
   }
}
Shell Program to Calculate the Factorial of a Number

01 Sep, 2021
Here we are going to see to calculate the factorial of a number. Factorial of a non-negative integer is the multiplication of all integers smaller than or equal to n. 
For example factorial of 5 is 5*4*3*2*1 which is 120.
Factorial can be calculated using the following recursive formula.
Below is  implementation of factorial:
#!/bin/bash
# Recursive factorial function

factorial()
{
    product=$1
           
    # Defining a function to calculate factorial using recursion
    if((product <= 2)); then
        echo $product
    else
        f=$((product -1))
        
# Recursive call

f=$(factorial $f)
f=$((f*product))
echo $f
fi
}

# main program
# reading the input from user
echo "Enter the number:"   
read num

# defining a special case for 0! = 1
if((num == 0)); then   
echo 1
else
#calling the function
factorial $num
fi
Output:
Enter the number
5
120

Enter the number
3
24

Enter the number
6
720
Approach:
Get a number
Use for loop to compute the factorial by using the below formula
fact(n) = n * n-1 * n-2 * ...
Display the result.
Below is the Implementation using for loop:
# shell script for factorial of a number
# factorial using for loop

echo "Enter a number"

# Read the number
read num                     

fact=1                    

for((i=2;i<=num;i++))
{
  fact=$((fact * i)) 
}

echo $fact
Output:
Enter a number
5
120

Enter a number
7
5040

Enter a number
4
24
Get a number
Use do-while loop to compute the factorial by using the below formula
fact(n) = n * n-1 * n-2 * .. 1
Display the result.
Below is the Implementation using a while loop.
# shell script for factorial of a number
# factorial using while loop

echo "Enter a number"

# Read the number
read num                
fact=1

# -gt is used for '>' Greater than sign
while [ $num -gt 1 ]  
do
  fact=$((fact * num))  
  num=$((num - 1))     
done

# Printing the value of the factorial
echo $fact            
Output:
Enter a number
10
3628800

Enter a number
2
2

Enter a number
9
362880
meetgor
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
Using WaitGroup in Golang

03 Jun, 2020
Go routines are a great selling point for golang, making it a choice of a lots of developers out there. In this post we will see a common problem with these goroutines and try to solve it.
Let’s see a simple code snippet illustrating this problem,
Go
package main  import "fmt"  func runner1() {    fmt.Print("\nI am first runner")}  func runner2() {    fmt.Print("\nI am second runner")}  func execute() {    go runner1()    go runner2()  }  func main() {        // Launching both the runners    execute()}
As you just saw there was nothing in the output, this because as soon as you launch both the goroutines, your main function just got terminated. And every program in Golang executes until main function is not terminated. So, what can we do with this problem
1. We can wait for some time after launching the runners, for this purpose we will use “time” packages function “Sleep” which pauses the execution of function for given duration,
Go
package main  import (    "fmt"    "time")  func runner1() {    fmt.Print("\nI am first runner")}  func runner2() {    fmt.Print("\nI am second runner")}  func execute() {    go runner1()    go runner2()  }  func main() {      // Launching both the runners    execute()    time.Sleep(time.Second)}
 
Output:
I am second runner
I am first runner

We just solve the problem, after launching our runners we wait for a second, so our main function was sleeping(blocked) for 1 sec. In that duration all of the go routines were executed successfully. But Golang is a fast language, It doesn’t take 1 sec to just print 2 strings.
The problem is that, our executors executes in bit amount of time so we unnecessarily  blocking the program for 1 sec. In this example it doesn’t seems to be a critical problem but if you making a production grade server who is going to serve 1000’s of request concurrently this will be a big problem.
2. Let’s use another Golang’s standard library primitive “sync.WaitGroup“. WaitGroup is actually a type of counter which blocks the execution of function (or might say A goroutine) until its internal counter become 0.
WaitGroup exports 3 methods.
Note: WaitGroup is concurrency safe, so its safe to pass pointer to it as argument for Groutines.
Go
package main  import (    "fmt"    "sync")  func runner1(wg *sync.WaitGroup) {    defer wg.Done() // This decreases counter by 1    fmt.Print("\nI am first runner")  }  func runner2(wg *sync.WaitGroup) {    defer wg.Done()    fmt.Print("\nI am second runner")}  func execute() {    wg := new(sync.WaitGroup)    wg.Add(2)      // We are increasing the counter by 2    // because we have 2 goroutines    go runner1(wg)    go runner2(wg)      // This Blocks the execution    // until its counter become 0    wg.Wait()}  func main() {    // Launching both the runners    execute()}
 
Output:
I am second runner
I am first runner
The output is same but we out program doesn’t block for 1 sec . Pattern, we showed you above is a common practice in writing concurrent code in Golang.
Golang-Concurrency
Articles
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Equal Tree Partition in C++

Suppose we have a binary tree with n nodes, our task is to check whether it's possible to partition the tree to two trees which have the equal sum of values after deleting exactly one edge on the original tree.
So, if the input is like
then the output will be true.
To solve this, we will follow these steps −
To solve this, we will follow these steps −
Define one stack st
Define one stack st
Define a function solve(), this will take node,
Define a function solve(), this will take node,
if node is null, then −return 0
if node is null, then −
return 0
return 0
leftSum := solve(left of node)
leftSum := solve(left of node)
rightSum := solve(right of node)
rightSum := solve(right of node)
curr := val + leftSum + rightSum of node
curr := val + leftSum + rightSum of node
insert curr into st
insert curr into st
return curr
return curr
From the main method do the following −
From the main method do the following −
solve(root)
solve(root)
totalSum := top element of st
totalSum := top element of st
delete element from st
delete element from st
while (not st is empty), do −x := top element of stdelete element from sty := totalSum - xif x is same as y, then −return true
while (not st is empty), do −
x := top element of st
x := top element of st
delete element from st
delete element from st
y := totalSum - x
y := totalSum - x
if x is same as y, then −return true
if x is same as y, then −
return true
return true
return false
return false
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
   }
};
class Solution {
public:
   stack <int> st;
   int solve(TreeNode* node){
      if (!node)
         return 0;
      int leftSum = solve(node->left);
      int rightSum = solve(node->right);
      int curr = node->val + leftSum + rightSum;
      st.push(curr);
      return curr;
   }
   bool checkEqualTree(TreeNode* root) {
      solve(root);
      int totalSum = st.top();
      st.pop();
      while (!st.empty()) {
         int x = st.top();
         st.pop();
         int y = totalSum - x;
         if (x == y)
            return true;
      }
      return false;
   }
};
main(){
   Solution ob;
   TreeNode *root = new TreeNode(5);
   root->left = new TreeNode(10);
   root->right = new TreeNode(10);
   root->right->left = new TreeNode(2);
   root->right->right = new TreeNode(3);
   cout<<(ob.checkEqualTree(root));
}
TreeNode *root = new TreeNode(5);
root->left = new TreeNode(10);
root->right = new TreeNode(10);
root->right->left = new TreeNode(2);
root->right->right = new TreeNode(3);
1
How to set a background Image With React Inline Styles ? - GeeksforGeeks

22 Dec, 2020
A React project is created using create-react-app command and the task is to set a background image using react inline styles. There are three approaches that are discussed below:
Approach 1: Set background image using external URL: If the image located somewhere online, then the background image of the element can be set like this:
Filename: App.js
Javascript
import React from "react";  const App = () => {  return (    <div style={{      backgroundImage: 'url("https://media.geeksforgeeks.org/'+      'wp-content/uploads/20201221222410/download3.png")',      height: "300px", backgroundRepeat: "no-repeat"    }}>      <h1> HELLO </h1>    </div>  );};  export default App;
Approach 2: Set background image using the Absolute URL method: If you put your image, for example, background.jpg file inside the public/ folder, you can include the absolute URL by using the PUBLIC_URL environment variable.
Filename: App.js
Javascript
import React from "react";  const App = () => {  return (    <div style={{      backgroundImage: `url(${process.env.PUBLIC_URL          + "/background.jpg"})`,      height: "300px", backgroundRepeat: "no-repeat"    }} >      <h1>Hello</h1>    </div>  );};  export default App;
Approach 3: Set background image using the Relative URL method: If you put your image, for example, background.jpg file inside the public/ folder in the react app, you can access it at <your host address>/background.jpg. 
You can then assign the URL relative to your host address to set the background image like this:
Filename: App.js
Javascript
import React from "react";  const App = () => {  return (    <div style={{      backgroundImage: "url(/background.jpg)",      height: "300px",      backgroundRepeat: "no-repeat"    }} >      <h1>Hello</h1>    </div>  );};  export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: 
Picked
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Python Pillow - Writing Text on Image

You can write text on images by passing the location of the text, the text itself and the color of the text. We can pass multiple other parameters to this method.
from PIL import Image, ImageDraw

img = Image.open(beach1.jpg')
d1 = ImageDraw.Draw(img)
d1.text((28, 36), "Hello, TutorialsPoint!", fill=(255, 0, 0))
img.show()
img.save("images/image_text.jpg")
If you save the above program as Example.py and execute, it will add the given text on it, and displays it using the standard PNG display utility, as follows −
There are numerous ways to select the font used for writing on the image. We can either load fonts directly from the system by passing the full path to the function, or we can use the ImageFont to load a TrueType font.
from PIL import Image, ImageDraw, ImageFont

img = Image.open('images/logo.jpg')
d1 = ImageDraw.Draw(img)
myFont = ImageFont.truetype('E:/PythonPillow/Fonts/FreeMono.ttf', 40)
d1.text((0, 0), "Sample text", font=myFont, fill =(255, 0, 0))
img.show()
img.save("images/image_text.jpg")

    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
Instant ofEpochMilli() method in Java with Examples - GeeksforGeeks

28 Nov, 2018
The ofEpochMilli() method of Instant class helps to get an Instant using milliseconds passed as parameter from the epoch of 1970-01-01T00:00:00Z. This returned milliseconds is used to get the different time units like seconds, etc by conversion.
Syntax:
public static Instant 
    ofEpochMilli(long epochMilli)
Parameters: This method accepts one parameter epochMilli is value of milliseconds from 1970-01-01T00:00:00Z.
Returns: This method returns Instant as the time from the Epoch as milliseconds.
Exception: This method throws DateTimeException if the result exceeds the maximum or minimum instant.
Below programs illustrate the ofEpochMilli() method:
Program 1:
// Java program to demonstrate// Instant.ofEpochMilli() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a long variable for milliseconds        long milliseconds            = 999999000;          // get Instant using ofEpochMilli() method        Instant instant            = Instant.ofEpochMilli(milliseconds);          // print result        System.out.println("Instant: "                           + instant);    }}
Instant: 1970-01-12T13:46:39Z

Program 2:
// Java program to demonstrate// Instant.ofEpochMilli() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // get Instant using ofEpochMilli() method        // passed epoch millisecond is 73264271044L        Instant instant            = Instant.ofEpochMilli(73264271044L);          // print result        System.out.println("Instant: "                           + instant);    }}
Instant: 1972-04-27T23:11:11.044Z

References: https://docs.oracle.com/javase/10/docs/api/java/time/Instant.html#ofEpochMilli(long)
Java-Functions
Java-Instant
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Singleton Class in Java
LinkedList in Java
Getting sine and hyperbolic sine in Julia - sin(), sinh() and sind() Methods - GeeksforGeeks

26 Mar, 2020
The sin() is an inbuilt function in julia which is used to calculate sine of the specified radian values.
Syntax: sin(x)
Parameters:
x: Specified radian values.
Returns: It returns the calculated sine of the specified radian values.
Example:
# Julia program to illustrate # the use of sin() method  # Getting sine of the specified# radian values.println(sin(0))println(sin(30))println(sin(90))println(sin(44))
Output:
0.0
-0.9880316240928618
0.8939966636005579
0.017701925105413577
The sinh() is an inbuilt function in julia which is used to calculate hyperbolic sine of the specified values.
Syntax: sinh(x)
Parameters:
x: Specified values.
Returns: It returns the calculated hyperbolic sine of the specified values.
Example:
# Julia program to illustrate # the use of sinh() method  # Getting sine of the specified values.println(sinh(0))println(sinh(30))println(sinh(90))println(sinh(45))
Output:
0.0
5.343237290762231e12
6.102016471589204e38
1.7467135528742547e19
The sind() is an inbuilt function in julia which is used to calculate sine of the specified value in degrees.
Syntax: sind(x)
Parameters:
x: Specified value in degrees.
Returns: It returns the calculated sine of the specified value in degrees.
Example:
# Julia program to illustrate # the use of sind() method  # Getting sine of the specified value # in degreeprintln(sind(0))println(sind(30))println(sind(90))println(sind(45))
Output:
0.0
0.5
1.0
0.7071067811865476
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
Reshaping array dimensions in Julia | Array reshape() Method
while loop in Julia
Taking Input from Users in Julia
Java Program to Convert String to InputStream - GeeksforGeeks

12 Jun, 2021
Given a string, the task is to convert the string to InputStream which is shown in the below illustrations.
Illustration:
Input  : String : "Geeks for Geeks"
Output : Input Stream : Geeks for Geeks 
Input  : String : "A computer science portal"
Output : Input stream :  A computer science portal 
In order to reach the goal, we need to use ByteArrayInputStream. So let us discuss how it’s done?
We can convert a String to an InputStream object by using the ByteArrayInputStream class. The ByteArrayInputStream is a subclass present in InputStream class. In ByteArrayInputStream there is an internal buffer present that contains bytes that reads from the stream.
Approach:
Get the bytes of the String.Create a new ByteArrayInputStream using the bytes of the StringAssign the ByteArrayInputStream object to an InputStream variable.Buffer contains bytes that read from the stream.Print the InputStream.
Get the bytes of the String.
Create a new ByteArrayInputStream using the bytes of the String
Assign the ByteArrayInputStream object to an InputStream variable.
Buffer contains bytes that read from the stream.
Print the InputStream.
Example:
Java
// Java Program to Convert String to InputStream// Using ByteArrayInputStream// Importing required librariesimport java.io.*;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.Charset; // Main classpublic class GFG {     // main driver method    public static void main(String[] args) throws IOException {        // Custom inout string as an input        String string = "Geeks for Geeks";         // Printing the above string        System.out.print("String : " + string);         // Now, using ByteArrayInputStream to        // get the bytes of the string, and        // converting them to InputStream        InputStream stream = new ByteArrayInputStream(string.getBytes                (Charset.forName("UTF-8")));         // Creating an object of BufferedReader class to        // take input        BufferedReader br = new BufferedReader(new InputStreamReader(stream));         // Printing the input stream        // using rreadLine() method        String str = br.readLine();         System.out.print("\nInput stream : ");         // If string is not NULL        while (str != null) {            // Keep taking input            System.out.println(str);            str = br.readLine();        }    }}
  
String : Geeks for Geeks
Input stream : Geeks for Geeks
 
simranarora5sos
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
Java Program To Find Decimal Equivalent Of Binary Linked List - GeeksforGeeks

03 Jan, 2022
Given a singly linked list of 0s and 1s find its decimal equivalent.
Input: 0->0->0->1->1->0->0->1->0
Output: 50   

Input: 1->0->0
Output: 4
The decimal value of an empty linked list is considered as 0.
Initialize the result as 0. Traverse the linked list and for each node, multiply the result by 2 and add the node’s data to it.
Java
// Java Program to find decimal value // of binary linked list class GFG{      // Link list Node static class Node {     boolean data;     Node next; };   // Returns decimal value of binary // linked liststatic int decimalValue(Node head) {     // Initialized result     int res = 0;       // Traverse linked list     while (head != null)     {         // Multiply result by 2 and         // add head's data         res = (res << 1) + (head.data?1:0);           // Move next         head = head.next;     }     return res; }   // Utility function to create a // new node. static Node newNode(int data) {     Node temp = new Node();     temp.data = (data == 1 ?                  true : false);     temp.next = null;     return temp; }   // Driver codepublic static void main(String args[]){     // Start with the empty list     Node head = newNode(1);     head.next = newNode(0);     head.next.next = newNode(1);     head.next.next.next = newNode(1);     System.out.print("Decimal value is " +                       decimalValue(head)); }}// This code is contributed by Arnab Kundu
Output : 
Decimal value is 11
Please refer complete article on Decimal Equivalent of Binary Linked List for more details!
Juniper Networks
Java Programs
Linked List
Juniper Networks
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Replace a Element in Java ArrayList?
Java Program to Read a File to String
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)
lsblk Command in Linux with Examples - GeeksforGeeks

27 Sep, 2021

Lsblk is used to display details about block devices and these block devices(Except ram disk) are basically those files that represent devices connected to the pc. It queries /sys virtual file system and udev db to obtain information that it displays. And it basically displays output in a tree-like structure. This command comes pre-installed with the util-Linux package. 
Many Linux distributions do not have lsblk command pre-installed. To install it use the following commands as per your Linux distribution. 
In case of Debian/Ubuntu  
$sudo apt-get install util-linux
In case of CentOS/RedHat  
$sudo yum install util-linux-ng
In case of Fedora OS  
$sudo yum install util-linux-ng
1. To display block devices. 
$lsblk 
It displays the list of block devices on your system. 
2. To display empty block devices as well.  
#lsblk -a 
This will display all block devices along with empty ones. 
3. To print size information in bytes. 
$lsblk -b
It displays all the block devices along with their sizes in bytes. 
4. To print zone model for devices.  
$lsblk -z 
5. To skip slave entries.  
$lsblk -d 
This will skip all the slave entries. 
6.To use ASCII characters for tree formatting.  
$lsblk -i 
This will display the tree formatting with ASCII character values. 
7. To print information about device owner, group, and mode of block devices.  
$lsblk -m 
This will display all details of device owner, group and mode of block devices. 
8. To print selected columns of block-devices. 
$lsblk -o SIZE, NAME, MOUNTPOINT 
This will print only the specified columns. 
9. To hide column headings.  
$lsblk -dn
This will hide column headings. 
10. To display help section of the command.  
$lsblk --help 
This will display the help section of the command. 
simmytarika5

linux-command


Linux-system-commands


Linux-Unix

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
TCP Server-Client implementation in C
tar command in Linux with examples
UDP Server-Client implementation in C
curl command in Linux with Examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
Cat command in Linux with examples
echo command in Linux with Examples
Mutex lock for Linux Thread Synchronization
default - Django Built-in Field Validation - GeeksforGeeks

24 Jun, 2020
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. default=value will make the field default to value. There will be no need to explicitly define any value, even if field is not entered it will default to value. Value depends upon field itself, as if field is datefield, it will accept only date values with predefined validations.
Syntax
field_name = models.Field(default = value)
Illustration of default=value using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app. We will be using CharField for experimenting for all field options.
from django.db import modelsfrom django.db.models import Model# Create your models here.  class GeeksModel(Model):    geeks_field = models.CharField(max_length = 200, default = "GFG is best")
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command,
Python manage.py shell
Now let us try to create instance of GeeksModel using None.
# importing required modelfrom geeks.models import GeeksModel  # creating instance of GeeksModel# without entering anythings = GeeksModel.objects.create()  # saving current model instances.save()
Let us check in admin interface if the instance of model is created.Therefore, default=value modifies the field to set default value for a particular field.
In BooleanField, if one wants to enable or disable the field by default, it can be easily done using default=True and default=false simultaneously.
NaveenArora
sethiojas
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Access object within another objects in Python - GeeksforGeeks

20 Aug, 2020
Prerequisite: Basics of OOPs in Python
In this article, we will learn how to access object methods and attributes within other objects in Python. If we have two different classes and one of these defined another class on calling the constructor. Then, the method and attributes of another class can be accessed by first class objects ( i.e; objects within objects ).
Here in the below example we learn to access object (its methods and attributes) within an object. We define two classes (class first and class second) with proper definitions. 
First class consists of a constructor and a method.
The constructor form an object of the second class in the attribute of the first class.
The method defines the presence in first class method.
Similarly, the second class consists of a constructor and a method.
The constructor form an attribute.
The method defines the presence in the second class method.
As the attribute of first class work as an object of the second class so all the methods and attributes of the second class can be accessed using this:
object_of_first_class.attribute_of_first_class

Below is the implementation:
Python3
# python program to understand the # accessing of objects within objects  # define class firstclass first:        # constructor    def __init__(self):        # class second object        # is created        self.fst = second()              def first_method(self):        print("Inside first method")  # define class secondclass second:        # constructor    def __init__(self):        self.snd = "GFG"              def second_method(self):        print("Inside second method")  # make object of first classobj1 = first()print(obj1)  # make object of second class# with the help of firstobj2 = obj1.fstprint(obj2)  # access attributes and methods # of second classprint(obj2.snd)  obj2.second_method()  # This code is contributed# by Deepanshu Rustagi.
Output:
<__main__.first object at 0x7fde6c57b828>
<__main__.second object at 0x7fde6c57b898>
GFG  
Inside second method

Python-OOP
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Selecting rows in pandas DataFrame based on conditions
Reading and Writing to text files in Python
sum() function in Python
HTML | <table> rules Attribute - GeeksforGeeks

29 May, 2019
The HTML <table> rules Attribute is used to specify the which parts of the inside borders that should be visible.
Syntax:
<table rules="value">
Attribute Values:
none: It does not create any lines.
groups: It create lines between row and column groups.
rows: It creates line between the rows.
cols: It creates line between the columns.
all: It creates line between the rows and columns.
Note: The <table> rules Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML table rules Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML table rules Attribute</h2>      <table rules="rows">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>    </table>    <br>    <table rules="cols">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>    </table>    <br>    <table rules="all">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <table> rules Attribute are listed below:
Google Chrome
Internet Explorer 9.0
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Matplotlib.axis.Axis.set_ticks() function in Python

08 Jun, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack.
The Axis.set_ticks() function in axis module of matplotlib library is used to set the locations of the tick marks from sequence ticks.  
Syntax: Axis.set_ticks(self, ticks, \*, minor=False)  
Parameters: This method accepts the following parameters. 
ticks : This parameter is the sequence of floats.
minor : This parameter contains the bool value.
Return value: This method does not return any value. 
Below examples illustrate the matplotlib.axis.Axis.set_ticks() function in matplotlib.axis: 
Example 1:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np   fig = plt.figure()  x = np.linspace(0,2*np.pi,100)y = 2*np.sin(x)  ax = fig.add_subplot()ax.plot(x,y)ax.yaxis.set_ticks([1,2,3,4,5,6,7])    ax.grid()   fig.suptitle("""matplotlib.axis.Axis.set_ticks()function Example\n""", fontweight ="bold")      plt.show()
Output:  
Example 2:
Python3
# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np   fig = plt.figure()x = np.linspace(-np.pi, np.pi, 100)y = 2 * np.sin(x)  ax = fig.add_subplot()ax.set_title('centered spines')ax.plot(x, y)  ax.spines['left'].set_position('center')ax.spines['right'].set_color('none')ax.spines['bottom'].set_position('center')ax.spines['top'].set_color('none')  ax.xaxis.set_ticks_position('bottom')ax.yaxis.set_ticks_position('left')ax.xaxis.set_ticks([-3, -2.5, -2, -1.5, -1,                    -0.5, 0, 0.5, 1, 1.5,                    2, 2.5, 3])  ax.grid()   fig.suptitle("""matplotlib.axis.Axis.set_ticks()function Example\n""", fontweight ="bold")      plt.show()
Output:  
 
Matplotlib-Axis Class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
HTML | DOM Location reload() Method

05 Jul, 2022
The location reload() method in HTML DOM is used to reload the current document. This method refreshes the current documents. It is similar to the refresh button in the browser. 
Syntax:
location.reload( forceGet )
Parameters: This method contains single parameter forceGet which is optional. This parameter contains boolean value which are listed below:
True: Reloads the current page from the server.
False: Reloads the current from the cache.
Return Value: It does not return any value. 
Example: 
html
<!DOCTYPE html><html>    <head>        <title>            HTML DOM Location reload() Method        </title>                 <!--script to reload current page-->        <script>            function locationreload() {                location.reload();                         }        </script>    </head>         <body>        <h1>GeeksforGeeks</h1>                 <h2>            HTML DOM Location reload() Method        </h2>                 <p>            Click on the button to reload the document        </p>                 <!-- script call here -->        <button onclick = "locationreload()">            Reload page        </button>    </body></html>                   
Output: 
Before click on the button:
  
After click on the button: The document will reload. 
Supported Browsers: The browser supported by DOM Location reload() Method are listed below:
Google Chrome 1
Edge 12
Internet Explorer 5.5
Firefox 1
Opera 3
Safari 1
geeksr3ap
HTML-DOM
HTML-Methods
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.