code-rag-bench/online-tutorials huggingface dataset:
Python Design Patterns - Observer

In this pattern, objects are represented as observers that wait for an event to trigger. An observer attaches to the subject once the specified event occurs. As the event occurs, the subject tells the observers that it has occurred.
The following UML diagram represents the observer pattern −
Let us now see how to implement the observer pattern.
import threading
import time
import pdb

class Downloader(threading.Thread):
   
   def run(self):
      print 'downloading'
      for i in range(1,5):
         self.i = i
         time.sleep(2)
			print 'unfunf'
         return 'hello world'

class Worker(threading.Thread):
   def run(self):
      for i in range(1,5):
         print 'worker running: %i (%i)' % (i, t.i)
         time.sleep(1)
         t.join()

         print 'done'

t = Downloader()
t.start()

time.sleep(1)

t1 = Worker()
t1.start()

t2 = Worker()
t2.start()

t3 = Worker()
t3.start()
The above program generates the following output −
The above code explains the procedure of downloading a particular result. As per the observer pattern logic, every object is treated as observer. It prints the output when event is triggered.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
HTML Navigator userAgent Property

The HTML navigator userAgent property returns the value of the user-agent header sent by the browser to the server.
Following is the syntax −
navigator.userAgent
Let us see an example of HTML navigator userAgent property −
 Live Demo
<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
      text-align: center;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 20px;
      width: 330px;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   .show {
      font-size: 1.2rem;
      color: #fff;
   }
</style>
<body>
<h1>HTML navigator userAgent property Demo</h1>
<button class="btn" onclick="display()">Show user-agent header value</button>
<div class="show"></div>
<script>
   function display() {
      document.querySelector(".show").innerHTML = "<p>Browser user-agent header value is:</p>" + "<p>" + navigator.userAgent + "</p>";
   }
</script>
</body>
</html>
Click on “Show user-agent header value” button to display browser user-agent header value −
HTTP headers | Accept-Ranges - GeeksforGeeks

31 Oct, 2019
The HTTP Accept-Ranges is the Response type header also the part of the ranges system. This header act as a marker that is used by the server to supports the partial request of the clients. The HTTP Accept-Ranges is useful when the client requests any particular portion of a huge file then this header will response and allow the client to download that particular part of that huge file. Like if your server containing a 10M file and the client is demanding for the last 100 bytes of that file then it can request the server only send data from the offset in that ranges.
The Accept-Ranges applies to some particular resources different range types for another type of resource. There is one good thing in the Accept-Ranges that is client can request any byte-range without checking the server supports ranges. When the client requests the range in response, the server sends the status code 206 which is partial content if it is sending the ranges of that file or the status code 200 if it is sending the whole file.
Syntax:
Accept-Ranges: bytes | none
Directives: This header accepts two directives as mentioned above and described below:
bytes: This directive defines the unit of range which is bytes. You can request byte ranges.
None: It means no range unit is supported. This directive should not be used. This directive will remove the pause button in the download manager.
Note: The None directive is used in Internet Explorer.
Example:
Accept-Ranges: bytes
To check this Accept-Ranges in action go to Inspect Element -> Network check the response header for Accept-Ranges like below, Accept-Ranges is highlighted you can see.Supported Browsers: The browsers compatible with HTTP header Accept-Ranges are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
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
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
Plotting graphs using Python's plotly and cufflinks module - GeeksforGeeks

06 Sep, 2021
plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
cufflink connects plotly with pandas to create graphs and charts of dataframes directly. choropleth is used to describe geographical plotting of USA. choropleth is used in the plotting of world maps and many more.
Let’s plot different types of plots like boxplot, spreadplot, etc. using plotly and cufflinks.
Command to install plotly:
pip install plotly 
Command to install cufflink:
pip install cufflink
 
Code #1: Show dataframe
# import all necessary librariesimport pandas as pdimport numpy as np  % matplotlib inlinefrom plotly import __version__import cufflinks as cf  from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot  # to get the connectioninit_notebook_mode(connected = True)  # plotly also serves online,# but we are using just a samplecf.go_offline()  # creating dataframesdf = pd.DataFrame(np.random.randn(100, 4), columns ='A B C D'.split())  df2 = pd.DataFrame({'Category':['A', 'B', 'C'], 'Values':[32, 43, 50]})df2.head()
Output: Code #2: Normal Plot
# plotly functiondf.iplot()
Output: Code #3: Scatter Plot
# markers are made to point in the graphdf.iplot(kind ='scatter', x ='A', y ='B', mode ='markers')
Output: Code #4: Box Plot
# boxplotdf.iplot(kind ='box')
Output: Code #5: Plot dataframes
# creating dataframe with three axesdf3 = pd.DataFrame({'x':[1, 2, 3, 4, 5],                    'y':[10, 20, 30, 20, 10],                    'z':[5, 4, 3, 2, 1]})
Output: Code #6: Surface plot
# surface plot# colorscale:red(rd), yellow(yl), blue(bu)df3.iplot(kind ='surface', colorscale ='rdylbu')
Output:
python-modules
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()
SQL AND and OR operators - GeeksforGeeks

