code-rag-bench/online-tutorials huggingface dataset:
Assembly - Memory Segments

We have already discussed the three sections of an assembly program. These sections represent various memory segments as well.
Interestingly, if you replace the section keyword with segment, you will get the same result. Try the following code −
segment .text	   ;code segment
   global _start    ;must be declared for linker 
	
_start:	           ;tell linker entry point
   mov edx,len	   ;message length
   mov ecx,msg     ;message to write
   mov ebx,1	   ;file descriptor (stdout)
   mov eax,4	   ;system call number (sys_write)
   int 0x80	   ;call kernel

   mov eax,1       ;system call number (sys_exit)
   int 0x80	   ;call kernel

segment .data      ;data segment
msg	db 'Hello, world!',0xa   ;our dear string
len	equ	$ - msg          ;length of our dear string
When the above code is compiled and executed, it produces the following result −
Hello, world!

A segmented memory model divides the system memory into groups of independent segments referenced by pointers located in the segment registers. Each segment is used to contain a specific type of data. One segment is used to contain instruction codes, another segment stores the data elements, and a third segment keeps the program stack.
In the light of the above discussion, we can specify various memory segments as −
Data segment − It is represented by .data section and the .bss. The .data section is used to declare the memory region, where data elements are stored for the program. This section cannot be expanded after the data elements are declared, and it remains static throughout the program.
The .bss section is also a static memory section that contains buffers for data to be declared later in the program. This buffer memory is zero-filled. 

Data segment − It is represented by .data section and the .bss. The .data section is used to declare the memory region, where data elements are stored for the program. This section cannot be expanded after the data elements are declared, and it remains static throughout the program.
The .bss section is also a static memory section that contains buffers for data to be declared later in the program. This buffer memory is zero-filled. 

Code segment − It is represented by .text section. This defines an area in memory that stores the instruction codes. This is also a fixed area.
Code segment − It is represented by .text section. This defines an area in memory that stores the instruction codes. This is also a fixed area.
Stack − This segment contains data values passed to functions and procedures within the program.
Stack − This segment contains data values passed to functions and procedures within the program.

    46 Lectures 
     2 hours 

 Frahaan Hussain

    23 Lectures 
     12 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Aggregate records in JavaScript

Let’s say, we have an array of objects that contains information about some random transactions carried out by some people −
const transactions = [{
   name: 'Rakesh',
   amount: 1500
}, {
      name: 'Rajesh',
      amount: 1200
}, {
      name: 'Ramesh',
      amount: 1750
}, {
      name: 'Rakesh',
      amount: 2100
}, {
      name: 'Mukesh',
      amount: 1100
}, {
      name: 'Rajesh',
      amount: 1950
}, {
      name: 'Mukesh',
      amount: 1235
}, {
      name: 'Ramesh',
      amount: 2000
}];
We are required to write a function that takes in this array and aggregates and returns the transaction amount of unique people in distinct objects.
Therefore, let’s write the code for this function −
const transactions = [{
   name: 'Rakesh',
   amount: 1500
}, {
      name: 'Rajesh',
      amount: 1200
}, {
      name: 'Ramesh',
      amount: 1750
}, {
      name: 'Rakesh',
      amount: 2100
}, {
      name: 'Mukesh',
      amount: 1100
}, {
      name: 'Rajesh',
      amount: 1950
}, {
      name: 'Mukesh',
      amount: 1235
}, {
      name: 'Ramesh',
      amount: 2000
}];
const aggregateArray = arr => {
   return arr.reduce((acc, val) => {
      const index = acc.findIndex(obj => obj.name === val.name);
      if(index !== -1){
         acc[index].amount += val.amount;
      }else{
         acc.push({
            name: val.name,
            amount: val.amount
         });
      };
      return acc;
   }, []);
};
console.log(aggregateArray(transactions));
The output in the console will be −
[
   { name: 'Rakesh', amount: 3600 },
   { name: 'Rajesh', amount: 3150 },
   { name: 'Ramesh', amount: 3750 },
   { name: 'Mukesh', amount: 2335 }
]
How to create Text Buttons using CSS ? - GeeksforGeeks

