code-rag-bench/online-tutorials huggingface dataset:
PostgreSQL – NTILE Function

08 Oct, 2021
In PostgreSQL, the NTILE() function is used to divide ordered rows in the partition into a specified number of ranked buckets. Buckets are nothing but ranked groups.
The syntax of the NTILE() looks like below:
Syntax:
NTILE(buckets) OVER (
    [PARTITION BY partition_expression, ... ]
    [ORDER BY sort_expression [ASC | DESC], ...]
)
Let’s analyze the above syntax:
The buckets are the number of ranked groups. It can either be a number or an expression but the expression must evaluate a positive integer value.
The PARTITION BY is an optional clause distributes rows into partitions.
The ORDER BY clause is used to sort rows in each partition.
Example 1:
First, create a table named sales_stats that stores the  sales revenue by employees:
CREATE TABLE sales_stats(
    name VARCHAR(100) NOT NULL,
    year SMALLINT NOT NULL CHECK (year > 0),
    amount DECIMAL(10, 2) CHECK (amount >= 0),
    PRIMARY KEY (name, year)
);
Second, insert some rows into the sales_stats table:
INSERT INTO 
    sales_stats(name, year, amount)
VALUES
    ('Raju kumar', 2018, 120000),
    ('Alibaba', 2018, 110000),
    ('Gabbar Singh', 2018, 150000),
    ('Kadar Khan', 2018, 30000),
    ('Amrish Puri', 2018, 200000),
    ('Raju kumar', 2019, 150000),
    ('Alibaba', 2019, 130000),
    ('Gabbar Singh', 2019, 180000),
    ('Kadar Khan', 2019, 25000),
    ('Amrish Puri', 2019, 270000);
The below statement uses the NTILE() function to distribute rows into 3 buckets:
SELECT 
    name,
    amount,
    NTILE(3) OVER(
        ORDER BY amount
    )
FROM
    sales_stats
WHERE
    year = 2019;
Output:
Example 2:
The below query uses the NTILE() function to divide rows in the sales_stats table into two partitions and 3 buckets for each:
SELECT 
    name,
    amount,
    NTILE(3) OVER(
        PARTITION BY year
        ORDER BY amount
    )
FROM
    sales_stats;
Output:
sooda367
PostgreSQL-function
PostgreSQL-Window-function
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL – Temporary Table

28 Aug, 2020
A temporary table, as the name implies, is a short-lived table that exists for the duration of a database session. PostgreSQL automatically drops the temporary tables at the end of a session or a transaction.
Syntax:
CREATE TEMPORARY TABLE temp_table(
   ...
);

or,

CREATE TEMP TABLE temp_table(
   ...
);
A temporary table is visible only to the session that creates it. In other words, it remains invisible to other sessions.
Example:
First, we create a new database test as follows:
CREATE DATABASE test;
Next, create a temporary table named mytemp as follows:
CREATE TEMP TABLE mytemp(c INT);
Then, launch another session that connects to the test database and query data from the mytemp table:
SELECT * FROM mytemp;
It will raise an error as the second session cannot see mytemp table. So, quit all sessions after that as follows:
\q
Finally, login to the database server again and query data from the mytemp table:
SELECT * FROM mytemp;
The mytemp table does not exist because it has been dropped automatically when the session ended, therefore, PostgreSQL issued an error.
Output:
postgreSQL-managing-table
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.pipe() method

29 Jul, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.
os.pipe() method in Python is used to create a pipe. A pipe is a method to pass information from one process to another process. It offers only one-way communication and the passed information is held by the system until it is read by the receiving process.
Syntax: os.pipe()
Parameter: No parameter is required
Return Type: This method returns a pair of file descriptors (r, w) usable for reading and writing, respectively.
# Python program to explain os.pipe() method   # importing os module import os    # Create a piper, w = os.pipe()  # The returned file descriptor r and w# can be used for reading and# writing respectively.  # We will create a child process# and using these file descriptor# the parent process will write # some text and child process will# read the text written by the parent process  # Create a child processpid = os.fork()  # pid greater than 0 represents# the parent processif pid > 0:      # This is the parent process     # Closes file descriptor r    os.close(r)      # Write some text to file descriptor w     print("Parent process is writing")    text = b"Hello child process"    os.write(w, text)    print("Written text:", text.decode())        else:      # This is the parent process     # Closes file descriptor w    os.close(w)      # Read the text written by parent process    print("\nChild Process is reading")    r = os.fdopen(r)    print("Read text:", r.read())
Parent process is writing
Text written: Hello child process

Child Process is reading
Text read: Hello child process

shubham_singh
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to divide text into two columns layout using CSS ?