04 Oct, 2021
In SQL, the AND & OR operators are used for filtering the data and getting precise results based on conditions. The SQL AND & OR operators are also used to combine multiple conditions. These two operators can be combined to test for multiple conditions in a SELECT, INSERT, UPDATE, or DELETE statement.
When combining these conditions, it is important to use parentheses so that the database knows what order to evaluate each condition.
The AND and OR operators are used with the WHERE clause.
These two operators are called conjunctive operators.
This operator displays only those records where both the conditions condition1 and condition2 evaluates to True. 
Syntax: 
SELECT * FROM table_name WHERE condition1 AND condition2 and ...conditionN;

table_name: name of the table
condition1,2,..N : first condition, second condition and so on
This operator displays the records where either one of the conditions condition1 and condition2 evaluates to True. That is, either condition1 is True or condition2 is True. Syntax: 
SELECT * FROM table_name WHERE condition1 OR condition2 OR... conditionN;

table_name: name of the table
condition1,2,..N : first condition, second condition and so on

Now, we consider a table database to demonstrate AND & OR operators with multiple cases:
If suppose we want to fetch all the records from the Student table where Age is 18 and ADDRESS is Delhi. then the query will be:
Query:
SELECT * FROM Student WHERE Age = 18 AND ADDRESS = 'Delhi';
Output:  
 
Take another example, to fetch all the records from the Student table where NAME is Ram and Age is 18. 
Query:
SELECT * FROM Student WHERE Age = 18 AND NAME = 'Ram';
Output:  
To fetch all the records from the Student table where NAME is Ram or NAME is SUJIT.  
Query:
SELECT * FROM Student WHERE NAME = 'Ram' OR NAME = 'SUJIT';
Output: 
 
To fetch all the records from the Student table where NAME is Ram or Age is 20. 
Query:
SELECT * FROM Student WHERE NAME = 'Ram' OR Age = 20;
Output: 
We can combine AND and OR operators in the below manner to write complex queries.  
Syntax: 
SELECT * FROM table_name WHERE condition1 AND (condition2 OR condition3);
 
Take an example to fetch all the records from the Student table where Age is 18 NAME is Ram or RAMESH.
Query:
SELECT * FROM Student WHERE Age = 18 AND (NAME = 'Ram' OR NAME = 'RAMESH');
Output: 
 
varshachoudhary
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to write a Pseudo Code?
SQL Interview Questions
Understanding "extern" keyword in C
Mutex vs Semaphore
Analysis of Algorithms | Set 3 (Asymptotic Notations)
ACID Properties in DBMS
SQL query to find second highest salary?
Normal Forms in DBMS
CTE in SQL
SQL Interview Questions
Guess the number with React - GeeksforGeeks

01 Oct, 2021
We create two components App and Result. App components contain all the logic, it is stateful and the Result component only shows the appropriate message on the page according to the user’s guess. The App component has a controlled input field in which the user allowed to type and guess the number. There is a default prop we set to the App component ‘secret’ that holds the required secret number and it is generated randomly. The app component passes the value of the input field and the secret number to the Result component. The result component accordingly show the appropriate message that the guessed number is high or low or correct.
Prerequisite:  
Basic knowledge of React
Setting up Development Environment
Example: Here we will edit the index.html file and app.js file according our requirement. For the result we will create a component and design the output component.  
index.js:
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
app.js :
Javascript
import React, { Component } from 'react'import Result from './Result' class App extends Component{   static defaultProps =  {    secret : Math.floor(Math.random() * 20) + 1  }   constructor(props){    super(props)    this.state = { term : '' }     this.handleChange = this.handleChange.bind(this)  }   handleChange(event){    this.setState({      [event.target.name] : event.target.value    })  }   render(){    return (      <div>        <div>          <label htmlFor='term'>            Guess Number between 1 to 20          </label>        </div>        <input          id='term'          type='text'          name='term'          value={this.state.term}          onChange={this.handleChange}        />           <Result term={this.state.term}            secretNum={this.props.secret} />      </div>    )  }}export default App
Result.js: This component is created for the result.
Javascript
import React from 'react' const Result = ({ term , secretNum }) => {  let result;  if(term){    if(secretNum > term){      result = 'You guessed Lower'    }    else if(secretNum < term){      result ='You guessed Higher'    }    else{      result ='Yippee, guessed it!'    }  }  return <h3>{result}</h3>} export default Result
Output :
Number Guessing App
sweetyty
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Node.js fs.readFileSync() Method
How to calculate the number of days between two dates in javascript?
OnionSearch - Scrapes Urls On Different .Onion Search Engines - GeeksforGeeks