15 Mar, 2021
In this article, we are going to see how to create text buttons using CSS.
The text button is a button that appears to be text but acts as a button if we press it. Text buttons are different from anchor tags even if they might look similar. To create text buttons first, we create simple buttons in HTML using a button tag. After creating the button we apply CSS and change its properties to make it look like a text button. To make it look like a text button we remove its default border and background. To identify that it is a button we give hover color so, when we move our cursor over it, it changes its color from transparent to green.
Syntax:
#textButton{
       background:none; 
       border:none;     
}
#textButton:hover{
       background-color: green;
}
Example: The following demonstrates the above approach. We created an HTML file, and we created a button with the name “GeeksforGeeks” using a button tag with id as “textButton”. After that, we created a style tag in which we selected that button using its id and removed its background and border properties by setting them to none. We added a hover background color so that users can identify our button. 
HTML
<!DOCTYPE html><html><body><h2>Welcome To GFG</h2> <h1>Text buttons using css</h1>  <!-- creating buttons -->    <button id="textButton">      GeeksforGeeks    </button>      <!-- Applying styling to buttons -->  <style>        #textButton{            background:none;             border:none;             }        #textButton:hover{            background-color: green;        }    </style></body></html>
Output: 
        
text buttons using CSS
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
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
Find position of the only set bit in C++

In this problem we are given a number N which has only one set bit in its binary representation. Our task is to find the position of the only set bit. If the number has only one set bit return the position of the number otherwise print invalid number.
Let’s take an example to understand the problem,
N = 32
6
Binary representation of the number is 10000.
One fact to know before we proceed further is the number will have only 1 set bit if it is a power of 2. Otherwise it will have more number of set bits.
A simple solution is by starting from the rightmost bit and then check the value of bits. We will use a loop to check if it is set or not.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
bool isPowerOfTwo(unsigned n) {
   if(n>0) {
      while(n%2 == 0)
      n/=2;
      if(n == 1)
         return true;
   }
   if(n == 0 || n != 1)
      return false;
   return false;
}
int findPostionOfSetBit(unsigned n) {
   unsigned i = 1, position = 1;
   while (!(i & n)) {
      i = i << 1;
      ++position;
   }
   return position;
}
int main(void){
   int n = 64;
   if(!isPowerOfTwo(n))
      cout<<"Invalid Number!";
   else
      cout<<"The position of the number "<<n<<" is "<<findPostionOfSetBit(n);
   return 0;
}
The position of the number 64 is 7
An alternate method to solve the problem is by using the shift operation to shift the number to right until it becomes 0. At the end the number of shifts done to reach 0 is the position of the set bit.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
bool isPowerOfTwo(unsigned n) {
   if(n>0) {
      while(n%2 == 0)
         n/=2;
      if(n == 1)
         return true;
   }
   if(n == 0 || n != 1)
      return false;
   return false;
}
int findPostionOfSetBit(unsigned n) {
   unsigned position = 0;
   while (n) {
      n = n >> 1;
      ++position;
   }
   return position;
}
int main(void){
   int n = 64;
   if(!isPowerOfTwo(n))
      cout<<"Invalid Number!";
   else
      cout<<"The position of the number "<<n<<" is
      "<<findPostionOfSetBit(n);
   return 0;
}
The position of the number 64 is 7
One more method to solve the problem is using math formulas. We know that,
2i = n, where n is the number
and i is the position of the number
The values of i here can be found using the formula,
i = log2(n)
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
bool isPowerOfTwo(unsigned n) {
   if(n>0) {
      while(n%2 == 0)
         n/=2;
      if(n == 1)
         return true;
   }
   if(n == 0 || n != 1)
      return false;
   return false;
}
int findPostionOfSetBit(unsigned n) {
   unsigned position = log2(n) + 1; ;
   return position;
}
int main(void){
   int n = 64;
   if(!isPowerOfTwo(n))
      cout<<"Invalid Number!";
   else
      cout<<"The position of the number "<<n<<" is "<<findPostionOfSetBit(n);
   return 0;
}
The position of the number 64 is 7
C program to search an array element using Pointers.

Write a C program to search an element from an array at runtime by the user and the result to be displayed on the screen after search. If the searching element is not in an array then, we need to search element is not found.
An array is used to hold the group of common elements under one name
The array operations are as follows −
Insert
Delete
Search
Refer an algorithm to search the elements into an array with the help of pointers −
Step 1 − Declare and read the number of elements.
Step 2 − Declare and read the array size at runtime.
Step 3 − Input the array elements.
Step 4 − Declare a pointer variable.
Step 5 − Allocate the memory dynamically at runtime.
Step 6 − Enter an element that to be searched.
Step 7 − Check if an element is present in an array by traversing. If an element is found display "Yes", otherwise "No".
Size of array is: 5
The array elements are as follows:
1 2 3 4 5
Enter the element to be searched: 4
The output is as follows −
4 is present in the array
Following is the C program to delete the elements into an array with the help of pointers −
 Live Demo