01 Sep, 2020
The purpose of this article is to divide the text into two columns by using the CSS column property. This property is used to set the number of columns and the width of these columns.
Syntax:
columns: column-width columns-count | auto | initial | inherit;
Example:
HTML
      <!DOCTYPE html><html>  <head>    <style>        body {            text-align: center;            color: green;        }          .GFG {            -webkit-columns: 40px 2;            /* Chrome, Safari, Opera */            -moz-columns: 60px 2;            /* Firefox */            columns: 60px 2;        }    </style></head>  <body>      <h1>        How to divide the text in the division        element into two columns using css?    </h1>      <div class="GFG">        <h2>Welcome to the world of Geeks!!</h2>        How many times were you frustrated while        looking out for a good collection of        programming/algorithm/interview questions?        What did you expect and what did you get?        This portal has been created to provide well        written, well thought and well-explained        solutions for selected questions.          <p>            <strong>Our team includes:</strong>        <p>            Sandeep Jain: An IIT Roorkee alumnus            and founder of GeeksforGeeks. He loves            to solve programming problems in most            efficient ways. Apart from GeeksforGeeks,            he has worked with DE Shaw and Co. as a            software developer and JIIT Noida as an            assistant professor.        </p>          <p>            Vaibhav Bajpai: Amazed by computer            science, he is a technology enthusiast who            enjoys being a part of a development. Off            from work, you canfind him in love with            movies, food, and friends.        </p>          <p>            Shikhar Goel: A Computer Science graduate            who likes to make things simpler. When he's            not working, you can find him surfing the web,            learning facts, tricks and life hacks.            He also enjoys movies in his leisure time.        </p>          <p>            Dharmesh Singh: A software developer who            is always trying to push boundaries in search            of great breakthroughs. Off from his desk,            you can find him cheering up his buddies            and enjoying life.        </p>          <p>            Shubham Baranwal: A passionate developer            who always tries to learn new technology and            software. In his free time, either he reads            some articles or learns some other stuff.        </p>    </div></body>  </html>                    
Output:
Supported Browsers are listed below:
Google Chrome 43.0
Internet Explorer 10.0
Firefox 16.0
Opera 30.0
Safari 9.0
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
String concatenation in Julia

25 Aug, 2020
String concatenation in Julia is a way of appending two or more strings into a single string whether it is character by character or using some special characters end to end. There are many ways to perform string concatenation.
Example: 
Input: str1 = 'Geeks'
str2 = 'for'
str3 = 'Geeks' 

Output: 'GeeksforGeeks'

The different ways in which we can concatenate strings in Julia are : 
Using * operator
Using ^ operator
Using string() function
It is used to concatenate different strings and/or characters into a single string. We can concatenate two or more strings in Julia using * operator.
Example: 
Julia
# creating string 1s1 = "Hello "  # creating string 2s2 = "World !"  # concatenating the stringss = s1 * s2  # printing the concatenated stringprint(s)
Output: 
This operator repeats the specified string with the specified number of times. It is used when there is a need to concatenate a single string multiple times.
Example: 
Julia
# creating strings1 = "Hello "  # concatenating the strings = s1 ^ 5  # printing the concatenated stringprint(s)
Output: 
Julia provides a pre-defined string() function for the concatenation of strings. This function takes all the strings to be concatenated as arguments and returns a single concatenated string. 
string(string1, string2, string3, string4, ...)
Example 1: 
Julia
# creating string 1s1 = "Hello "  # creating string 2s2 = "World !"  # concatenating the stringss = string(s1, s2)  # printing the concatenated stringprint(s)
Output: 
Example 2: 
Julia
# creating 3 stringss1 = "I"s2 = "Love"s3 = "Julia"  # concatenating the stringsstring(s1, " ", s2, " ", s3)  # printing the concatenated stringprint(s)
Output:
Concatenated strings can be stored in a File by using the write() function. Here, firstly the concatenation is done and then the file is first opened into ‘w’ i.e. write mode and the concatenated string is stored with the use of write().
Example: 
Julia
# creating 3 stringss1 = "I"s2 = "Love"s3 = "Julia"  # concatenating the stringss = s1 * " " * s2 * " " * s3  # storing string s in a fileopen("myfile.txt", "w") do io           write(io, s)     end;
Output: 
Picked
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is difference between internal and private modifiers in C#?

Internal access specifier allows a class to expose its member variables and member functions to other functions and objects in the current assembly.
Any member with internal access specifier can be accessed from any class or method defined within the application in which the member is defined.
The following is an example −
using System;

namespace RectangleApplication {
   class Rectangle {
      //member variables
      internal double length;
      internal double width;