18 Jul, 2021
OnionSearch is a free and open-source Python script that scrapes URLs on different “.onion” search engines. OnionSearch is a free and open-source tool available on GitHub. OnionSearch is used for scrapping URLs tools. OnionSearch is used to scan websites for information gathering and finding vulnerabilities in websites and web apps. This tool can be used to get information about our target(domain). We can target any domain using OnionSearch. The interactive console provides a number of helpful features, such as command completion and contextual help. This tool is written in python, so you must have python installed in your Kali Linux to use this tool. It is a script that scrapes URLs on different .onion search engines.
List of currently supported search engines of  OnionSearch :
ahmia Search engine.
darksearchio Search engine.
onionland Search engine.
notevil Search engine.
darksearchenginer Search engine.
phobos Search engine.
onionsearchserver Search engine.
torgle Search engine.
onionsearchengine Search engine.
tordex Search engine.
tor66 Search engine.
tormax Search engine.
haystack Search engine.
multivac Search engine.
evosearch Search engine.
deeplink Search engine.
Step 1: Open your kali Linux operating system and install the tool using the following command.
git clone https://github.com/megadose/OnionSearch.git
cd OnionSearch'
Step 2: Use the following command to install the setup of the tool.
python3 setup.py install
The tool has been installed successfully. Now we will see examples of running the tool.
Example 1: Use the OnionSearch tool to request all the engines for the word “computer”.
onionsearch "computer"
Example 2: Use the OnionSearch tool to   request all the engines except “Ahmia” and “Candle” for the word “computer”:
onionsearch "computer" --exclude ahmia candle
By running these commands, you can find all the servers and URLs on different “.onion” search engines. Similarly, you can perform searching on URLs.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
Docker - COPY Instruction
mv command in Linux with examples
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Ionic - Padding

Ionic offers an easy way to add padding to elements. There are couple of classes that can be used and all of them will add 10px between border of element and its content. The following table displays all the available padding classes.
When you want to apply some padding to your element, you just need to assign one of the classes from the table above. The following example shows two block buttons. The first one is using the padding class and the second one does not. You will notice that the first button is larger, since it has 10px padding applied.
<div class = "button button-block padding">Padding</div>
<div class = "button button-block">No padding</div>

The above code will produce the following screen −

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
Pure Function in C++

Pure functions always return the same result for the same argument values. They only return the result and there are no extra side effects like argument modification, I/O stream, output generation etc.
Some pure functions are sin(), strlen(), sqrt(), max(), pow(), floor() etc. Some impure functions are rand(), time() etc.
Some programs to demonstrate some of the pure functions are as follows −
The strlen() function is used to find the length of a string. This is demonstrated in the following program −
 Live Demo
#include<iostream>
#include<string.h>
using namespace std;

int main() {
   char str[] = "Rainbows are beautiful";
   int count = 0;

   cout<<"The string is "<< str <<endl;
   cout <<"The length of the string is "<<strlen(str);

   return 0;
}
The output of the above program is as follows −
The string is Rainbows are beautiful
The length of the string is 22
The sqrt() function is used to find the square root of a number.This is demonstrated in the following program −
 Live Demo
#include<iostream>
#include<cmath>

using namespace std;
int main() {
   int num = 9;

   cout<<"Square root of "<< num <<" is "<<sqrt(num);

   return 0;
}
The output of the above program is as follows −
Square root of 9 is 3
Global and Local Variables in C#

A local variable is used where the scope of the variable is within the method in which it is declared. They can be used only by statements that are inside that function or block of code.
 Live Demo