#include<stdio.h>
int i,l;
int search(int ,int *,int);
int main(){
   int n,m;
   printf("enter the size of array:");
   scanf("%d",&n);
   int a[n];
   printf("enter the elements:\n");
   for(i=0;i<n;i++){
      scanf("%d",&a[i]);
   }
   printf("enter the element to be searched:");
   scanf("%d",&m);
   search(n,a,m);
   return 0;
}
int search(int n,int *a,int m){
   for(i=0;i<n;i++){
      if(m==a[i]){
         l=1;
         break;
      }
   }
   if(l==1){
      printf("%d is present in the array",m);
   } else {
      printf("%d is not present in the array",m);
   }
}
When the above program is executed, it produces the following output −
Run 1:
enter the size of array:5
enter the elements:
14
12
11
45
23
enter the element to be searched:11
11 is present in the array
Run 2:
enter the size of array:3
enter the elements:
12
13
14
enter the element to be searched:45
45 is not present in the array
Accessing Hash Elements in Perl

When accessing individual elements from a hash in Perl, you must prefix the variable with a dollar sign ($) and then append the element key within curly brackets after the name of the variable. For example −
 Live Demo
#!/usr/bin/perl
%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40);
print "$data{'John Paul'}\n";
print "$data{'Lisa'}\n";
print "$data{'Kumar'}\n";
This will produce the following result −
45
30
40
Rotating an array - JavaScript

Let’s say, we are required to write a JavaScript function that takes in an array and a number n and rotates the array by n elements
For example: If the input array is −
const arr = [12, 6, 43, 5, 7, 2, 5];
and number n is 3,
Then the output should be −
const output = [5, 7, 2, 5, 12, 6, 43];
Let’s write the code for this function −
Following is the code −
// rotation
const arr = [12, 6, 43, 5, 7, 2, 5];
const rotateByOne = arr => {
   for(let i = 0; i < arr.length-1; i++){
      temp = arr[i];
      arr[i] = arr[i+1];
      arr[i+1] = temp;
   };
}
Array.prototype.rotateBy = function(n){
const { length: l } = this;
   if(n >= l){
       return;
   };
   for(let i = 0; i < n; i++){
       rotateByOne(this);
   };
};
const a = [1,2,3,4,5,6,7];
a.rotateBy(2);
console.log(a);
Following is the output in the console −
[
 3, 4, 5, 6,
 7, 1, 2
]
JavaScript SyntaxError - Illegal character - GeeksforGeeks

23 Jul, 2020
This JavaScript exception illegal character occurs if there is an invalid or unexpected token that doesn’t belong there in the code.
Message:
SyntaxError: Invalid character (Edge)
SyntaxError: illegal character (Firefox)
SyntaxError: Invalid or unexpected token (Chrome)

Error Type:
SyntaxError

Cause of Error: There is an invalid or unexpected token that doesn’t belong there in the code. Check the code for mismatches like a minus sign ( – ) and a dash ( – ) or simple quotes ( ” ) vs non-standard quotation marks ( “ ).
Example 1: In this example, there is not any mismatch, So the error has not occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>      // Valid token         var GFG_colors = ['#002', '#353', '#665'];       document.write(GFG_colors)    </script></body></html>
Output:
#002,#353,#665

Example 2: In this example, there is a token mismatch, So the error has occurred.
HTML
<!DOCTYPE html><html><head>    <title>Syntax Error</title></head><body>    <script>      // Invalid Token      var GFG_colors = ['#002', '#353', '#665'];       document.write(GFG_colors)    </script></body></html>
Output(in console):
SyntaxError: Invalid or unexpected token

JavaScript-Errors
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Read whole ASCII file into C++ std::string

This is a simple way to read whole ASCII file into std::string in C++ −
Begin
   Declare a file a.txt using file object f of ifstream type to perform read operation.
   Declare a variable str of string type.
   If(f)
      Declare another variable ss of ostringstream type.
      Call rdbuf() fuction to read data of file object.
      Put the data of file object in ss.
      Put the string of ss into the str string.
   Print the value of str.
End.
#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
using namespace std;
int main() {
   ifstream f("a.txt"); //taking file as inputstream
   string str;
   if(f) {
      ostringstream ss;
      ss << f.rdbuf(); // reading data
      str = ss.str();
   }
   cout<<str;
}
a.txt data file containing the text “hi”
hi
Program to check given string is anagram of palindromic or not in Python