      double GetArea() {
         return length * width;
      }

      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }//end class Rectangle

   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.length = 4.5;
         r.width = 3.5;
         r.Display();
         Console.ReadLine();
      }
   }
}
Private access specifier allows a class to hide its member variables and member functions from other functions and objects. Only functions of the same class can access its private members.
The following is an example −
using System;

namespace RectangleApplication {
   class Rectangle {
      private double length;
      private double width;

      public void Acceptdetails() {
         length = 10;
         width = 15;
      }

      public double GetArea() {
         return length * width;
      }

      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }

   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine();
      }
   }
}
Convert JSON array into normal json in JavaScript

Suppose, we have a JSON array with key/value pair objects like this −
const arr = [{
   "key": "name",
   "value": "john"
},
{
   "key": "number",
   "value": "1234"
},
{
   "key": "price",
   "value": [{
      "item": [{
         "item": [{
            "key": "quantity",
            "value": "20"
         },
         {
            "key": "price",
            "value": "200"
         }]
      }]
   }]
}];
We are required to write a JavaScript function that takes in one such array.
The function should prepare a new array where data is simply listed against key value instead of this complex structure.
Therefore, for the above array, the output should look like this −
const output = {
   "name": "john",
   "number": "1234",
   "price": {
      "quantity": "20",
      "price": "200"
   }
};
The code for this will be −
const arr = [{
   "key": "name",
   "value": "john"
},
{
   "key": "number",
   "value": "1234"
},
{
   "key": "price",
   "value": [{
      "item": [{
         "item": [{
            "key": "quantity",
            "value": "20"
         },
         {
            "key": "price",
            "value": "200"
         }]
      }]
   }]
}];
const simplify = (arr = []) => {
   const res = {};
   const recursiveEmbed = function(el){
      if ('item' in el) {
         el.item.forEach(recursiveEmbed, this);
         return;
      };
      if (Array.isArray(el.value)) {
         this[el.key] = {};
         el.value.forEach(recursiveEmbed, this[el.key]);
         return;
      };
      this[el.key] = el.value;
   };
   arr.forEach(recursiveEmbed, res);
   return res;
};
console.log(simplify(arr));
And the output in the console will be −
{
   name: 'john',
   number: '1234',
   price: { quantity: '20', price: '200' }
}
Material Design Lite - Badges

An MDL badge component is an onscreen notification which can be a number or an icon. It is generally used to emphasize the number of items.
MDL provides a range of CSS classes to apply various predefined visual and behavioral
enhancements to the badges. The following table lists down the available classes and their
effects.
mdl-badge
Identifies element as an MDL badge component. Required for span or link element.
mdl-badge--no-background
Applies open-circle effect to badge and is optional.
mdl-badge--overlap
Makes the badge overlap with its container and is optional.
data-badge="value"
Assigns a string value to badge	used as attribute; required on span or link.
The following example will help you understand the use of the mdl-badge class to add notifications to span and link elements.
The MDL classes given below will be used in this example.
mdl-badge − Identifies element as an MDL badge component.
mdl-badge − Identifies element as an MDL badge component.
data-badge − Assigns a string value to badge. Icons can be assigned to it using HTML symbols.
data-badge − Assigns a string value to badge. Icons can be assigned to it using HTML symbols.
<html>
   <head>
      <script src = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.min.js">
      </script>
      
      <link rel = "stylesheet" 
         href = "https://storage.googleapis.com/code.getmdl.io/1.0.6/material.indigo-pink.min.css">
      <link rel = "stylesheet" 
         href = "https://fonts.googleapis.com/icon?family=Material+Icons">
      <style>
         body {
            padding: 20px;
            background: #fafafa;
            position: relative;
         }
      </style>
   </head>
   
   <body>
      <span class = "material-icons mdl-badge" data-badge = "1">account_box</span>    
      <span class = "material-icons mdl-badge" data-badge = "★">account_box</span>	
      <span class = "mdl-badge" data-badge = "4">Unread Messages</span>
      <span class = "mdl-badge" data-badge = "⚑">Rating</span>
      <a href = "#" class = "mdl-badge" data-badge = "5">Inbox</a>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
fputs() function in PHP

Write to an open file using the fpus() function in PHP. It is an alias of fwrite(). The fputs() function returns the number of bytes written on success. It returns FALSE on failure.
The fputs() function halts at the end of the file or when it reaches the specified length whichever comes first.
fputs(file_pointer, string, length)
file_pointer − A file pointer created using fopen(). Required.
file_pointer − A file pointer created using fopen(). Required.
string − A string to be written. Required.
string − A string to be written. Required.
length − Maximum bytes to write. Optional.
length − Maximum bytes to write. Optional.
The fputs() function returns the number of bytes written on success. It returns FALSE on failure.
<?php
   $file_pointer = fopen("new.txt","w");
   echo fputs($file,"This is demo text!");
   fclose($file_pointer);