using System;
public class Program {
   public static void Main() {
      int a;
      a = 100;
      // local variable
      Console.WriteLine("Value:"+a);
   }
}
Value:100
C# do not support global variables directly and the scope resolution operator used in C++ for global variables is related to namespaces. It is called global namespace alias.
If you have a type that share an identifier in different namespace, then to identify them use the scope resolution operator. For example, to reference System.Console class, use the global namespace alias with the scope resolution operator −
global::System.Console
using myAlias = System.Collections;
namespace Program {
   class Demo {
      static void Main() {
         myAlias::Hashtable hTable = new myAlias::Hashtable();
         hTable.Add("A", "1");
         hTable.Add("B", "2");
         hTable.Add("C", "3");
         foreach (string str in h.Keys) {
            global::System.Console.WriteLine(str + " " + h[n]);
         }
      }
   }
}
Join, Sleep and Abort methods in C# Threading

Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. This method has different overloaded forms.
Makes the thread pause for a period of time.
The Abort method is used to destroy threads.
Let us see an example of Join() in threading −
using System;
using System.Diagnostics;
using System.Threading;
namespace Sample {
   class Demo {
      static void Run() {
         for (int i = 0; i < 2; i++)
         Console.Write("Sample text!");
      }
      static void Main(string[] args) {
         Thread t = new Thread(Run);
         t.Start();
         t.Join();
         Console.WriteLine("Thread terminated!");
         Console.Read();
      }
   }  
}
Let us see an example of abort() and sleep() in Threading.
using System;
using System.Threading;
namespace Demo {
   class ThreadCreationProgram {
      public static void CallToChildThread() {
         try {
            Console.WriteLine("Child thread starts");
            // do some work, like counting to 10
            for (int counter = 0; counter <= 10; counter++) {
               Thread.Sleep(500);
               Console.WriteLine(counter);
            }
            Console.WriteLine("Child Thread Completed");
         } catch (ThreadAbortException e) {
            Console.WriteLine("Thread Abort Exception");
         } finally {
            Console.WriteLine("Couldn't catch the Thread Exception");
         }
      }
      static void Main(string[] args) {
         ThreadStart childref = new ThreadStart(CallToChildThread);
         Console.WriteLine("In Main: Creating the Child thread");
         Thread childThread = new Thread(childref);
         childThread.Start();
         //stop the main thread for some time
         Thread.Sleep(2000);
         //now abort the child
         Console.WriteLine("In Main: Aborting the Child thread");
         childThread.Abort();
         Console.ReadKey();
      }
   }
}
How to handle a mouse right click event using jQuery?

To handle a mouse right click event, use the mousedown() jQuery method. Mouse left, right and middle click can also be captured using the same method. You can try to run the following code to learn how to handle a mouse right click event:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $('.myclass').mousedown(function(event) {
    switch (event.which) {
        case 1:
            alert('Left mouse button is pressed');
            break;
        case 2:
            alert('Middle mouse button is pressed');
            break;
        case 3:
            alert('Right mouse button is pressed');
            break;
        default:
            alert('Nothing');
    }
});
});
</script>
</head>
<body>

<a href="http://qries.com" class="myclass">Click me</a>

</body>
</html>
What is Multiplication Assignment Operator (*=) in JavaScript?

Multiplication Assignment Operator (*=)multiplies the right operand with the left operand and assigns the result to the left operand.
You can try to run the following code to learn how to work with Multiplication Assignment Operator −
<html>
   <body>
      <script>
         var a = 33;
         var b = 10;

         document.write("Value of a => (a *= b) => ");
         result = (a *= b);
         document.write(result);
      </script>
   </body>
</html>
Donut Plot with Matplotlib (Python) | by Asad Mahmood | Towards Data Science

“A picture is worth a thousand words”
In this post, I’ll demonstrate how to create a donut plot using matplotlib with python. Donut plot is a very efficient way of comparing stats of multiple entities. As per [1]
Just like a pie chart, a doughnut chart shows the relationship of parts to a whole, but a doughnut chart can contain more than one data series. Each data series that you plot in adoughnut chart adds a ring to the chart.
Now let’s use the following dummy data representing the usage of mobile applications of different social media websites.
╔═════════════════╦══════════╗║   Social Media  ║   Usage  ║╠═════════════════╬══════════╣║ Twitter         ║ 60 %     ║║ Facebook        ║ 75 %     ║║ Instagram       ║ 80 %     ║╚═════════════════╩══════════╝
Following is the code for creating a donut plot.
import pandas as pdimport redata = pd.read_csv('testdata.csv')print(data.head())import matplotlib.pyplot as plt# create donut plotsstartingRadius = 0.7 + (0.3* (len(data)-1))for index, row in data.iterrows():    scenario = row["scenario"]    percentage = row["Percentage"]    textLabel = scenario + ' ' + percentage    print(startingRadius)    percentage = int(re.search(r'\d+', percentage).group())    remainingPie = 100 - percentage    donut_sizes = [remainingPie, percentage]    plt.text(0.01, startingRadius + 0.07, textLabel, horizontalalignment='center', verticalalignment='center')    plt.pie(donut_sizes, radius=startingRadius, startangle=90, colors=['#d5f6da', '#5cdb6f'],            wedgeprops={"edgecolor": "white", 'linewidth': 1})    startingRadius-=0.3# equal ensures pie chart is drawn as a circle (equal aspect ratio)plt.axis('equal')# create circle and place onto pie chartcircle = plt.Circle(xy=(0, 0), radius=0.35, facecolor='white')plt.gca().add_artist(circle)plt.savefig('donutPlot.jpg')plt.show()
On the very core, donut plot here in this code is being created by creating a series of pie charts of different radiuses one on top of the other with a white circle in the center.
Text Analysis Using Turicreate