Suppose we have a string s, we have to check whether any permutation of s is a palindrome or not.
So, if the input is like s = "admma", then the output will be True, as we can rearrange "admma" to "madam" which is a palindrome.
To solve this, we will follow these steps −
c := a map holding each individual character count of s
count := 0
for each i in list of all values of c, doif i is odd, thenif count is same as 0, thencount := count + 1come out from the loopreturn False
if i is odd, thenif count is same as 0, thencount := count + 1come out from the loopreturn False
if count is same as 0, thencount := count + 1come out from the loop
count := count + 1
come out from the loop
return False
return True
Let us see the following implementation to get better understanding −
 Live Demo
from collections import Counter
class Solution:
   def solve(self, s):
      c = Counter(s)
      count = 0
      for i in c.values():
         if i % 2 != 0:
            if count == 0:
               count += 1
               continue
            return False
      return True
ob = Solution()
s = "admma"
print(ob.solve(s))
"admma"
True
Perl - Data Types

Perl is a loosely typed language and there is no need to specify a type for your data while using in your program. The Perl interpreter will choose the type based on the context of the data itself.
Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars, also known as associative arrays. Here is a little detail about these data types.
Scalar
Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters.
Arrays
Arrays are ordered lists of scalars that you access with a numeric index, which starts with 0. They are preceded by an "at" sign (@).
Hashes
Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%).
Perl stores all the numbers internally as either signed integers or double-precision floating-point values. Numeric literals are specified in any of the following floating-point or integer formats −
Strings are sequences of characters. They are usually alphanumeric values delimited by either single (') or double (") quotes. They work much like UNIX shell quotes where you can use single quoted strings and double quoted strings.
Double-quoted string literals allow variable interpolation, and single-quoted strings are not. There are certain characters when they are proceeded by a back slash, have special meaning and they are used to represent like newline (\n) or tab (\t).
You can embed newlines or any of the following Escape sequences directly in your double quoted strings −
Let's see again how strings behave with single quotation and double quotation. Here we will use string escapes mentioned in the above table and will make use of the scalar variable to assign string values.
#!/usr/bin/perl

# This is case of interpolation.
$str = "Welcome to \ntutorialspoint.com!";
print "$str\n";

# This is case of non-interpolation.
$str = 'Welcome to \ntutorialspoint.com!';
print "$str\n";

# Only W will become upper case.
$str = "\uwelcome to tutorialspoint.com!";
print "$str\n";

# Whole line will become capital.
$str = "\UWelcome to tutorialspoint.com!";
print "$str\n";

# A portion of line will become capital.
$str = "Welcome to \Ututorialspoint\E.com!"; 
print "$str\n";

# Backsalash non alpha-numeric including spaces.
$str = "\QWelcome to tutorialspoint's family";
print "$str\n";
This will produce the following result −
Welcome to
tutorialspoint.com!
Welcome to \ntutorialspoint.com!
Welcome to tutorialspoint.com!
WELCOME TO TUTORIALSPOINT.COM!
Welcome to TUTORIALSPOINT.com!
Welcome\ to\ tutorialspoint\'s\ family


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
How to get current thread id in android?

Before getting into example, we should know what thread is. A thread is a lightweight sub-process,it going to do back ground operations without interrupt to ui. This example demonstrate about How to get current thread id 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"?>
<LinearLayout 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"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="100dp"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken textview. It contains information about current thread id.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   TextView textView;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      textView.setText("Current thread: " + Thread.currentThread().getId());
   }
}
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 −
In the above result, it is showing current thread id.
Click here to download the project code
Constructor Delegation in C++

Here we will see what is the constructor delegation? When a constructor calls other constructor of the same class, then it is called the constructor delegation. This feature is present from C++11.
Let us see the following program, and try to analyze what are the difficulties in this code.
#include <iostream>
using namespace std;
class MyClass {
   int a, b, c;
   public:
   MyClass(){
      a = b = c = 0;
   }
   MyClass(int c) {
      // Initializing a and b are redundent, only c initialization is needed here
      a = 0;
      b = 0;
      this->c = c;
   }
   void display(){
      cout << "a : " << a << ", b : " << b << ", c : " << c;
   }
};
main() {
   MyClass my_obj(5);
   my_obj.display();
}
a : 0, b : 0, c : 5
Here we can see that the code is working fine, but there is some redundant code. The non-parameterized constructor can set the values of a and b to 1. So if we use the first constructor into the second one, then it will be more effective. For this reason, we have to use the method called constructor delegation.
#include <iostream>
using namespace std;
class MyClass {
   int a, b, c;
   public:
   MyClass(){
      a = b = c = 0;
   }
   MyClass(int c) : MyClass(){ //using constructor delegation
      this->c = c;
   }
   void display(){
      cout << "a : " << a << ", b : " << b << ", c : " << c;
   }
};
main() {
   MyClass my_obj(5);
   my_obj.display();
}
a : 0, b : 0, c : 5
Print 1 to 100 in C++, without loop and recursion