?>
The following is the output. It returns the number of bytes written.
18
Let us see another example which writes a specified number of bytes to the file. The content is also read and displayed.
<?php
   $file_pointer = fopen("new.txt","w");
   echo fputs($file,"This is demo text!",4);
   fclose($file_pointer);
   fopen("new.txt", "r");
   echo fread($file_pointer, filesize("new.txt"));
   fclose($file_pointer);
?>
4
Maximum rational number (or fraction) from an array in C++

In this problem, we are given a 2-D array that contains rational numbers
(one in each row). Our task is to create a program to calculate the maximum
rational number (or fraction) from an array in C++.
Problem Description − The 2-D array is of the form [n][2]. Each row has two integer values that denote the value of a and b in the equation of rational number, a/b. We need to find the greatest number out of all these rational numbers.
Let’s take an example to understand the problem,
rat[][] = {
   {3, 2},
   {5, 7},
   {1, 9},
   {11, 4}
}
11 4
The maximum number out of
3/2 , 5/7 , 1/9 , 11/4 is 11/4.
To solve the problem, we need to find the values of the numbers and then
compare their values. But, this might give an error if the difference between
the precision is greater like, if we use float we cannot differentiate between
rational numbers, 34.12313431123, and 34.12313431124.
So, we will use another method to compare values. This is using the LCM of
all denominators and then changing the numerators accordingly. After this,
the comparison of the numerators will return the maximum number.
Program to show the implementation of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
const int n = 4;
int findMaxRatNum(int ratNum[n][2]){
   int numArray[n];
   int LCM = 1;
   int mavVal = 0, index = 0;
   for (int i = 0; i < n; i++)
      LCM = (LCM * ratNum[i][1]) / __gcd(LCM, ratNum[i][1]);
   for (int i = 0; i < n; i++) {
      numArray[i] = (ratNum[i][0]) * (LCM / ratNum[i][1]);
      if (mavVal < numArray[i]) {
         mavVal = numArray[i];
         index = i;
      }
   }
   return index;
}
int main(){
   int ratNum[n][2] = {{3, 2},{5, 7},{1, 9},{11, 4}};
   int i = findMaxRatNum(ratNum);
   cout<<"The maximum rational number from an array is "<<ratNum[i][0]<<"/"<<ratNum[i][1];
}
The maximum rational number from an array is 11/4
string.gsub() function in Lua programming

There are scenarios when we want to change a pattern that we found in a string with our pattern, and in Lua for that we have a famous library function, named the string.gsub() function.
The string.gsub() function has three arguments, the first is the subject string, in which we are trying to replace a substring to another substring, the second argument is the pattern that we want to replace in the given string, and the third argument is the string from which we want to replace the pattern.
string.gsub(x,a,b)
In the above syntax, the x identifier is used to denote the string in which we are trying to replace a pattern, the a identifier is the pattern that we want to replace, and the b identifier is the pattern with which we want to replace the substring that we found.
Now, let’s consider a basic example of the string.gsub() in Lua.
Consider the example shown below −
 Live Demo
s = string.gsub("Lua is good", "good", "great")
print(s)--> Lua is great
Lua is great
Let’s consider one more simple example, so that you understand it completely.
Consider the example shown below −
 Live Demo
s = string.gsub("hello lii", "l", "x")
print(s)
hexxo xii
It should be noted that if we provide a pattern that is not present in the string, then nothing will change, the string will remain the same.
Consider the example shown below −
 Live Demo
s = string.gsub("Lua is good", "ok", "great")
print(s)
Lua is good
There’s also a fourth argument that we can pass in the string.gsub() function and that fourth argument will be used to limit the number of substitutions to be made.
Consider the example shown below −
 Live Demo
s = string.gsub("lua is lua and lua", "lua", "he",2)
print(s)
he is he and lua
Alphanumeric Order by in MySQL for strings mixed with numbers

Let’s say you have a VARCHAR column in a table with values are strings and the numbers are on the right side. For example −
John1023
Carol9871
David9098
Now, consider you want to order by on the basis of these right-side numbers in the entire column. For this, use ORDER BY RIGHT.
Let us first create a table −
mysql> create table DemoTable757 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientId varchar(100)
);
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable757(ClientId) values('John1023');
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable757(ClientId) values('Carol9871');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable757(ClientId) values('David9098');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable757(ClientId) values('Adam9989');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable757(ClientId) values('Bob9789');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable757;
This will produce the following output -
+----+-----------+
| Id | ClientId  |
+----+-----------+
|  1 | John1023  |
|  2 | Carol9871 |
|  3 | David9098 |
|  4 | Adam9989  |
|  5 | Bob9789   |
+----+-----------+
5 rows in set (0.00 sec)
Following is the query for alphanumeric order by in MySQL −
mysql> select Id,ClientId from DemoTable757 order by right(ClientId,4);
This will produce the following output -
+----+-----------+
| Id | ClientId  |
+----+-----------+
|  1 | John1023  |
|  3 | David9098 |
|  5 | Bob9789   |
|  2 | Carol9871 |
|  4 | Adam9989  |
+----+-----------+
5 rows in set (0.00 sec)
AngularJS | angular.uppercase() Function - GeeksforGeeks

