code-rag-bench/online-tutorials huggingface dataset:
Computer Organization | Performance of Computer - GeeksforGeeks

27 Jul, 2018
Computer performance is the amount of work accomplished by a computer system. The word performance in computer performance means “How well is the computer doing the work it is supposed to do?”. It basically depends on response time, throughput and execution time of a computer system.
Response time is the time from start to completion of a task. This also includes:
Operating system overhead.
Waiting for I/O and other processes
Accessing disk and memory
Time spent executing on the CPU or execution time.
Throughput is the total amount of work done in a given time.
CPU execution time is the total time a CPU spends computing on a given task. It also excludes time for I/O or running other programs. This is also referred to as simply CPU time.
Performance is determined by execution time as performance is inversely proportional to execution time.
Performance = (1 / Execution time) 
And,
(Performance of A /  Performance of B) 
= (Execution Time of B / Execution Time of A) 
If given that Processor A is faster than processor B, that means execution time of A is less than that of execution time of B. Therefore, performance of A is greater than that of performance of B.
Example –Machine A runs a program in 100 seconds, Machine B runs the same program in 125 seconds
(Performance of A /  Performance of B) 
= (Execution Time of B / Execution Time of A) 
= 125 / 100 = 1.25 
That means machine A is 1.25 times faster than Machine B.
And, the time to execute a given program can be computed as:
Execution time  = CPU clock cycles x clock cycle time 
Since clock cycle time and clock rate are reciprocals, so,
Execution time  = CPU clock cycles / clock rate 
The number of CPU clock cycles can be determined by,
CPU clock cycles 
= (No. of instructions / Program ) x (Clock cycles / Instruction) 
= Instruction Count x CPI 
Which gives,
Execution time 
= Instruction Count x CPI x clock cycle time
= Instruction Count x CPI / clock rate  
The units for CPU Execution time are:
How to Improve Performance?To improve performance you can either:
Decrease the CPI (clock cycles per instruction) by using new Hardware.
Decrease the clock time or Increase clock rate by reducing propagation delays or by use pipelining.
Decrease the number of required cycles or improve ISA or Compiler.
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Program for Decimal to Binary Conversion
Direct Access Media (DMA) Controller in Computer Architecture
Flag register of 8086 microprocessor
Interrupts
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
How to plot a density map in Python Matplotlib?

To plot a density map in Python, we can take the following steps −
Create side, x, y, and z using numpy. Numpy linspace helps to create data between two points based on a third number.
Create side, x, y, and z using numpy. Numpy linspace helps to create data between two points based on a third number.
Return coordinate matrices from coordinate vectors using side data.
Return coordinate matrices from coordinate vectors using side data.
Create exponential data using x and y (Step 2).
Create exponential data using x and y (Step 2).
Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method.
Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt, cm, colors
import numpy as np

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

side = np.linspace(-2, 2, 15)
X, Y = np.meshgrid(side, side)
Z = np.exp(-((X - 1) ** 2 + Y ** 2))

plt.pcolormesh(X, Y, Z, shading='auto')

plt.show()
Tryit Editor v3.6 - Show Sass

$myFont: Helvetica, sans-serif;
$myColor: red;
$myFontSize: 18px;
$myWidth: 680px;

body {
  font-family: $myFont;
  font-size: $myFontSize;
  color: $myColor;
}

#container {
  width: $myWidth;
}

body {
  font-family: Helvetica, sans-serif;
  font-size: 18px;
  color: red;
}

#container {
  width: 680px;
  border: 1px blue double;
}

<!DOCTYPE html>
<html>
<link rel="stylesheet" href="mystyle.css">
<body>

<h1>Hello World</h1>

<p>This is a paragraph.</p>

<div id="container">This is some text inside a container.</div>

</body>
</html>
This is a paragraph.
How can I set a Border for an ImageView in Android?

This example demonstrates how do I can I set a border for an ImageView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="match_parent"
      android:background="@layout/image_border"
      android:padding="7dp"
      android:scaleType="centerInside"
      android:src="@drawable/image" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 4 − Create a layout from in res/layout and add the following code in res/layout/image_border.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_height="match_parent"
   android:layout_width="match_parent">
   <stroke
      android:width="8dp"
      android:color="#01fee9" />
</shape>
Step 5 − Add the following code to androidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Online Python Formatter