There are several methods to print numbers without using loops like by using recursive function, goto statement and creating a function outside main() function.
Here is an example to print numbers using goto statement in C++ language,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main() {
   int count=1;
   int x;
   cout << "Enter the max value of x : ";
   cin >> x;
   PRINT:
   cout << " " << count;
   count++;
   if(count<=x)
   goto PRINT;
   return 0;
}
Enter the max value of x : 1
In the above program, we used GOTO statement to print the numbers from 1 to 100 without using loops and recursion.
PRINT:
cout << " " << count;
count++;
if(count<=x)
goto PRINT;
Java Generics - Lower Bounded Wildcards

The question mark (?), represents the wildcard, stands for unknown type in generics. There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Integer or its superclasses like Number.
To declare a lower bounded Wildcard parameter, list the ?, followed by the super keyword, followed by its lower bound.
Following example illustrates how super is used to specify an lower bound wildcard.
package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class GenericsTester {

   public static void addCat(List<? super Cat> catList) {
      catList.add(new RedCat());
      System.out.println("Cat Added");
   }

   public static void main(String[] args) {
      List<Animal> animalList= new ArrayList<Animal>();
      List<Cat> catList= new ArrayList<Cat>();
      List<RedCat> redCatList= new ArrayList<RedCat>();
      List<Dog> dogList= new ArrayList<Dog>();

      //add list of super class Animal of Cat class
      addCat(animalList);

      //add list of Cat class
      addCat(catList);

      //compile time error
      //can not add list of subclass RedCat of Cat class
      //addCat(redCatList);

      //compile time error
      //can not add list of subclass Dog of Superclass Animal of Cat class
      //addCat.addMethod(dogList); 
   }
}
class Animal {}

class Cat extends Animal {}

class RedCat extends Cat {}

class Dog extends Animal {}
This will produce the following result −
Cat Added
Cat 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
Python | sympy.cancel() method - GeeksforGeeks

20 Jun, 2019
With the help of sympy.cancel() method, we are able to any rational function and put it into a standard canonical form i.e p/q.
Syntax : sympy.cancel()Return : Return the canonical expression of any rational function.
Example #1 :In the given example, we can see that by using sympy.cancel() method, we can find the canonical form of any rational number i.e (p/q).
# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = (x**2 + 2 * x + 1)/(x**2 + x)   # Using sympy.collect() methodgfg_exp = cancel(gfg_exp)   print(gfg_exp)
Output :
(x + 1)/x
Example #2 :
# import sympyfrom sympy import * x, y, z = symbols('x y z')gfg_exp = 1 / x + (3 * x / 2 - 2)/(x - 4)   # Using sympy.collect() methodgfg_exp = cancel(gfg_exp)   print(gfg_exp)
Output :
(3*x**2 – 2*x – 8)/(2*x**2 – 8*x)
SymPy
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to count specific characters present in the slice in Golang? - GeeksforGeeks

26 Aug, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice of bytes, you can count the elements present in it with the help of Count function. This function returns the total number of elements or the total number of some specified element available in the given slice. This function is defined under the bytes package so, you have to import bytes package in your program for accessing Count function.
Syntax:
func Count(slice_1, sep_slice []byte) int
If the sep_slice is empty slice, then this function returns 1 + the number of UTF-8-encoded code points present in the slice_1.
Example:
// Go program to illustrate how to// count the elements of the slicepackage main  import (    "bytes"    "fmt")  func main() {      // Creating and initializing     // slices of bytes    // Using shorthand declaration    slice_1 := []byte{'A', 'N', 'M',            'A', 'P', 'A', 'A', 'W'}          slice_2 := []byte{'g', 'e', 'e', 'k', 's'}      // Counting elements in the given slices    // Using Count function    res1 := bytes.Count(slice_1, []byte{'A'})    res2 := bytes.Count(slice_2, []byte{'e'})    res3 := bytes.Count([]byte("GeeksforGeeks"), []byte("ks"))    res4 := bytes.Count([]byte("Geeks"), []byte(""))    res5 := bytes.Count(slice_1, []byte(""))      // Displaying results    fmt.Println("Result 1:", res1)    fmt.Println("Result 2:", res2)    fmt.Println("Result 3:", res3)    fmt.Println("Result 4:", res4)    fmt.Println("Result 5:", res5)  }
Output:
Result 1: 4
Result 2: 2
Result 3: 2
Result 4: 6
Result 5: 9

Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Golang Maps
Slices in Golang
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
Lodash _.differenceBy() Method - GeeksforGeeks