16 Apr, 2019
The angular.uppercase() Function in AngularJS is used to convert the string into uppercase. It can be used when user wants to show the text in uppercase instead of lowercase.Syntax:
angular.uppercase(string)
Example: In this example the string is converted into uppercase.
<html ng-app="app"><head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>    <title>angular.uppercase()</title>    </head>    <body style="text-align:center">     <h1 style="color:green">GeeksforGeeks</h1>     <h2>angular.uppercase()</h2>     <div ng-controller="geek">     <br>     <b>Before: </b>{{ string1 }}     <br><br>     <button id="myButton" ng-mousedown="upper()">Click it!     </button>     <br><br>       <b>After: </b>{{ string2 }}     </div>       <script>       var app = angular.module('app', []);       app.controller('geek', function($scope) {       $scope.obj1 =        "geeksforgeeks is the computer science portal for geeks."       $scope.obj2;       $scope.string1 = $scope.obj1;       $scope.upper = function() {       $scope.string2 = angular.uppercase($scope.obj1);       }    });    </script>    </body></html>
Output:Before Click:After Click:
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Angular File Upload
Angular | keyup event
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
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?
CSS3 - Web Fonts

Web fonts are used to allows the fonts in CSS, which are not installed on local system.
TrueType Fonts (TTF)
TrueType is an outline font standard developed by Apple and Microsoft in the late 1980s, It became most common fonts for both windows and MAC operating systems.
OpenType Fonts (OTF)
OpenType is a format for scalable computer fonts and developed by Microsoft
The Web Open Font Format (WOFF)
WOFF is used for develop web page and developed in the year of 2009. Now it is using by W3C recommendation.
SVG Fonts/Shapes
SVG allow SVG fonts within SVG documentation. We can also apply CSS to SVG with font face property.
Embedded OpenType Fonts (EOT)
EOT is used to develop the web pages and it has embedded in webpages so no need to allow 3rd party fonts
Following code shows the sample code of font face −
<html>
   <head>
      <style>
         @font-face {
            font-family: myFirstFont;
            src: url(/css/font/SansationLight.woff);
         }
         div {
            font-family: myFirstFont;
         }
      </Style>
   </head>
   
   <body>
      <div>This is the example of font face with CSS3.</div>
      <p><b>Original Text :</b>This is the example of font face with CSS3.</p>
   </body>
</html>
It will produce the following result −
Original Text :This is the example of font face with CSS3.
The following list contained all the fonts description which are placed in the @font-face rule −
font-family
Used to defines the name of font
src
Used to defines the URL
font-stretch
Used to find, how font should be stretched
font-style
Used to defines the fonts style
font-weight
Used to defines the font weight(boldness)

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Cumulative percentage of a column in Pandas - Python - GeeksforGeeks

15 Mar, 2021
Cumulative Percentage is calculated by the mathematical formula of dividing the cumulative sum of the column by the mathematical sum of all the values and then multiplying the result by 100. This is also applicable in Pandas Data frames.Here, the pre-defined cumsum() and sum() functions are used to compute the cumulative sum and sum of all the values of a column.Syntax: 
df[cum_percent] = 100 * (df[‘column_name’].cumsum()/df[‘column_name’].sum())  
Example 1:
Python3
import pandas as pdimport numpy as np  # Create a DataFramedf1 = {     'Name':['abc','bcd','cde','def','efg','fgh','ghi'],   'Math_score':[52,87,49,74,28,59,48]}  df1 = pd.DataFrame(df1, columns=['Name','Math_score']) # Computing Cumulative Percentagedf1['cum_percent'] = 100*(df1.Math_score.cumsum() / df1.Math_score.sum()) df1
 
 
Output:  
 
 
 
 
Example 2: 
 