Editable Python Code
1234567891011121314151617#!/usr/bin/pythonimport reline = "Cats are smarter than dogs";matchObj = re.match( r'dogs', line, re.M|re.I)if matchObj:          print "match --> matchObj.group() : ", matchObj.group()else:   print "No match!!"searchObj = re.search( r'dogs', line, re.M|re.I)if searchObj:        print "search --> searchObj.group() : ", searchObj.group()else:   print "Nothing found!!"X
Privacy Policy
Cookies Policy
Terms of Use
method overloading and type promotion in Java

Method overloading helps to create multiple methods with the same name to do similar action on a different type of parameters.
We can use type promotion in case variables are of similar type. Type promotion automatically promotes the lower range value to higher range value. For example, byte variable can be assigned to an int variable. Here byte variable will be type promoted to int. In case, we want to add two numbers which can be byte, short or int, we can use a single method. See the example below −
 Live Demo
public class Tester {
   public static void main(String args[]) {
      Tester tester = new Tester();
      byte a = 1, b= 2;
      short c = 1, d = 2;
      int e = 1, f = 2;
      System.out.println(tester.add(a, b));
      System.out.println(tester.add(c, d));
      System.out.println(tester.add(e, f));
   }
   public int add(int a, int b) {
      return a + b;
   }
}
3
3
3
C - memset function

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <stdio.h>

void* memset(void* s, int c, int n); 

The memset function sets the first n bytes in s to c. Generally this function is used to set a memory location to null chracters '\0'.
The memset function returns s with the set value to c
#include <stdio.h>

int main() {
  char string[20];

  strcpy(string, "Hello");
  printf( "Before using memset |%s|\n", string );
  memset( string, '\0', sizeof(string) );
  printf( "After using memset |%s|\n", string );

  return 0;
}

It will proiduce following result:
Before using memset |Hello|
After using memset ||


Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
C# | Boolean.TryParse() Method - GeeksforGeeks

20 Apr, 2019
This method is used to convert the specified string representation of a logical value to its Boolean equivalent. It returns a value that indicates whether the conversion succeeded or failed.
Syntax:
public static bool TryParse (string value, out bool result);
Parameters:
value: It is a string containing the value to convert.
result: When this method returns, if the conversion succeeded, contains true if value is equal to TrueString or false if value is equal to FalseString. If the conversion failed, contains false. The conversion fails if the value is null or is not equal to the value of either the TrueString or FalseString field.
Return Value: This method returns true if value was converted successfully otherwise it returns false.
Below programs illustrate the use of Boolean.TryParse(String, Boolean) Method:
Example 1:
// C# program to demonstrate// Boolean.TryParse(String, Boolean)// Methodusing System;  class GFG {  // Main Methodpublic static void Main() {          // passing different values         // to the method to check        checkParse("true");        checkParse("false");        checkParse("'     true     '");        checkParse(" $  ");        checkParse("1");    }  // Declaring checkparse methodpublic static void checkParse(string value) {          // Declaring data type        bool result;        bool flag;           // using the method        result = Boolean.TryParse(value, out flag);          // Display boolean type result        Console.WriteLine("{0} --> {1} ", value, result);    }}
true --> True 
false --> True 
'     true     ' --> False 
 $   --> False 
1 --> False

Example 2:
// C# program to demonstrate// Boolean.TryParse(String, Boolean)// Methodusing System;  class GFG {      // Main Method    public static void Main()    {          // passing different values         // to the method to check        checkParse("true1");        checkParse(null);        checkParse(String.Empty);    }  // Declaring checkparse methodpublic static void checkParse(string value) {          // Declaring data type        bool result;        bool flag;           // using the method        result = Boolean.TryParse(value, out flag);          // Display boolean type result        Console.WriteLine("{0} --> {1} ", value, result);    }}
true1 --> False 
 --> False 
 --> False

Note: The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.boolean.tryparse?view=netframework-4.7.2
CSharp-Boolean-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
C# | Method Overriding
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Constructors
Introduction to .NET Framework
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
C# | Delegates
IDE | GeeksforGeeks | A computer science portal for geeks

Please enter your email address or userHandle.
12345678910111213141516171819202122232425262728def DNF(input, length, Swaps=0):        high = length - 1        p = 0        i = 0        while i <= high:                if input[i] == 1:                        if input[i]==input[p]:                            p+=1                            i+=1                        else:                            input[i],input[p]=input[p],input[i]                            p = p+1                            i = i+1                            Swaps+=1                elif input[i] > 2:                        if input[i]==input[high]:                            high-=1                        else:                            input[i],input[high]=input[high],input[i]                            high = high-1                            Swaps+=1                else:                        i = i+1        print "Swaps",Swapsinput = [1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4]DNF(input,len(input))print inputההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
https://ide.geeksforgeeks.org/3bIgei
Swaps 6
[1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 4, 4, 4, 4, 4, 4, 4, 4]
Get the first element in an array and return using MongoDB Aggregate?