25 Mar, 2022
The _.differenceBy() method is used to remove the values from the original array by iterating over each element in the array by using the Iterate function. It is almost same as _.difference() function. 
Syntax:
lodash.differenceBy(array, [values], [iterate=_.identity])
Parameters: This function accepts three parameters as mention above and describe below
array: This is the array from which the values are to be removed.
values: It is the Array of values that is to be removed from the original array.
Iterate: This is the function that iterate over each element.
Note: If the iterate function is not given then _.differenceBy() function act as _.difference() function.   
Return Value: This function returns an array. 
Example 1:
Javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [1, 2, 3, 4.2] // Array to be subtractedlet val = [2, 3, 3, 5] // New Array after _.differenceBy()// method where Math.double is the// comparable functionlet newArray = _.differenceBy(    array1, val, Math.double); // Printing the original arrayconsole.log("Before : ", array1); // Printing the outputconsole.log("After : ", newArray);
Output:
Example 2:
Javascript
// Requiring the lodash libraryconst _ = require("lodash"); // Original arraylet array1 = [1, 2, 3, 4.2] // Value array to be subtractedlet val = [2, 3, 4, 5] // new Array after _.differenceBy()// method where Math.double is the// comparable functionlet newArray1 = _.differenceBy(    array1, val, Math.floor); // New Array after _.differenceBy function// where no comparable function is givenlet newArray2 = _.differenceBy(array1, val); // Printing the original arrayconsole.log("Before : ", array1); // printing the outputconsole.log("When compare funct is given: ",        newArray1); // Printing the outputconsole.log("When compare funct is not given: ",        newArray2);
Output:
sumitgumber28
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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 calculate the number of days between two dates in javascript?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to Perform SQL Join on Multiple Columns in Same Table? - GeeksforGeeks

14 Nov, 2021
In SQL, for extracting valuable data, we need to perform self join within the same table. Self-join is a simple cross-product followed by a condition. An illustration of the same is shown in the below article. For this article, we will be using the Microsoft SQL Server as our database.
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks.
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command.
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table CORPORATE inside the database GeeksForGeeks. This table has 4 columns namely E_NAME, E_ID, E_DEPT, and E_LOC containing the name, id, department, and location of various employees.
Query:
CREATE TABLE CORPORATE(
E_NAME VARCHAR(10),
E_ID INT,
E_DEPT VARCHAR(10),
E_LOC VARCHAR(10));
Output:
Step 4: Describe the structure of the table CORPORATE.
Query:
EXEC SP_COLUMNS CORPORATE;
Output:
Step 5: Insert 5 rows into the CORPORATE table.
Query:
INSERT INTO CORPORATE VALUES('RAM',1,'HR','DELHI');
INSERT INTO CORPORATE VALUES('RAM',1,'SALES','DELHI');
INSERT INTO CORPORATE VALUES('VARUN',2,'IT','BANGALORE');
INSERT INTO CORPORATE VALUES('VARUN',2,'MARKETING','HYDERABAD');
INSERT INTO CORPORATE VALUES('RAVI',3,'FINANCE','KOCHI');
INSERT INTO CORPORATE VALUES('RAVI',3,'FINANCE','TRIVANDRUM');
Output:
Step 6: Display all the rows of the CORPORATE table.
Query:
SELECT * FROM CORPORATE;
Output:
Step 7: Retrieve the details of all the employees who have worked in at least 2 departments and at least 2 locations.
Note: Use of AS for making 2 aliases of the table CORPORATE with C1 and C2 for comparing the IDs, departments, and locations of the employees.
Query:
SELECT C1.E_NAME,C1.E_ID,C1.E_DEPT,C1.E_LOC FROM
CORPORATE AS C1,CORPORATE AS C2 WHERE C1.E_ID=C2.E_ID 
AND C1.E_DEPT<>C2.E_DEPT AND C1.E_LOC<>C2.E_LOC;
Output:
Note: Here RAM is not displayed although he has worked at 2 different departments as his location was the same. Similarly, RAVI is not displayed although he has worked at 2 different locations as his department was the same.
Step 8: To display just the name(s) of the employees who have worked in at least 2 departments and at least 2 locations, use SELECT just for the E_NAME column and keep that is DISTINCT to avoid redundant rows.
Query:
SELECT DISTINCT(C1.E_NAME) FROM CORPORATE
AS C1,CORPORATE AS C2 WHERE C1.E_ID=C2.E_ID
AND C1.E_DEPT<>C2.E_DEPT AND C1.E_LOC<>C2.E_LOC;
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
How to count number of visits to a website using Express.js ? - GeeksforGeeks