Python3
import pandas as pdimport numpy as np  # Create a DataFramedf1 = {     'Name':['abc','bcd','cde','def','efg','fgh','ghi'],   'Math_score':[52,87,49,74,28,59,48],  'Eng_score':[34,67,25,89,92,45,86]}  df1 = pd.DataFrame(df1,columns=['Name','Math_score','Eng_score']) # Computing cumulative Percentagedf1['Eng_cum_percent'] = (df1.Eng_score.cumsum() / df1.Eng_score.sum()) * 100 df1
 
 
Output:  
 
 
arorakashish0911
Python pandas-dataFrame
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 ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to execute multiple select queries in MySQL ?

To execute multiple select queries in MySQL, use the concept of DELIMITER. Let us first create a table −
mysql> create table DemoTable1
(
   Title text
)ENGINE=MyISAM;
Query OK, 0 rows affected (0.30 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1 values('The database MySQL is less popular than MongoDB') ;
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1 values('Java language uses MySQL database');
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable1 values('Node.js uses the MongoDB') ;
Query OK, 1 row affected (0.05 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable1;
This will produce the following output −
+-------------------------------------------------+
| Title                                           |
+-------------------------------------------------+
| The database MySQL is less popular than MongoDB |
| Java language uses MySQL database               |
| Node.js uses the MongoDB                        |
+-------------------------------------------------+
3 rows in set (0.00 sec)
Following is the query to create the second table −
mysql> create table DemoTable2
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY
);
Query OK, 0 rows affected (0.45 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2 values(),(),(),(),(),(),(),(),();
Query OK, 9 rows affected (0.19 sec)
Records: 9 Duplicates: 0 Warnings: 0
Display all records from the table using select statement −
mysql> select *from DemoTable2;
This will produce the following output −
+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
+----+
9 rows in set (0.00 sec)
Following is the query to execute multiple select queries −
mysql> DELIMITER //
mysql> select *from DemoTable1;
select *from DemoTable2;
//
This will produce the following output displaying the result of both the select statements −
+-------------------------------------------------+
| Title                                           |
+-------------------------------------------------+
| The database MySQL is less popular than MongoDB |
| Java language uses MySQL database               |
| Node.js uses the MongoDB                        |
+-------------------------------------------------+
3 rows in set (0.00 sec)
+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
|  6 |
|  7 |
|  8 |
|  9 |
+----+
9 rows in set (0.03 sec)
Programmatically opening URLs in a web browser in Python (tkinter)

Python has a rich library of extensions and modules which are used for multiple purposes. To work with web-based content, Python provides a webbrowser module. The module creates an environment which enables the user to display web-based content in the application. To work with webbrowser, you have to make sure that it is installed in your local machine.
import webbrowser
If the module is not available in your environment, then you can install it using the following command −
pip install webbrowser
Using the webbrowser module in our program, we will open an URL in our web browser. To open the URL in a default browser, we can use the open() function in the module.
# Import the required libraries
import webbrowser

# Add a URL to open in a new window
url= 'https://www.tutorialspoint.com/'

# Open the URL in a new Tab
webbrowser.open_new_tab(url)
Running the above code will open the given URL in a new window of the default browser.
Ant - Executing Java code

You can use Ant to execute the Java code. In the following example, the java class takes in an argument (administrator's email address) and send out an email.
public class NotifyAdministrator {
   public static void main(String[] args) {
      String email = args[0];
      notifyAdministratorviaEmail(email);
      System.out.println("Administrator "+email+" has been notified");
   }
   public static void notifyAdministratorviaEmail(String email {
      //......
   }
}
Here is a simple build that executes this java class.
<?xml version="1.0"?>
<project name="sample" basedir="." default="notify">
   <target name="notify">
      <java fork="true" failonerror="yes" classname="NotifyAdministrator">
         <arg line="admin@test.com"/>
      </java>
   </target>
</project>
When the build is executed, it produces the following outcome −
C:\>ant
Buildfile: C:\build.xml

notify: [java] Administrator admin@test.com has been notified

BUILD SUCCESSFUL
Total time: 1 second
In this example, the java code does a simple thing which is, to send an email. We could have used the built in the Ant task to do that.
However, now that you have got the idea, you can extend your build file to call the java code that performs complicated things. For example: encrypts your source code.

    20 Lectures 
     2 hours 

 Deepti Trivedi

    19 Lectures 
     2.5 hours 

 Deepti Trivedi

    139 Lectures 
     14 hours 

 Er. Himanshu Vasishta

    30 Lectures 
     1.5 hours 

 Pushpendu Mondal

    65 Lectures 
     6.5 hours 

 Ridhi Arora

    10 Lectures 
     2 hours 

 Manish Gupta
 Print
 Add Notes
 Bookmark this page
C Program for Matrix Chain Multiplication

In this problem, we are given a sequence( array) of metrics. our task is to create a C program for Matrix chain multiplication. We need to find a way to multiply these matrixes so that, the minimum number of multiplications is required.
The array of matrices will contain n elements, which define the dimensions of the matrices as, arr[i-1] X arr[i].
Let’s take an example to understand the problem,
array[] = {3, 4, 5, 6}
the matrices will be of the order −
Mat1 = 3X4, Mat2 = 4X5, Mat3 = 5X6
For these three matrices, there can be two ways to multiply,
mat1*(mat2*mat3) -> (3*4*6) + (4*5*6) = 72 + 120 = 192
(mat1*mat2)*mat3 -> (3*4*5) + (3*5*6) = 60 + 90 = 150
The minimum number of mulitplications will be 150 in case of (mat1*mat2)*mat3.
The problem can be solved using dynamic programming as it posses both the properties i.e. optimal substructure and overlapping substructure in dynamic programming.
So here is C Program for Matrix Chain Multiplication using dynamic programming
 Live Demo
#include <stdio.h>
int MatrixChainMultuplication(int arr[], int n) {
   int minMul[n][n];
   int j, q;
   for (int i = 1; i < n; i++)
      minMul[i][i] = 0;
   for (int L = 2; L < n; L++) {
      for (int i = 1; i < n - L + 1; i++) {
         j = i + L - 1;
         minMul[i][j] = 99999999;
         for (int k = i; k <= j - 1; k++) {
            q = minMul[i][k] + minMul[k + 1][j] + arr[i - 1] * arr[k] * arr[j];
            if (q < minMul[i][j])
            minMul[i][j] = q;
         }
      }
   }
   return minMul[1][n - 1];
}
int main(){
   int arr[] = {3, 4, 5, 6, 7, 8};
   int size = sizeof(arr) / sizeof(arr[0]);
   printf("Minimum number of multiplications required for the matrices multiplication is %d ",    MatrixChainMultuplication(arr, size));
   getchar();
   return 0;
}
Minimum number of multiplications required for the matrices multiplication is 444
Display HashMap elements in Java

Create a HashMap −
HashMap hm = new HashMap();
Add elements to the HashMap that we will be displaying afterward −
hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));
hm.put("Physics", new Integer(91));
Now, to display the HashMap elements, use Iterator. The following is an example to display HashMap elements −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Maths", new Integer(98));
      hm.put("Science", new Integer(90));
      hm.put("English", new Integer(97));
      hm.put("Physics", new Integer(91));
      hm.put("Chemistry", new Integer(93));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("Elements: "+hm);
   }
}
Maths: 98
English: 97
Chemistry: 93
Science: 90
Physics: 91
Elements: {Maths=98, English=97, Chemistry=93, Science=90, Physics=91}
PHP 7 - Apache Configuration