08 Dec, 2021
What is Text Analysis?Text is a group of words or sentences.Text analysis is  analyzing the text and then extracting information with the help of text.Text data is one of  the biggest factor that can make a company big or small.For example 
On E-Commerce website people buy things .With Text Analysis the E-Commerce website can know what it’s customer likes and it through this data it can make it’s productivity higher.
Using Text analysis and some Machine Learning Algorithm our Alexa Google Home mini works.  These two are based on Natural Language Processing.
Using Text Analysis we can decide whether a E-mail is a Spam or a Non Spam.
Text analysis can be done using text mining.As the text “data” can be structured as well as unstructured.The text mining technique will help us in differentiating between them.
Now let’s do some text analysis using Turicreate.We will build a model that classifies that a message is a spam or ham for text analysis.Link for the dataset=https://www.kaggle.com/team-ai/spam-text-message-classificationStep 1: Import the Turicreate Library
python3
import turicreate as tc
python3
python3
data = tc.SFrame("data.csv")
Step 3: We will explore the data first.
# It will print the first full rows of the datadata.head().
Output: 
dataset
Step 4:Now adding the word count in the data set.This is because data has two things category and message. Adding the word count will help in model feature selection.
python3
# Text analytics library has a count word function. # It will separately count the words for each row # of message column.data['word_count']= tc.text_analytics.count_words(data['Message'])  # now we can see that the data has one more column if word_count.data.head()
Here One more row of word_count is added in the data set.
Step 5: To split the data into train and test set.
python3
train_data, test_data = data.random_split(.8, seed = 0)
python3
# We will use our feature as word count and # our target "category is to find out spam or ham.  model = tc.logistic_classifier.create(    train_data, target ='Category',     features =['word_count'],     validation_set = test_data)
python3
model.evaluate(test_data)
The accuracy is 0.975 that means 97.5%.Step 8: We can predict manually by checking from our test data that it is giving right answer or not.
Code:
python3
test_data.head()# We will select the first one that is spam # and select that is spam or not.
Step 9: Predicting the test data.
python3
model.predict(test_data[1])
The result is spam hence the model is predicting it right.
simmytarika5
gulshankumarar231
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
How to adjust CSS for specific zoom level?

02 Jul, 2019
In this article, we are going to learn how do we adjust the CSS for a specific zoom level. The CSS zoom property allows scaling of the content. This property is not recommended for production sites because it doesn’t support in some browsers.
Values:
percentage: Scaling by percentage
number: Scaling using percentage, e.g 1 = 100% and 1.5 = 150%
normal: zoom: 1
Syntax: (The zoom here is set at 100%. Change it accordingly.)
<button onclick="sampleDiv.style.zoom='100%'">Zoom 100%</button>
Example: This example shows how to adjust CSS for specific zoom level.
<!DOCTYPE html><html>  <head>    <title>        adjust CSS for specific zoom level    </title></head>  <body style="text-align:center">    <h2 style="color:green">      GeeksForGeeks  </h2>    <h2 style="color:purple">      adjust CSS for specific zoom level      </h2>    <div id="sampleDiv" style="width: 100px; background-color: green; ">        <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190506164011/logo3.png"              alt="Trulli"              width="250"              height="250"             align="middle"             class="center">    </div>    <button onclick="sampleDiv.style.zoom='100%'">      Zoom 100%  </button>    <button onclick="sampleDiv.style.zoom='50%'">      Zoom 50%  </button>    <button onclick="sampleDiv.style.zoom='200%'">      Zoom 200%  </button></body>  </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Apple Safari
Opera
CSS-Misc
Picked
CSS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
How to select all child elements recursively using CSS?
Build a Survey Form using HTML and CSS
CSS | :not(:last-child):after Selector
Create a Responsive Navbar using ReactJS
How to make flexbox children 100% height of their parent using CSS?
Python | Pandas dataframe.take()