01 Jul, 2021
Session management can be done in node.js by using the express-session module. It helps in saving the data in the key-value form. In this article, we will see how to count the Number of views in Express Session in Express Js.
Prerequisites:
Basic knowledge of  Node.
Node.js installed (version 12+).
npm installed (version 6+).
To set up Node Project in Editor you can see here.
Installing requires modules:
npm install express
npm install express-session
 
Call API:
var session = require('express-session')
Example: This example illustrates the above approach.
app.js
// Call Express Api.var express=require('express'),  // Call express Session Api.session = require('express-session'),  app=express();  // Session Setupapp.use (    session ({          // It holds the secret key for session        secret: "I am girl",          // Forces the session to be saved        // back to the session store        resave: true,                            // Forces a session that is "uninitialized"        // to be saved to the store        saveUninitialized: false,        cookie: {    }));  // Get function in which send session as routes.app.get('/session', function(req, res, next) {      if (req.session.views) {                // Increment the number of views.      req.session.views++        // Print the views.      res.write('<p> No. of views: '           + req.session.views + '</p>')       res.end()    } else {      req.session.views = 1      res.end(' New session is started')    }  })  // The server object listens on port 3000.app.listen(3000,function(){    console.log("Express Started on Port 3000");});
Run index.js file using the below command.
node app.js
Now to set your session, just open the browser and type this URL .
http://localhost:3000/session
Output:
Express.js
NodeJS-Questions
Web technologies
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
jQuery | event.target Property with Example - GeeksforGeeks

12 Feb, 2019
The event.target is an inbuilt property in jQuery which is used to find which DOM element will start the event.Syntax:
event.target

Parameter: It does not accept any parameter because it is a property not a function.Return Value: It returns which DOM element triggered the event.
jQuery code to show the working of event.target Property property:
<html>  <head>    <style>        span,        strong,        p {            padding: 8px;            display: block;            border: 2px solid green;            width: 50%;            margin: 10px;        }                  #output {            margin: 10px;            padding: 10px;            width: 100px;            border: 2px solid green;            display: block;        }    </style>    <script src="https://code.jquery.com/jquery-1.10.2.js">    </script></head>  <body>    <div>        <p>            <strong><span>click Here !</span></strong>        </p>    </div>    <!-- output will show inside this block -->    <div id="output"></div>    <!-- jQuery code to show working of this property -->    <script>        $("body").click(function(event) {            $("#output").html("clicked: " + event.target.nodeName);        });    </script></body>  </html>
Output:Before clicking anywhere-
After clicking inside of the p element-
After clicking inside of the STRONG element-
After clicking inside of the SPAN element-
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
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 ?
JQuery | Set the value of an input text field
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
How to fetch data from JSON file and display in HTML table using jQuery ?
How to create a CSS rule or class at runtime using jQuery ? - GeeksforGeeks

15 Jan, 2020
It’s a common practice to write a CSS file for our HTML. Those are called static CSS. When we want to create our Cascading Style Sheet rule at runtime, we need jQuery. The jQuery enables us to apply styles to our HTML dynamically.
The CSS rules once written can be stored in a variable and used multiple times wherever needed.We use jQuery’s css(“arrtibute1”, “value1”).
Below example illustrates the approach:
Example 1:
<!DOCTYPE html><html>  <head>    <title>CSS Rules with JQuery</title>    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous">    </script></head>  <body>    <div id="myId">        <h1>GeeksforGeeks</h1>    </div>      <div class="myclass">        <h1>A Computer Science Portal for Geeks</h1>    </div>      <script>          // Here 'my_css' variable stores the Style        var my_css = {            backgroundColor: "red",            color: "rgb(0,255,0)"        }        $("#myId").css(my_css);          var my_class_css = {            background: "green",            color: "rgb(255,255,255)"        }        $(".myclass").css(my_class_css);    </script>  </body>  </html>
Output:
Example 2: It also has an alternative where you can directly use a CSS-like styling code instead of a JavaScript-like styling.
<!DOCTYPE html><html>  <head>    <title>CSS Rules with JQuery</title>    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous">  </script></head>  <body>    <div id="myId">        <h1>Without Coding</h1>    </div>      <div class="myclass">        <h1>There are no Geeks</h1>    </div>      <script>        $(document).ready(function() {              // Build your CSS.            var body_css = {                "background-color": "rgb(0,0,0)",                "font-weight": "",                "color": "rgb(255,255,255)"            }              $("body").css(body_css);        });    </script>  </body>  </html>
Output:
CSS-Misc
HTML-Misc
jQuery-Misc
Picked
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
jQuery | attr() Method
Difference Between JavaScript and jQuery
jQuery | parent() & parents() with Examples
How to submit a form using ajax in jQuery ?
jQuery | focus() with Examples
C/C++ Program for Greedy Algorithm to find Minimum number of Coins - GeeksforGeeks