Apache uses httpd.conf file for global settings, and the .htaccess file for per-directory access settings. Older versions of Apache split up httpd.conf into three files (access.conf, httpd.conf, and srm.conf), and some users still prefer this arrangement.
Apache server has a very powerful, but slightly complex, configuration system of its own. Learn more about it at the Apache Web site − www.apache.org
The following section describes the settings in httpd.conf that affect PHP directly and cannot be set elsewhere. If you have standard installation then httpd.conf will be found at /etc/httpd/conf:
This value sets the default number of seconds before any HTTP request will time out. If you set PHP's max_execution_time to longer than this value, PHP will keep grinding away but the user may see a 404 error. In safe mode, this value will be ignored; instead, you must use the timeout value in php.ini.
DocumentRoot designates the root directory for all HTTP processes on that server. It looks something like this on Unix −
DocumentRoot ./usr/local/apache_2.4.0/htdocs.

You can choose any directory as the document root.
The PHP MIME type needs to be set here for PHP files to be parsed. Remember that you can associate any file extension with PHP like .php3, .php5 or .htm.
AddType application/x-httpd-php .php
AddType application/x-httpd-phps .phps
AddType application/x-httpd-php3 .php3 .phtml
AddType application/x-httpd-php .html

You must uncomment this line for the Windows apxs module version of Apache with shared object support −
LoadModule php7_module modules/php7apache2_4.dll

on Unix flavors −
LoadModule php7_module modules/mod_php.so

You must uncomment this line for the static module version of Apache.
AddModule mod_php7.c


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Fortran - Constants

The constants refer to the fixed values that the program cannot alter during its execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, a complex constant, or a string literal. There are only two logical constants : .true. and .false.
The constants are treated just like regular variables, except that their values cannot be modified after their definition.
There are two types of constants −
Literal constants
Named constants
A literal constant have a value, but no name.
For example, following are the literal constants −
"PQR" "a" "123'abc$%#@!"
" a quote "" "
'PQR' 'a' '123"abc$%#@!'
' an apostrophe '' '
A named constant has a value as well as a name.
Named constants should be declared at the beginning of a program or procedure, just like a variable type declaration, indicating its name and type. Named constants are declared with the parameter attribute. For example,
real, parameter :: pi = 3.1415927