23 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.take() function return the elements in the given positional indices along an axis. This means that we are not indexing according to actual values in the index attribute of the object. We are indexing according to the actual position of the element in the object.
Syntax: DataFrame.take(indices, axis=0, convert=None, is_copy=True, **kwargs)
Parameters :indices : An array of ints indicating which positions to take.axis : The axis on which to select elements. 0 means that we are selecting rows, 1 means that we are selecting columnsconvert : Whether to convert negative indices into positive ones. For example, -1 would map to the len(axis) – 1. The conversions are similar to the behavior of indexing a regular Python list.is_copy : Whether to return a copy of the original object or not.**kwargs : For compatibility with numpy.take(). Has no effect on the output.
Returns : An array-like containing the elements taken from the object.
For link to the CSV file used in the code, click here
Example #1: Use take() function to take some values over the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Print the dataframedf
Now we will modify the index labels for the demonstration purpose. Right now the labels are numbered from 0 to 914.
# double the value of index labelsdf.index = df.index * 2  # Print the modified dataframedf
Let’s take the values at position 0, 1 and 2
# take values at input position over the index axis  df.take([0, 1, 2], axis = 0)
Output :As we can see in the output, the values are selected based on the position but not on the index labels. Example #2: Use take() function to take values at position 0, 1 and 2 over the column axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Print the dataframedf
Now we will take values at position 0, 1 and 2 over the column axis.
# take values over the column axis.  df.take([0, 1, 2], axis = 1)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
How to remove .html extension from URL of a static page ?

07 Aug, 2021
All the pages on the website have a structure which is given by HTML. HTML provides the structure to content, text, tables, headings, and lists on the webpage that makes the page easy to read. While saving an HTML document it has an extension as .html. Therefore, the URL of the website have a .html extension. The .html extension can be easily removed by editing the .htaccess file.
.htaccess file: The .htaccess file is created with a Text Editor like Notepad. It is a simple ASCII file that lets the server know what configuration changes are to be made on a per-directory basis.
Note: The .htaccess is the full name of the file. It is not file.htaccess, it is simply .htaccess.
Removing .html Extension: To remove the .html extension from a URL. For example: From  
example.com/content.html
To 
example.com/content
You have to follow these steps: 
Log in to cPanel account.
In the Files section, click on the File Manager icon.
Click on the Settings Button in the top right corner.
If you want to make changes in the Primary Domain then Click on the radio button next to the Web Root. If changes are to be made on Other Domains, then Click the dropdown menu and find the domain in which changes are to be made.
Remember to check the checkbox next to Show Hidden Files. Now click the Save Button to return to the File Manager window.
Now you are in the Root Folder of the domain which you have selected to make changes. Search for the .htaccess file and right-click on it. Click on the Edit option in the menu. You can now add code to the .htaccess file.
Add the following code inside the .htaccess file: 
HTML
#remove html file extension https://example.com/page.html# to https://example.com/pageRewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^([^\.]+)$ $1.html [NC, L]
Click on the Save Changes Button and then on Close Button.
You can now link any page inside the HTML document without needing to add the extension of the page as no extension will be visible now in the URL of the website.
Example:  
<a href="http://example.com/image" title="image">image</a>
The search engine may index these pages as duplicate content, to overcome this add a <canonical> meta tag in the HTML file. 
Example:  
<link rel="canonical" href="https://example.com/blog/first-blog" />
 
nidhi_biet
sumitgumber28
HTML-Misc
Picked
HTML
Web Technologies
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
XML - Validation