02 Jan, 2019
Given a value V, if we want to make change for V Rs, and we have infinite supply of each of the denominations in Indian currency, i.e., we have infinite supply of { 1, 2, 5, 10, 20, 50, 100, 500, 1000} valued coins/notes, what is the minimum number of coins and/or notes needed to make the change?
Examples:
Input: V = 70
Output: 2
We need a 50 Rs note and a 20 Rs note.

Input: V = 121
Output: 3
We need a 100 Rs note, a 20 Rs note and a 
1 Rs coin. 
C/C++
// C++ program to find minimum number of denominations#include <bits/stdc++.h>using namespace std;  // All denominations of Indian Currencyint deno[] = { 1, 2, 5, 10, 20, 50, 100, 500, 1000 };int n = sizeof(deno) / sizeof(deno[0]);  // Driver programvoid findMin(int V){    // Initialize result    vector<int> ans;      // Traverse through all denomination    for (int i = n - 1; i >= 0; i--) {        // Find denominations        while (V >= deno[i]) {            V -= deno[i];            ans.push_back(deno[i]);        }    }      // Print result    for (int i = 0; i < ans.size(); i++)        cout << ans[i] << "  ";}  // Driver programint main(){    int n = 93;    cout << "Following is minimal number of change for " << n << " is ";    findMin(n);    return 0;}
Following is minimal number of change for 93 is 50  20  20  2  1

Please refer complete article on Greedy Algorithm to find Minimum number of Coins for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Exit codes in C/C++ with Examples
C program to find the length of a string
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Regular expressions in C
Create n-child process from same parent process using fork() in C
Conditional wait and signal in multi-threading
How to store words in an array in C?
How to Place Legend Outside of the Plot in Matplotlib?

03 Jan, 2021
In this article, we will see how to place legend outside the Plot in Matplotlib? Let’s discuss some concepts :
Matplotlib : Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
Legend : A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes. The attribute Loc in legend() is used to specify the location of the legend. Default value of loc is loc=”best” (upper left).
Here, first we will see why placing of legend outside is required.
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt  # create datax=np.linspace(-20, 20, 1000)  # plot the graphsplt.plot(x,np.sin(x))plt.plot(x,np.cos(x))  # add legendsplt.legend(["Sine","Cosine"])  plt.show()
Output:
Legends overlap the graph (incomplete information)
As, we can see that the above figure legends are overlapped on graph i.e; incomplete information. To solve this problem we need to place the legend outside the plot.
Import LibrariesCreate/ Load dataMake plotsAdd legend outside the plot.
Import Libraries
Create/ Load data
Make plots
Add legend outside the plot.
Example 1: (Right Side)
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt  # create datax=np.linspace(-20, 20, 1000)  # plot the graphsplt.plot(x,np.sin(x))plt.plot(x,np.cos(x))  # add legends and set its box positionplt.legend(["Sine","Cosine"],           bbox_to_anchor = (1.05, 0.6))  plt.show()
Output:
Example 2: ( At top)
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt  # create datax=np.linspace(-20, 20, 1000)  # plot the graphsplt.plot(x, np.sin(x))plt.plot(x, np.cos(x))  # add legends and set its box positionplt.legend(["Sine", "Cosine"],           bbox_to_anchor=(0.6, 1.2))  plt.show()
Output :
Example 3: ( With subplots)
Python3
# importing packagesimport numpy as npimport matplotlib.pyplot as plt  # create datax = np.linspace(-5, 5, 1000)colors=[['c','g'], ['y','r']]  # make subplot and plots the grpahsfig, ax = plt.subplots(2, 2)for i in range(2):    ax[0][i].plot(x, np.sin(x+i),                  color = colors[0][i],                  label = "y=sin(x+{})".format(i))          ax[1][i].plot(x, np.sin(x+i),                   color = colors[1][i],                  label = "y=sin(x+{})".format(i))      # set legend positionfig.legend(bbox_to_anchor=(1.3, 0.6))  # set spacing to subplotsfig.tight_layout()  plt.show()
Output :
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.