The following program calculates the displacement due to vertical motion under gravity.
program gravitationalDisp

! this program calculates vertical motion under gravity 
implicit none  

   ! gravitational acceleration
   real, parameter :: g = 9.81   
   
   ! variable declaration
   real :: s ! displacement   
   real :: t ! time  
   real :: u ! initial speed  
   
   ! assigning values 
   t = 5.0   
   u = 50  
   
   ! displacement   
   s = u * t - g * (t**2) / 2  
   
   ! output 
   print *, "Time = ", t
   print *, 'Displacement = ',s  
   
end program gravitationalDisp
When the above code is compiled and executed, it produces the following result −
Time = 5.00000000    
Displacement = 127.374992    

 Print
 Add Notes
 Bookmark this page
Create a navbar scrolling with the page in Bootstrap

To create a navbar that scrolls with the page, add the .navbar-static-top class. This class does not require adding the padding to the <body>.
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <nav class = "navbar navbar-default navbar-static-top" role = "navigation">
         <div class = "navbar-header">
            <a class = "navbar-brand" href = "#">Car Accessories</a>
         </div>
         <div>
            <ul class = "nav navbar-nav">
               <li class = "active"><a href = "#">Car Cover</a></li>
               <li><a href = "#">Car Mobile Holder</a></li>
               <li><a href = "#">Car Mobile Charger</a></li>
            </ul>
         </div>
      </nav>
   </body>
</html>
Batch Script - Files Inputs

When a batch file is run, it gives you the option to pass in command line parameters which can then be read within the program for further processing. The batch files parameters can be recalled from within the program using the % operator along with the numeric position of the parameter. Following is how the command line parameters are defined.
%0 is the program name as it was called.
%1 is the first command line parameter.
%2 is the second command line parameter.
So on till %9.
Let’s take a look at a simple example of how command line parameters can be used.
@echo off
echo The first parameter is %1
echo The second parameter is %2
echo The third parameter is %3
If the above code is stored in a file called test.bat and the file is run as
test.bat 5 10 15

then, following will be the output.
The first parameter is 5
The second parameter is 10
The third parameter is 15

 Print
 Add Notes
 Bookmark this page
JSF - Using DataModel in a DataTable

In this section, we'll showcase the use of datamodel in a dataTable.
Let us create a test JSF application to test the above functionality.
package com.tutorialspoint.test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;

@ManagedBean(name = "userData", eager = true)
@SessionScoped
public class UserData implements Serializable {
   private static final long serialVersionUID = 1L;

   private static final Employee[] employees =  new Employee[] {
      new Employee("John", "Marketing", 30,2000.00),
      new Employee("Robert", "Marketing", 35,3000.00),
      new Employee("Mark", "Sales", 25,2500.00),
      new Employee("Chris", "Marketing", 33,2500.00),
      new Employee("Peter", "Customer Care", 20,1500.00)
   };

   private DataModel<Employee> employeeDataModel 
      = new ArrayDataModel<Employee>(employees);

   public DataModel<Employee> getEmployees() { 
      return employeeDataModel; 
   }	
}
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"   
xmlns:h = "http://java.sun.com/jsf/html"
xmlns:f = "http://java.sun.com/jsf/core">
   
   <h:head>
      <title>JSF tutorial</title>		
      <h:outputStylesheet library = "css" name = "styles.css"  /> 	
   </h:head>
   
   <h:body> 
      <h2>DataTable Example</h2>
      
      <h:form>
         <h:dataTable value = "#{userData.employees}" var = "employee"
            styleClass = "employeeTable"
            headerClass = "employeeTableHeader"
            rowClasses = "employeeTableOddRow,employeeTableEvenRow">
      
            <h:column> 
               <f:facet name = "header">Sr. No</f:facet>
               #{userData.employees.rowIndex + 1}
            </h:column>
            
            <h:column>    				
               <f:facet name = "header">Name</f:facet>    				
               #{employee.name}
            </h:column>
            
            <h:column>
               <f:facet name = "header">Department</f:facet>
               #{employee.department}
            </h:column>
            
            <h:column>
               <f:facet name = "header">Age</f:facet>
               #{employee.age}
            </h:column>
            
            <h:column>
               <f:facet name = "header">Salary</f:facet>
               #{employee.salary}
            </h:column>
         </h:dataTable>
      </h:form>
   
   </h:body>
</html>
Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result.

    37 Lectures 
     3.5 hours 

 Chaand Sheikh
 Print
 Add Notes
 Bookmark this page