Validation is a process by which an XML document is validated. An XML document is said to be valid if its contents match with the elements, attributes and associated document type declaration(DTD), and if the document complies with the constraints expressed in it. Validation is dealt in two ways by the XML parser. They are −
Well-formed XML document
Valid XML document
An XML document is said to be well-formed if it adheres to the following rules −
Non DTD XML files must use the predefined character entities for amp(&), apos(single quote), gt(>), lt(<), quot(double quote).
Non DTD XML files must use the predefined character entities for amp(&), apos(single quote), gt(>), lt(<), quot(double quote).
It must follow the ordering of the tag. i.e., the inner tag must be closed before closing the outer tag.
It must follow the ordering of the tag. i.e., the inner tag must be closed before closing the outer tag.
Each of its opening tags must have a closing tag or it must be a self ending tag.(<title>....</title> or <title/>).
Each of its opening tags must have a closing tag or it must be a self ending tag.(<title>....</title> or <title/>).
It must have only one attribute in a start tag, which needs to be quoted.
It must have only one attribute in a start tag, which needs to be quoted.
amp(&), apos(single quote), gt(>), lt(<), quot(double quote) entities other than these must be declared.
amp(&), apos(single quote), gt(>), lt(<), quot(double quote) entities other than these must be declared.
Following is an example of a well-formed XML document −
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
<!DOCTYPE address
[
   <!ELEMENT address (name,company,phone)>
   <!ELEMENT name (#PCDATA)>
   <!ELEMENT company (#PCDATA)>
   <!ELEMENT phone (#PCDATA)>
]>

<address>
   <name>Tanmay Patil</name>
   <company>TutorialsPoint</company>
   <phone>(011) 123-4567</phone>
</address>
The above example is said to be well-formed as −
It defines the type of document. Here, the document type is element type.
It defines the type of document. Here, the document type is element type.
It includes a root element named as address.
It includes a root element named as address.
Each of the child elements among name, company and phone is enclosed in its self explanatory tag.
Each of the child elements among name, company and phone is enclosed in its self explanatory tag.
Order of the tags is maintained.
Order of the tags is maintained.
If an XML document is well-formed and has an associated Document Type Declaration (DTD), then it is said to be a valid XML document. We will study more about DTD in the chapter XML - DTDs.
Python – Dictionary Values Mean

01 Aug, 2020
Given a dictionary, find mean of all the values present.
Input : test_dict = {“Gfg” : 4, “is” : 4, “Best” : 4, “for” : 4, “Geeks” : 4}Output : 4.0Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean.
Input : test_dict = {“Gfg” : 5, “is” : 10, “Best” : 15}Output : 10.0Explanation : Mean of these is 10.0
Method #1 : Using loop + len()
This is brute way in which this task can be performed. In this, we loop through each value and perform summation and then the result is divided by total keys extracted using len().
Python3
# Python3 code to demonstrate working of # Dictionary Values Mean# Using loop + len()  # initializing dictionarytest_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # loop to sum all values res = 0for val in test_dict.values():    res += val  # using len() to get total keys for mean computationres = res / len(test_dict)  # printing result print("The computed mean : " + str(res)) 
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0

Method #2 : Using sum() + len() + values()
The combination of above functions can be used to solve this problem. In this, we perform summation using sum() and size() of total keys computed using len().
Python3
# Python3 code to demonstrate working of # Dictionary Values Mean# Using sum() + len() + values()  # initializing dictionarytest_dict = {"Gfg" : 4, "is" : 7, "Best" : 8, "for" : 6, "Geeks" : 10}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # values extracted using values()# one-liner solution to problem.res = sum(test_dict.values()) / len(test_dict)  # printing result print("The computed mean : " + str(res)) 
The original dictionary is : {'Gfg': 4, 'is': 7, 'Best': 8, 'for': 6, 'Geeks': 10}
The computed mean : 7.0

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Cost and efforts of software maintenance - GeeksforGeeks

17 Nov, 2021
Software Maintenance is a very broad activity that takes place once the operation is done. It optimizes the software performance by reducing errors, eliminating useless lines of codes and applying advanced development. It can take up to 1-2 years to build a software system while its maintenance and modification can be an ongoing activity for 15-20 years. 
Categories of Software Maintenance: 
Corrective MaintenanceAdaptive MaintenancePerfective MaintenancePreventive Maintenance
Corrective Maintenance
Adaptive Maintenance
Perfective Maintenance
Preventive Maintenance
The cost of system maintenance represents a large proportion of the budget of most organizations that use software system. More than 65% of software lifecycle cost is expanded in the maintenance activities. Cost of software maintenance can be controlled by postponing the. development opportunity of software maintenance but this will cause the following intangible cost: 
Customer dissatisfaction when requests for repair or modification cannot be addressed in a timely manner.
Reduction in overall software quality as a result of changes that introduce hidden errors in maintained software.
Software maintenance cost factors: The key factors that distinguish development and maintenance and which lead to higher maintenance cost are divided into two subcategories: 
Non-Technical factorsTechnical factors
Non-Technical factors
Technical factors
Non-Technical factors: The Non-Technical factors include:  
Application DomainStaff stabilityProgram lifetimeDependence on External EnvironmentHardware stability
Application Domain
Staff stability
Program lifetime
Dependence on External Environment
Hardware stability
Technical factors: Technical factors include the following:  
module independenceProgramming languageProgramming styleProgram validation and testingDocumentationConfiguration management techniques
module independence
Programming language
Programming style
Program validation and testing
Documentation
Configuration management techniques
Efforts expanded on maintenance may be divided into productivity activities (for example analysis and evaluation, design and modification, coding). The following expression provides a module of maintenance efforts:  
M = P + K(C - D) 
where, M: Total effort expanded on the maintenance. P: Productive effort. K: An empirical constant. C: A measure of complexity that can be attributed to a lack of good design and documentation. D: A measure of the degree of familiarity with the software. 
 
sagar0719kumar
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional vs Non Functional Requirements
Software Engineering | Classical Waterfall Model
Software Requirement Specification (SRS) Format
Differences between Verification and Validation
Software Engineering | Requirements Engineering Process
Levels in Data Flow Diagrams (DFD)
Software Engineering | Requirements Elicitation
DFD for Library Management System
Software Engineering | SDLC V-Model
Software Engineering | Architectural Design
How to Add Apple's new San Francisco font on a Webpage using CSS ? - GeeksforGeeks

29 Jan, 2020
The newly created Apple’s San Francisco font is comfortable for human eyes as per research. Normally Apple’s font can not be used on any webpage through CSS. These kind of fonts are in-build in Apple’s product but the new San Francisco font can be used in any web content. Mr. Craig Hockenberry introduces the procedure of how we can use that font on your webpage through CSS only.
Syntax:
body {
    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}
Firefox and Internet explorer use -apple-system; and for chrome we use BlinkMacSystemFont.
Note: For system use you can download San francisco font from here. After downloading you have install each version one by one.
Other available variants:
font-family: -apple-system-body
font-family: -apple-system-headline
font-family: -apple-system-subheadline
font-family: -apple-system-caption1
font-family: -apple-system-caption2
font-family: -apple-system-footnote
font-family: -apple-system-short-body
font-family: -apple-system-short-headline
font-family: -apple-system-short-subheadline
font-family: -apple-system-short-caption1
font-family: -apple-system-short-footnote
font-family: -apple-system-tall-body
Example:
<!DOCTYPE html><html>  <head>    <title>San Francisco font</title>      <style>        body {            font-family: -apple-system,                 BlinkMacSystemFont, sans-serif;        }        h1 {            color: green;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>          <h3>Welcome To San francisco font</h3>          <p>        This font are pplicable        now in webpages    </p>          <p>        To apply this font on your web        site through CSS just follow the        body tag element in the style tag    </p></body>  </html>            
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Insert data into inner array in MongoDB?

You can use $addToSet operator for this. Let us first create a collection with documents −
> db.insertDataIntoArrayDemo.insertOne(
   {
      "UserDetails":[
         {
            "UserId" :"user121",
            "userGroupMessage":[]
         },
         {
            "UserId" :"user221",
            "userGroupMessage":["Cool","Good Morning"]
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd694e157806ebf1256f128")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.insertDataIntoArrayDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd694e157806ebf1256f128"),
   "UserDetails" : [
      {
         "UserId" : "user121",
         "userGroupMessage" : [ ]
      },
      {
         "UserId" : "user221",
         "userGroupMessage" : [
            "Cool",
            "Good Morning"
         ]
      }
   ]
}
Following is the query to insert data into inner array in MongoDB −
> db.insertDataIntoArrayDemo.update({"UserDetails.UserId":"user121"},
   {"$addToSet":{"UserDetails.$.userGroupMessage":"Hello"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.insertDataIntoArrayDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd694e157806ebf1256f128"),
   "UserDetails" : [
      {
         "UserId" : "user121",
         "userGroupMessage" : [
            "Hello"
         ]
      },
      {
         "UserId" : "user221",
         "userGroupMessage" : [
            "Cool",
            "Good Morning"
         ]
      }
   ]
}
Way to read input from console in C#

Use the ReadLine() method to read input from the console in C#. This method receives the input as string, therefore you need to convert it.
For example −
Let us see how to get user input from user and convert it to integer.
Firstly, read user input −
string val;
Console.Write("Enter integer: ");
val = Console.ReadLine();
Now convert it to integer −
int a = Convert.ToInt32(val);
Console.WriteLine("Your input: {0}",a);
Let us see this in an example. The input is added using command line argument−
 Live Demo
using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      string val;
      Console.Write("Enter Integer: ");
      val = Console.ReadLine();
      int a = Convert.ToInt32(val);
      Console.WriteLine("Your input: {0}",a);
   }
}
The above will give the following result −
Enter Integer: 5
Your input: 5