Use unwindoperatorwithproject for to get the first element in an array. Let us create a collection with documents. Following is the query
>db.getFirstElementInArrayDemo.insertOne({"StudentName":"John","StudentSubject":["MongoDB","Python","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c41292d6669774125244e")
}
>db.getFirstElementInArrayDemo.insertOne({"StudentName":"Chris","StudentSubject":["Java","C"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c413f2d6669774125244f")
}
>db.getFirstElementInArrayDemo.insertOne({"StudentName":"Robert","StudentSubject":["C++","Ruby"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c41532d66697741252450")
}
Following is the query to display all documents from a collection with the help of find() method
> db.getFirstElementInArrayDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5c9c41292d6669774125244e"),
   "StudentName" : "John",
   "StudentSubject" : [
      "MongoDB",
      "Python",
      "MySQL"
   ]
}
{
   "_id" : ObjectId("5c9c413f2d6669774125244f"),
   "StudentName" : "Chris",
   "StudentSubject" : [
      "Java",
      "C"
   ]
}
{
   "_id" : ObjectId("5c9c41532d66697741252450"),
   "StudentName" : "Robert",
   "StudentSubject" : [
      "C++",
      "Ruby"
   ]
}
Following is the query to get first element in an array and return using aggregate
> db.getFirstElementInArrayDemo.aggregate([
...    {$unwind:"$StudentSubject"},
...    {$group:{"_id":"$_id","FirstElement":{$first:"$StudentSubject"}}},
...    {$project:{"_id":0,"FirstElement":1}}
... ]);
This will produce the following output
{ "FirstElement" : "Java" }
{ "FirstElement" : "C++" }
{ "FirstElement" : "MongoDB" }
You can use $slice operator in find() to get the first element in the array. Following is the query
> db.getFirstElementInArrayDemo.find({},{"StudentSubject":{$slice:1}});
This will produce the following output
{ "_id" : ObjectId("5c9c41292d6669774125244e"), "StudentName" : "John", "StudentSubject" : [ "MongoDB" ] }
{ "_id" : ObjectId("5c9c413f2d6669774125244f"), "StudentName" : "Chris", "StudentSubject" : [ "Java" ] }
{ "_id" : ObjectId("5c9c41532d66697741252450"), "StudentName" : "Robert", "StudentSubject" : [ "C++" ] }
Java Generics - No Instance

A type parameter cannot be used to instantiate its object inside a method.
public static <T> void add(Box<T> box) {
   //compiler error
   //Cannot instantiate the type T
   //T item = new T();  
   //box.add(item);
}
To achieve such functionality, use reflection.
public static <T> void add(Box<T> box, Class<T> clazz) 
   throws InstantiationException, IllegalAccessException{
   T item = clazz.newInstance();   // OK
   box.add(item);
   System.out.println("Item added.");
}
package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) 
      throws InstantiationException, IllegalAccessException {
      Box<String> stringBox = new Box<String>();
      add(stringBox, String.class);
   }  

   public static <T> void add(Box<T> box) {
      //compiler error
      //Cannot instantiate the type T
      //T item = new T();  
      //box.add(item);
   }

   public static <T> void add(Box<T> box, Class<T> clazz) 
      throws InstantiationException, IllegalAccessException{
      T item = clazz.newInstance();   // OK
      box.add(item);
      System.out.println("Item added.");
   }   
}

class Box<T> {
   private T t;

   public void add(T t) {
      this.t = t;
   }

   public T get() {
      return t;
   }   
}
This will produce the following result −
Item added.


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
What is __init__.py in Python?

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable. An example of the __init__.py file:
from math import sin
from my_package import my_func
The above code ensures that the imported functions are available in the package's modules when it is imported as it is defined in the __init__.py file. You can read more about __init__.py at http://mikegrouchy.com/blog/2012/05/be-pythonic-__init__py.html
Converting a proper fraction to mixed fraction - JavaScript

A proper fraction is the one that exists in the p/q form (both p and q being natural numbers)
Suppose we divide the numerator of a fraction (say a) with its denominator (say b), to get quotient q and remainder r.
The mixed fraction form for fraction (a/b) will be −
qrb
And it is pronounced as "q wholes and r by b”.
We are required to write a JavaScript function that takes in an array of exactly two numbers representing a proper fraction and our function should return an array with three numbers representing its mixed form
Following is the code −
const arr = [43, 13];
const properToMixed = arr => {
   const quotient = Math.floor(arr[0] / arr[1]);
   const remainder = arr[0] % arr[1];
   if(remainder === 0){
      return [quotient];
   }else{
      return [quotient, remainder, arr[1]];
   };
};
console.log(properToMixed(arr));
Following is the output in the console −
[ 3, 4, 13 ]
A Simple Explanation of the Bag-of-Words Model | by Victor Zhou | Towards Data Science

The bag-of-words (BOW) model is a representation that turns arbitrary text into fixed-length vectors by counting how many times each word appears. This process is often referred to as vectorization.
Let’s understand this with an example. Suppose we wanted to vectorize the following:
the cat sat
the cat sat in the hat
the cat with the hat
We’ll refer to each of these as a text document.
We first define our vocabulary, which is the set of all words found in our document set. The only words that are found in the 3 documents above are: the, cat, sat, in, the, hat, and with.
To vectorize our documents, all we have to do is count how many times each word appears:
Now we have length-6 vectors for each document!
the cat sat: [1, 1, 1, 0, 0, 0]
the cat sat in the hat: [2, 1, 1, 1, 1, 0]
the cat with the hat: [2, 1, 0, 0, 1, 1]
Notice that we lose contextual information, e.g. where in the document the word appeared, when we use BOW. It’s like a literal bag-of-words: it only tells you what words occur in the document, not where they occurred.
Now that you know what BOW is, I’m guessing you’ll probably need to implement it. Here’s my preferred way of doing it, which uses Keras’s Tokenizer class:
Running that code gives us:
Vocabulary: ['the', 'cat', 'sat', 'hat', 'in', 'with'][[0. 1. 1. 1. 0. 0. 0.] [0. 2. 1. 1. 1. 1. 0.] [0. 2. 1. 0. 1. 0. 1.]]
Notice that the vectors here have length 7 instead of 6 because of the extra 0 element at the beginning. This is an inconsequential detail - Keras reserves index 0 and never assigns it to any word.
Despite being a relatively basic model, BOW is often used for Natural Language Processing (NLP) tasks like Text Classification. Its strengths lie in its simplicity: it’s inexpensive to compute, and sometimes simpler is better when positioning or contextual info aren’t relevant.
I’ve written a blog post that uses BOW for profanity detection — check it out if you’re curious to see BOW in action!
Originally published at https://victorzhou.com.
Python | Pandas Dataframe/Series.tail() method

01 Oct, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas tail() method is used to return bottom n (5 by default) rows of a data frame or series.
Syntax: Dataframe.tail(n=5)
Parameters:n: integer value, number of rows to be returned
Return type: Dataframe with bottom n rows
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example #1:In this example, bottom 5 rows of data frame are returned and stored in a new variable. No parameter is passed to .tail() method since by default it is 5.
# importing pandas moduleimport pandas as pd  # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # calling tail() method # storing in new variabledata_bottom = data.tail()  # displaydata_bottom
Output:As shown in the output image, it can be seen that the index of returned rows is ranging from 453 to 457. Hence, last 5 rows were returned.
 Example #2: Calling on Series with n parameter()
In this example, the .tail() method is called on series with custom input of n parameter to return bottom 12 rows of the series.
# importing pandas moduleimport pandas as pd  # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")  # number of rows to returnn = 12  # creating seriesseries = data["Salary"]  # returning top n rowsbottom = series.tail(n = n)  # displaybottom
Output:As shown in the output image, top 12 rows ranging from 446 to 457th index position of the Salary column were returned.
Python pandas-dataFrame-methods
Python pandas-methods
Python pandas-series-methods
Python-pandas
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
Difference between JOIN and UNION in SQL

19 Apr, 2022
JOIN: JOIN in SQL is used to combine data from many tables based on a matched condition between them. The data combined using JOIN statement results into new columns. Consider the two tables:
Boys
Girls
 Example:
sql> 
SELECT Boys.Name, Boys.Age, Girls.Address,
FROM Boys 
INNER JOIN Girls 
ON Boys.Rollno = Girls.Rollno; 
The resultant table is:  UNION: UNION in SQL is used to combine the result-set of two or more SELECT statements. The data combined using UNION statement is into results into new distinct rows. Example:
sql> 
SELECT Name 
FROM Boys 
WHERE Rollno < 16 

UNION

SELECT Name 
FROM Girls 
WHERE Rollno > 9 
The resultant table is:  Difference between JOIN and UNION in SQL :
dhruv5819
hemantdhoundiyal0
DBMS-Join
Picked
SQL-Clauses
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Interview Questions
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Python 3 - Loops

In general, statements are executed sequentially − The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.
Programming languages provide various control structures that allow more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement −
Python programming language provides the following types of loops to handle looping requirements.
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
You can use one or more loop inside any another while, or for loop.
The Loop control statements change the execution from its normal sequence. When the execution leaves a scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
Terminates the loop statement and transfers execution to the statement immediately following the loop.
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
Let us go through the loop control statements briefly.
Iterator is an object which allows a programmer to traverse through all the elements of a collection, regardless of its specific implementation. In Python, an iterator object implements two methods, iter() and next().
String, List or Tuple objects can be used to create an Iterator.
#!/usr/bin/python3
import sys

list = [1,2,3,4]
it = iter(list) # this builds an iterator object
print (next(it)) #prints next available element in iterator
#Iterator object can be traversed using regular for statement
for x in it:
   print (x, end=" ")
#or using next() function
while True:
   try:
      print (next(it))
   except StopIteration:
      sys.exit()
A generator is a function that produces or yields a sequence of values using yield method.
When a generator function is called, it returns a generator object without even beginning execution of the function. When the next() method is called for the first time, the function starts executing until it reaches the yield statement, which returns the yielded value. The yield keeps track i.e. remembers the last execution and the second next() call continues from previous value.
The following example defines a generator, which generates an iterator for all the Fibonacci numbers.
#!usr/bin/python3

import sys
def fibonacci(n): #generator function
   a, b, counter = 0, 1, 0
   while True:
      if (counter > n): 
         return
      yield a
      a, b = b, a + b
      counter += 1
f = fibonacci(5) #f is iterator object

while True:
   try:
      print (next(f), end=" ")
Python | Background subtraction using OpenCV

06 Jul, 2021
Background Subtraction has several use cases in everyday life, It is being used for object segmentation, security enhancement, pedestrian tracking, counting the number of visitors, number of vehicles in traffic etc. It is able to learn and identify the foreground mask.As the name suggests, it is able to subtract or eliminate the background portion in an image. Its output is a binary segmented image which essentially gives information about the non-stationary objects in the image. There lies a problem in this concept of finding non-stationary portion, as the shadow of the moving object can be moving and sometimes being classified in the foreground.The popular Background subtraction algorithms are:  
BackgroundSubtractorMOG : It is a gaussian mixture based background segmentation algorithm.
BackgroundSubtractorMOG2: It uses the same concept but the major advantage that it provides is in terms of stability even when there is change in luminosity and better identification capability of shadows in the frames.
Geometric multigrid: It makes uses of statistical method and per pixel bayesin segmentation algorithm.
 
Python3
# Python code for Background subtraction using OpenCVimport numpy as npimport cv2 cap = cv2.VideoCapture('/home/sourabh/Downloads/people-walking.mp4')fgbg = cv2.createBackgroundSubtractorMOG2() while(1):    ret, frame = cap.read()     fgmask = fgbg.apply(frame)      cv2.imshow('fgmask', fgmask)    cv2.imshow('frame',frame )          k = cv2.waitKey(30) & 0xff    if k == 27:        break      cap.release()cv2.destroyAllWindows()
Original video frame:  
Background subtracted video frame:  
Thus, we saw an application of background subtraction algorithm detecting motions, life in video frames. 
pravesh25pandey
abhishek0719kadiyan
varshagumber28
sumitgumber28
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
Prove that the square of an odd integer is always odd

31 May, 2021
This article focuses on discussing in detail the proof of why the square of an odd integer is always an odd number.
Odd Number:A number is said to be odd if it is not divisible by 2, or if a number can be expressed in the form of (2k +1), for some integer k, then the number is called an odd number.
Square Root:Given two numbers A and B, if A * A = B then, A is known as the square root of B.
Problem Statement: The square of an odd integer is always an odd number.
Proof:This section discusses the proof of the above problem statement-
1. Consider an odd integer, X. According to the above definition, A can be written as-
X = (2k + 1), for some integer k
2. Now, squaring both sides-
X2 = (2k + 1)2 ---(1)
3. The formula for the square of the sum of 2 numbers is-
(A + B)2 = A2 + 2AB + B2
4. Using the above property in equation (1)-
X2 = (2k)2 + 4k + 1
X2 = 4k2 + 4k + 1 ---(2) 
5. Now, let’s do some rearrangements in equation 2 as- 
X2 = 2(2k2 + 2k) + 1
6. Notice the right-hand side of the above equation. Since K is an integer, (2k2 + 2k) is also an integer. Now, let’s assume an integer, m = (2k2 + 2k). The above equation can be written as-
X2 = (2m + 1), for some integer m
7. From the above equation and the definition of an odd integer, it can be concluded that X2 is also an odd integer, which proves our statement that the Square of an odd integer is always odd.
Example:For X = 3-
1. Put the value X = 3 in the above equations’ step by step-
X = (2k + 1), for some integer k
3 = (2k + 1), for k = 1 (integer)
2. Now, if square of X is taken-
X2 = (2k + 1)2
X2 = 4K2 + 4K + 1
3. Again, after doing arrangements, X2 can be written as- 
X2 = 2(2k2 + 2k) + 1
for X = 3,
9 = 2(2k2 + 2k) + 1 
4. For k = 1, (2k2 + 2k) evaluates to 4. Let m= (2k2 + 2k) = 4 i.e.
9 = 2m + 1, for m = 4 (integer)  
Now, from the above definition of an odd integer, it can be said that 9 is an odd number, which implies the square of an odd integer (In this case, 3) is always odd. Hence, Proved.
Engineering Mathematics
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Propositional Logic and Predicate Logic
Activation Functions
Logic Notations in LaTeX
Mathematics | Introduction of Set theory
Introduction of Statistics and its Types
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Normal Forms in DBMS
PL/SQL - Basic Loop Statement

Basic loop structure encloses sequence of statements in between the LOOP and END LOOP statements. With each iteration, the sequence of statements is executed and then control resumes at the top of the loop.
The syntax of a basic loop in PL/SQL programming language is −
LOOP 
   Sequence of statements; 
END LOOP; 

Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT statement or an EXIT WHEN statement is required to break the loop.
DECLARE 
   x number := 10; 
BEGIN 
   LOOP 
      dbms_output.put_line(x); 
      x := x + 10; 
      IF x > 50 THEN 
         exit; 
      END IF; 
   END LOOP; 
   -- after exit, control resumes here  
   dbms_output.put_line('After Exit x is: ' || x); 
END; 
/
When the above code is executed at the SQL prompt, it produces the following result −
10 
20 
30 
40 
50 
After Exit x is: 60  

PL/SQL procedure successfully completed. 

You can use the EXIT WHEN statement instead of the EXIT statement −
DECLARE 
   x number := 10; 
BEGIN 
   LOOP 
      dbms_output.put_line(x); 
      x := x + 10; 
      exit WHEN x > 50; 
   END LOOP; 
   -- after exit, control resumes here 
   dbms_output.put_line('After Exit x is: ' || x); 
END; 
/
When the above code is executed at the SQL prompt, it produces the following result −
10 
20 
30 
40  
50 
After Exit x is: 60  

PL/SQL procedure successfully completed.
Double parseDouble() method in Java with examples

26 Oct, 2018
The parseDouble() method of Java Double class is a built in method in Java that returns a new double initialized to the value represented by the specified String, as done by the valueOf method of class Double.
Syntax:
public static double parseDouble(String s)
Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.
Return type: It returns e double value represented by the string argument.
Exception: The function throws two exceptions which are described below:
NullPointerException– when the string parsed is null
NumberFormatException– when the string parsed does not contain a parsable float
Below is the implementation of the above method.
Program 1:
// Java Code to implement// parseDouble() method of Double class  class GFG {      // Driver method    public static void main(String[] args)    {          String str = "100";          // returns the double value        // represented by the string argument        double val = Double.parseDouble(str);          // prints the double value        System.out.println("Value = " + val);    }}
Value = 100.0

Program 2: To show NumberFormatException
// Java Code to implement// parseDouble() method of Double class  class GFG {      // Driver method    public static void main(String[] args)    {          try {              String str = "";              // returns the double value            // represented by the string argument            double val = Double.parseDouble(str);              // prints the double value            System.out.println("Value = " + val);        }        catch (Exception e) {            System.out.println("Exception: " + e);        }    }}
Exception: java.lang.NumberFormatException: empty String

Program 3: To show NullPointerException
// Java Code to implement// parseDouble() method of Double class  class GFG {      // Driver method    public static void main(String[] args)    {          try {              String str = null;              // returns the double value            // represented by the string argument            double val = Double.parseDouble(str);              // prints the double value            System.out.println("Value = " + val);        }        catch (Exception e) {            System.out.println("Exception: " + e);        }    }}
Exception: java.lang.NullPointerException

Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
java-basics
Java-Double
Java-Functions
Java-lang package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PostgreSQL - Delete Data - GeeksforGeeks

23 Aug, 2021
In this article, we are going to see how to delete data in tables from PostgreSQL using pyscopg2 module in Python. In PostgreSQL, DELETE TABLE is used to delete the data in the existing table from the database. It removes table definition and all associated data, indexes, rules, triggers, and constraints for that table. If the particular table doesn’t exist then it shows an error. 
Here, we are using the accounts table for demonstration.
Now let’s drops this table, for we will use will psycopg2 module to connect the PostgreSQL and execute the SQL query in cursor.execute(query) object.
Syntax: cursor.execute(sql_query);
Here we are deleting all the table data using DELETE clause.
Syntax: DELETE FROM table_name
Code:
Python3
# importing psycopg2import psycopg2  conn=psycopg2.connect(    database="geeks",    user="postgres",    password="root",    host="localhost",    port="5432")    # Creating a cursor object using the cursor() # methodcursor = conn.cursor()  # delete all details from account tablesql = ''' DELETE FROM account '''  # Executing the querycursor.execute(sql)    # Commit your changes in the databaseconn.commit()  # Closing the connectionconn.close()
Output:
Where clause is used as a condition statement in SQL, it is used to filter records.
Syntax: DELETE FROM table_name FROM WHERE condition
Code:
Python3
# importing psycopg2import psycopg2  conn=psycopg2.connect(    database="geeks",    user="postgres",    password="password",    host="localhost",    port="5432")    # Creating a cursor object using the cursor() # methodcursor = conn.cursor()  # delete details of row where id =1 from account # tablesql = ''' DELETE FROM account WHERE id='151' '''  # Executing the querycursor.execute(sql)  # Commit your changes in the databaseconn.commit()  # Closing the connectionconn.close()
Output:
Picked
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Clausal Form in Deductive Databases - GeeksforGeeks

01 Sep, 2021
In clausal form, the formula is made up of a number of clauses, where each clause is composed of a number of literals connected by OR logical connectives only.
A formula can have the following quantifiers:
Universal quantifier – It can be understood as – “For all x, P(x) holds”, meaning P(x) is true for every object x in the universe. Example: All trucks has wheels.  Existential quantifier – It can be understood as – “There exists an x such that P(x)”,  meaning P(x) is true for at least one object x of the universe. Example: Someone cares for you.  
Universal quantifier – It can be understood as – “For all x, P(x) holds”, meaning P(x) is true for every object x in the universe. Example: All trucks has wheels.  
Existential quantifier – It can be understood as – “There exists an x such that P(x)”,  meaning P(x) is true for at least one object x of the universe. Example: Someone cares for you.  
A clausal form formula must be transformed into another formula with the following characteristics :  
All variables in the formula are universally quantified. Hence, it is not necessary to include the universal quantifiers explicitly for all. The quantifiers are removed, and all variables in the formula are implicitly quantified by the universal quantifier.  
 
As the formula is made up of a number of clauses, and each clause is composed of a number of literals connected by OR logical connectives only. Hence, each clause is a disjunction of literals.  
To form a formula, the clauses themselves are connected by AND logical connectives only. Hence, clausal form of a formula is a conjunction of clauses.  
Any formula can be converted into clausal form. 
Example : Literals can be positive literals or negative literals. For the forms of the individual clauses where each of is a disjunction of literals. For the clause form:
  
NOT(P1) OR NOT(P2) OR ..... OR NOT(Pn) OR Q1 OR Q2 OR ..... OR Qm 
The above clause has n negative literals and m positive literals. This clause can be transformed into the following equivalent logical formula:  
P1 AND P2 AND ..... AND Pn => Q1 OR Q2 OR ..... OR Qm 
where ‘=>’ is the implies symbol. 
If all the p literals (i = 1, 2, ..., ) are true, the 2nd formula is true only if at least one of the Q’s is true, which is the meaning of the (implies) symbol. For 1st formula, if all the P literals (i = 1, 2, ..., n) are true, their negations are all false; so in this case it is true only if at least one of the Q’s is true. 
Thus the above two formulas are equivalent, hence their truth values are always the same. 
kalrap615
DBMS-Relational Algebra
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Deadlock in DBMS
Types of Functional dependencies in DBMS
KDD Process in Data Mining
What is Temporary Table in SQL?
Conflict Serializability in DBMS
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Differences between TCP and UDP
Histogram in R using ggplot2 - GeeksforGeeks

25 Feb, 2021
ggplot2 is an R Package that is dedicated to Data visualization. ggplot2 Package  Improve the quality and the beauty (aesthetics ) of the graph. By Using ggplot2 we can make almost every kind of graph In RStudio
A histogram is an approximate representation of the distribution of numerical data. In a histogram, each bar groups numbers into ranges. Taller bars show that more data falls in that range. A histogram displays the shape and spread of continuous sample data.
Histograms roughly give us an idea about the probability distribution of a given variable by depicting the frequencies of observations occurring in certain ranges of values. Basically, Histograms are used to show distributions of a given variable while bar charts are used to compare variables. Histograms plot quantitative data with ranges of the data grouped into the intervals while bar charts plot categorical data.
geom_histogram() function is an in-built function of ggplot2 module.
Approach
Import module
Create dataframe
Create histogram using function
Display plot
Example 1:
R
set.seed(123)  # In the above line,123 is set as the # random number value# The main point of using the seed is to# be able to reproduce a particular sequence # of 'random' numbers. and sed(n) reproduces# random numbers results by seeddf <- data.frame(   gender=factor(rep(c(     "Average Female income ", "Average Male incmome"), each=20000)),   Average_income=round(c(rnorm(20000, mean=15500, sd=500),                           rnorm(20000, mean=17500, sd=600)))   )  head(df)  # if already installed ggplot2 then use library(ggplot2)library(ggplot2)  # Basic histogramggplot(df, aes(x=Average_income)) + geom_histogram()  # Change the width of binsggplot(df, aes(x=Average_income)) +         geom_histogram(binwidth=1)  # Change colorsp<-ggplot(df, aes(x=Average_income)) +        geom_histogram(color="white", fill="red")p
Output : 
Example 2:
R
plot_hist <- ggplot(airquality, aes(x = Ozone)) +     # binwidth help to change the thickness (Width) of the bar    geom_histogram(aes(fill = ..count..), binwidth = 10)+     # name = "Mean ozone(03) in ppm parts per million "   # name is used to give name to axis     scale_x_continuous(name = "Mean ozone(03) in ppm parts per million ",                      breaks = seq(0, 200, 25),                      limits=c(0, 200)) +   scale_y_continuous(name = "Count") +     # ggtitle is used to give name to a chart   ggtitle("Frequency of mean ozone(03)") +   scale_fill_gradient("Count", low = "green", high = "red")  plot_hist
Output : 
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
How to get the Shared folder permissions with PowerShell?

To get the shared folder permissions using PowerShell, we can use the Get-SmbShare cmdlet.
For example, we have a shared folder name DSC and we need to retrieve its permissions, we can use the below command.
Get-SmbShare -Name DSC
Name ScopeName Path Description
---- --------- ---- -----------
DSC       *   E:\DSC
It doesn’t show the permission by default and we can retrieve the full list using Fl *. For example,
Get-SmbShare -Name DSC | fl *
And you can see the PresentPathACL property there. This property is used to retrieve the permissions on the shared folder. So we can directly use the command,
(Get-SmbShare -Name DSC).PresetPathAcl
Directory: E:\
Path Owner                   Access
---- -----                   ------
DSC BUILTIN\Administrators   Everyone Allow ReadAndExecute, Synchronize
To get the shared folder permission from the remote computer use,
Invoke-Command -ComputerName Labmachine2k16 -ScriptBlock {
   Get-SmbShare -Name DSC} | Select -ExpandProperty PresetPathAcl
Another direct command, you can use is Get-SmbShareAccess
Get-SmbShareAccess -Name "Shared folder"
PS C:\Temp> Get-SmbShareAccess -Name "Shared folder"
Name          ScopeName AccountName AccessControlType AccessRight
----          --------- ----------- ----------------- -----------
Shared folder    *       Everyone          Allow          Read
How to set the range for boxplot in base R?

By default, R considers the vector or the data frame column values. But if we want to set the range for boxplot in base R, we can use ylim argument within the boxplot function. For example, if we have a vector called x that contains values starting from 21 to 50 and we want to have the range in the boxplot starting from 1 to 100 then we can use the command
boxplot(x,ylim=c(1,100))
 Live Demo
x<-rnorm(500,10,1)
boxplot(x)
boxplot(x,ylim=c(0,15))
boxplot(x,ylim=c(2,20))