code-rag-bench/online-tutorials huggingface dataset:
PyQt5 - Setting background color to lineedit of ComboBox - GeeksforGeeks

04 May, 2020
In this article we will see how we can set the background color to the line edit part of combo box, line edit part of the combo box is in which text is shown and edit.
In order to add background color to the line edit part of the combo box, do the following –
1. Create a combo box2. Create a line edit widget3. Change background color of the line edit widget4. Add line edit widget to the combo box
Syntax :
# creating line edit widget
line_edit = QLineEdit()
        
# setting background color to the line edit widget
line_edit.setStyleSheet("QLineEdit"
                        "{"
                        "background : lightblue;"
                        "}")
        
        
# adding line edit widget to combo box
self.combo_box.setLineEdit(line_edit)

Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 150, 30)          # making combo box editable        self.combo_box.setEditable(True)          # geek list        geek_list = ["Sayian", "Super Sayian", "Super Sayian 2", "Super Sayian B"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # creating line edit widget        line_edit = QLineEdit()          # setting background color to the line edit widget        line_edit.setStyleSheet("QLineEdit"                                "{"                                "background : lightblue;"                                "}")            # adding line edit widget to combo box        self.combo_box.setLineEdit(line_edit)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python PyQt5-ComboBox-stylesheet
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Continued Fraction Factorization algorithm - GeeksforGeeks

02 Sep, 2020
The continued fraction factorization method (CFRAC) is a general-purpose factorization algorithm valid for integers. It calculates factors of a given integer number without considering its unique properties. It has a sub-exponential running time.  It was first described in 1931 by  D. H. Lehmer and R. E. Powers and later in 1975 were developed into a computer algorithm by Michael A. Morrison and John Brillhart.
(1)   
is called a Continued Fraction, where ai and bi are either real or complex values for all i > = 0. When all the values of bi‘s are 1, then it is called a simple continued fraction.
A Simple Continued Fraction can be denoted as:
(2)   
where Ck= [a0; a1, a2, ..., an] for k<=n is the k-th convergent of the Simple Continued Fraction.An Infinite Continued Fraction [a0; a1, a2, ..., ak, ...] is defined as a limit of the convergents Ck=[a0; a1, a2, ..., an]
Algorithm:This algorithm uses residues produced in the Continued Fraction of (mn)1/2 for some m to produce a square number. 
This algorithm solves the mathematical equation:
(3)   
CFRAC algorithm has a time complexity of:
(4)   
Example 1:
 
Input: continued_fraction((10/7))
Output: [1, 2, 3]

Explanation:

(5)   
Example 2:
Input:  list(continued_fraction_convergents([0, 2, 1, 2]))
Output: [0, 1/2, 1/3, 3/8]
Explanation:

(6)   
Example 3:
 
Input: continued_fraction_reduce([1, 2, 3, 4, 5]) 
Output: 225/157
Explanation:

(7)   
#using sympy modulefrom sympy.ntheory.continued_fraction import continued_fractionfrom sympy import sqrt#calling continued_fraction methodcontinued_fraction(10/7)
Output:
[1, 2, 3]

Code 2: To convert a Continued Fraction into fraction.
#using sympy modulefrom sympy.ntheory.continued_fraction import continued_fraction_reduce   #calling continued_fraction_reduce methodcontinued_fraction_reduce([1, 2, 3, 4, 5])
Output:
225/157

Code 3: To get a list of convergents from a Continued fraction.
# using sympy modulefrom sympy.core import Rational, pifrom sympy import Sfrom sympy.ntheory.continued_fraction import continued_fraction_convergents, continued_fraction_iterator      # calling continued_fraction_convergents method and # passing it as a parameter to a listlist(continued_fraction_convergents([0, 2, 1, 2]))
Output:
[0, 1/2, 1/3, 3/8]

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | sympy.cos() method - GeeksforGeeks

19 Jul, 2019
In simpy, cos() method is cosine function. Using the cos(x) method in simpy module, we can compute the cosine of x.
Syntax : sympy.cos(x)

Return : Returns the cosine of x 
Code #1:Below is the example using cos() method to find cosine function.
# importing sympy libraryfrom sympy import *  # calling cos() method on expressiongeek1 = cos(-1)geek2 = cos(pi / 3)  print(geek1)print(geek2)
Output:
cos(1)
1/2

 Code #2:
# importing sympy libraryfrom sympy import *    # calling cos() method on expressiongeek = cos(2 + 5j)print(geek)
Output:
-30.8822353189167 - 67.4727884405875*I
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
MongoDB count() Method - db.Collection.count() - GeeksforGeeks

28 Jan, 2021
The count() method counts the number of documents that match the selection criteria. It returns the number of documents that match the selection criteria. It takes two arguments first one is the selection criteria and the other is optional. 
This method is equivalent to db.collection.find().count(). 
You cannot use this method in transactions.
One a shared cluster, if you use this method without a query predicate, then it will return an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So, to avoid such type of situation use db.collection.aggregate() method
Syntax:
db.Collection_Name.count(
Selection_criteria,
{
    limit: <integer>,
    skip: <integer>,
    hint: <string or document>,
    maxTimeMS : <integer>,
    readConcern: <string>,
    collation: <document>  
})
Or if we want to count the number of documents in the collection then use this syntax:
db.Collection_name.count()
Parameters:
The first parameter is a selection criteria. The type of this parameter is a document.
The second parameter is optional.
Optional Parameters:
limit: It is the maximum number of documents to count.
skip: It is the number of documents to skip before counting.
hint: It is a document or field that specifies the index to use to support the filter. It can take an index specification document or the index name string and if you specify an index that does not exist, then it will give an error.
maxTimeMs: It is the maximum amount of time to allow the query to run.
readConcern: It is used when you don’t want to use default read concern. To use a read concern level of “majority”, you must specify a nonempty query condition.
collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
Return: 
This method returns the number of documents that match to selection criteria.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Four documents contains name and age of the students
Count the number of documents in the given collection:
Here, we count the total number of documents present in the student collection.
db.student.count()
Count the number of documents that match the given collection:
Here, we count the total number of documents in the student collection that matches the given condition, i.e., age is greater than 18.
db.student.count({age:{$gt:18}})
Note: Here, $gt mean greater than
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
Create user and add role in MongoDB
Export data from MongoDB
MongoDB - sort() Method
MongoDB - Regex
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB insertMany() Method - db.Collection.insertMany()
MongoDB - Update() Method
Implementation of Perceptron Algorithm for NOT Logic Gate - GeeksforGeeks

08 Jun, 2020
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function:
    
For a particular choice of the weight vector  and bias parameter , the model predicts output  for the corresponding input vector .
NOT logical function truth table is of only 1-bit binary input (0 or 1), i.e, the input vector  and the corresponding output  –
Now for the corresponding weight vector  of the input vector , the associated Perceptron Function can be defined as:
    
For the implementation, considered weight parameter is  and the bias parameter is .
Python Implementation:
# importing Python libraryimport numpy as np  # define Unit Step Functiondef unitStep(v):    if v >= 0:        return 1    else:        return 0  # design Perceptron Modeldef perceptronModel(x, w, b):    v = np.dot(w, x) + b    y = unitStep(v)    return y  # NOT Logic Function# w = -1, b = 0.5def NOT_logicFunction(x):    w = -1    b = 0.5    return perceptronModel(x, w, b)  # testing the Perceptron Modeltest1 = np.array(1)test2 = np.array(0)  print("NOT({}) = {}".format(1, NOT_logicFunction(test1)))print("NOT({}) = {}".format(0, NOT_logicFunction(test2)))
NOT(1) = 0
NOT(0) = 1

Here, the model predicted output () for each of the test inputs are exactly matched with the NOT logic gate conventional output () according to the truth table.Hence, it is verified that the perceptron algorithm for NOT logic gate is correctly implemented.
Neural Network
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Decision Tree Introduction with example
Support Vector Machine Algorithm
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
p5.js | saveCanvas() Function - GeeksforGeeks

18 Mar, 2020
The saveCanvas() function is used to save a p5.Table object to a file. The format of the file saved can be defined as a parameter to the function. It saves a text file with comma-separated-values by default, however, it can be used to save it using-tab separated-values or generate an HTML table from it.
Syntax:
saveCanvas(selectedCanvas, filename, extension)
saveCanvas(filename, extension)
Parameters: This function accepts three parameter as mentioned above and described below.
selectedCanvas: This is a p5.Table object that would be saved to the file.
filename: It specifies the string that is used as the filename of the saved file. It is an optional parameter.
extension: It is a string which denotes the extension of the file to be saved. It is an optional parameter.
Below example illustrates the saveCanvas() function in p5.js:
Example:
function preload() {  img = loadImage('sample-image.png');}  function setup() {  createCanvas(600, 300);  textSize(22);    background("orange");  text("Click on the button to save the"+       " current canvas to file", 20, 40);  image(img, 30, 60);    // Create a button for saving the canvas  removeBtn = createButton("Save Canvas");  removeBtn.position(30, 200)  removeBtn.mousePressed(saveToFile);}  function saveToFile() {  // Save the current canvas to file as png  saveCanvas('mycanvas', 'png')}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/saveCanvas
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
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 insert spaces/tabs in text using HTML/CSS?
Python Functools - lru_cache() - GeeksforGeeks

26 Jun, 2020
The functools module in Python deals with higher-order functions, that is, functions operating on(taking as arguments) or returning functions and other such callable objects. The functools module provides a wide array of methods such as cached_property(func), cmp_to_key(func), lru_cache(func), wraps(func), etc. It is worth noting that these methods take functions as arguments.
lru_cache() is one such function in functools module which helps in reducing the execution time of the function by using memoization technique.
Syntax:@lru_cache(maxsize=128, typed=False)
Parameters:maxsize:This parameter sets the size of the cache, the cache can store upto maxsize most recent function calls, if maxsize is set to None, the LRU feature will be disabled and the cache can grow without any limitationstyped:If typed is set to True, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results and they will be stored in two separate entries in the cache
Example:1
from functools import lru_cacheimport time    # Function that computes Fibonacci # numbers without lru_cachedef fib_without_cache(n):    if n < 2:        return n    return fib_without_cache(n-1) + fib_without_cache(n-2)      # Execution start timebegin = time.time()fib_without_cache(30)  # Execution end timeend = time.time()  print("Time taken to execute the\function without lru_cache is", end-begin)  # Function that computes Fibonacci# numbers with lru_cache@lru_cache(maxsize = 128)def fib_with_cache(n):    if n < 2:        return n    return fib_with_cache(n-1) + fib_with_cache(n-2)      begin = time.time()fib_with_cache(30)end = time.time()  print("Time taken to execute the \function with lru_cache is", end-begin)
Output:
Time taken to execute the function without lru_cache is 0.4448213577270508Time taken to execute the function with lru_cache is 2.8371810913085938e-05
Example 2:
from functools import lru_cache  @lru_cache(maxsize = 100)def count_vowels(sentence):    sentence = sentence.casefold()    return sum(sentence.count(vowel) for vowel in 'aeiou')      print(count_vowels("Welcome to Geeksforgeeks"))
Output:
9

nidhi_biet
Python Decorators
Python functools-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
stty command in Linux with Examples - GeeksforGeeks

18 Feb, 2021
stty command in Linux is used to change and print terminal line settings. Basically, this command shows or changes terminal characteristics.
Syntax:
stty [-F DEVICE | --file=DEVICE] [SETTING]...
stty [-F DEVICE | --file=DEVICE] [-a|--all]
stty [-F DEVICE | --file=DEVICE] [-g|--save]

Example: It will display the characteristics of the terminal.
Options:
stty –all: This option print all current settings in human-readable form.stty --all
stty --all
stty -g: This option will print all current settings in a stty-readable form.stty -g
stty -g
stty -F : This option will open and use the specified DEVICE instead of stdin.Example:stty -F D/
Example:
stty -F D/
stty –help : This option will display this help and exit.stty --help
stty --help
stty –version: This option will show the version information and exit.stty --version
stty --version
YouTubeGeeksforGeeks507K subscribersLinux Tutorials | About the user and the terminal | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:002:04 / 2:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WnjofnvIIvg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
linux-command
Linux-misc-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Conditional Statements | Shell Script
Tail command in Linux with examples
scp command in Linux with Examples
echo command in Linux with Examples
Compiling with g++
ps command in Linux with Examples
tr command in Unix/Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
mv command in Linux with examples
Batch Script - Calling a Function

A function is called in Batch Script by using the call command. Following is the syntax.
call :function_name

Following example shows how a function can be called from the main program.
@echo off 
SETLOCAL 
CALL :Display 
EXIT /B %ERRORLEVEL% 
:Display 
SET /A index=2 
echo The value of index is %index% 
EXIT /B 0
One key thing to note when defining the main program is to ensure that the statement EXIT /B %ERRORLEVEL% is put in the main program to separate the code of the main program from the function.
The above command produces the following output.
The value of index is 2

 Print
 Add Notes
 Bookmark this page
AngularJS - Expressions

Expressions are used to bind application data to HTML. Expressions are written inside double curly braces such as in {{ expression}}. Expressions behave similar to ngbind directives. AngularJS expressions are pure JavaScript expressions and output the data where they are used.
<p>Expense on Books : {{cost * quantity}} Rs</p>

<p>Hello {{student.firstname + " " + student.lastname}}!</p>

<p>Roll No: {{student.rollno}}</p>

<p>Marks(Math): {{marks[3]}}</p>

The following example shows the use of all the above-mentioned expressions −
<html>
   <head>
      <title>AngularJS Expressions</title>
   </head>
   
   <body>
      <h1>Sample Application</h1>
      
      <div ng-app = "" ng-init = "quantity = 1;cost = 30; 
         student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};
         marks = [80,90,75,73,60]">
         <p>Hello {{student.firstname + " " + student.lastname}}!</p>
         <p>Expense on Books : {{cost * quantity}} Rs</p>
         <p>Roll No: {{student.rollno}}</p>
         <p>Marks(Math): {{marks[3]}}</p>
      </div>
      
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
      
   </body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.
Hello {{student.firstname + " " + student.lastname}}!
Expense on Books : {{cost * quantity}} Rs
Roll No: {{student.rollno}}
Marks(Math): {{marks[3]}}

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    40 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
How to load an image and show the image using Keras?

To load an image and show the image using Keras, we will use load_image() method to load an image and set the target size of the image to be shown.
Use load_img() method to load the figure.
Set the target size of the image.
To display the figure, use show() method.
from keras.preprocessing import image
img = image.load_img('bird.jpg', target_size=(350, 750))

img.show()
WPF - Application Level

Defining a style on app level can make it accessible throughout the entire application. Let’s take the same example, but here, we will put the styles in app.xaml file to make it accessible throughout application. Here is the XAML code in app.xaml.
<Application x:Class = "Styles.App" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   StartupUri = "MainWindow.xaml"> 
	
   <Application.Resources> 
      <Style TargetType = "TextBlock"> 
         <Setter Property = "FontSize" Value = "24" /> 
         <Setter Property = "Margin" Value = "5" /> 
         <Setter Property = "FontWeight" Value = "Bold" /> 
      </Style> 
		
      <Style TargetType = "TextBox">
         <Setter Property = "HorizontalAlignment" Value = "Left" /> 
         <Setter Property = "FontSize" Value = "24" /> 
         <Setter Property = "Margin" Value = "5" /> 
         <Setter Property = "Width" Value = "200" /> 
         <Setter Property = "Height" Value="40" /> 
      </Style> 
		
   </Application.Resources>
	
</Application>
Here is the XAML code to create text blocks and text boxes.
<Window x:Class = "Styles.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   Title = "MainWindow" Height = "350" Width = "604">
	
   <Grid> 
      <Grid.RowDefinitions> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "*" /> 
      </Grid.RowDefinitions> 
		
      <Grid.ColumnDefinitions> 
         <ColumnDefinition Width = "*" /> 
         <ColumnDefinition Width = "2*" /> 
      </Grid.ColumnDefinitions> 
		
      <TextBlock Text = "First Name: "/>  
      <TextBox Name = "FirstName" Grid.Column = "1" /> 
      <TextBlock Text = "Last Name: " Grid.Row = "1" /> 
      <TextBox Name = "LastName" Grid.Column = "1" Grid.Row = "1" /> 
      <TextBlock Text = "Email: " Grid.Row = "2" /> 
      <TextBox Name = "Email" Grid.Column = "1" Grid.Row = "2"/> 
   </Grid> 
	
</Window>
When you compile and execute the above code, it will produce the following window.
We recommend that you execute the above code and try to insert more features into it.

    31 Lectures 
     2.5 hours 

 Anadi Sharma

    30 Lectures 
     2.5 hours 

 Taurius Litvinavicius
 Print
 Add Notes
 Bookmark this page
Remove object from array in MongoDB?

To remove object from an array in MongoDB, you can use $pull operator. The syntax is as follows:
db.yourCollectionName.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}},
false,true);
To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:
> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23,
... "CustomerDetails":[
... {
... "CustomerId":100,
... "CustomerProduct":"Product-1"
... },
... {
... "CustomerId":150,
... "CustomerProduct":"Product-2"
... },
... {
... "CustomerId":200,
... "CustomerProduct":"Product-3"
... }
... ]
... });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ea036a0c51185aefbd14f")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.removeObject.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 150,
         "CustomerProduct" : "Product-2"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}
Here is the query to remove object from an array in MongoDB:
> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
... {$pull:{"CustomerDetails":{"CustomerId":150}}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Above, we have removed object from an array. Let us display document from the collection. The query is as follows:
> db.removeObject.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}
Python - Calculate the median of column values of a Pandas DataFrame

To calculate the median of column values, use the median() method. At first, import the required Pandas library −
import pandas as pd
Now, create a DataFrame with two columns −
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90] }
)
Finding the median of a single column “Units” using median() −
print"Median of Units column from DataFrame1 = ",dataFrame1['Units'].median()


In the same way, we have calculated the median value from the 2nd DataFrame.
Following is the complete code −
import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Finding median of "Units" column values
print"Median of Units column from DataFrame1 = ",dataFrame1['Units'].median()

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],
      "Price": [8000, 500, 3000, 1500, 3000, 4000]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# Finding median of "Price" column values
print"Median of Price column from DataFrame2 = ",dataFrame2['Price'].median()
This will produce the following output −
DataFrame1 ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3    Tesla     80
4  Bentley    110
5   Jaguar     90
Median of Units column from DataFrame1 = 105.0

DataFrame2 ...
   Price   Product
0  8000    TV
1  500     PenDrive
2  3000    HeadPhone
3  1500    EarPhone
4  3000    HDD
5  4000    SSD
Median of Price column from DataFrame2 = 3000.0
MongoDB - Deployment

When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production.
The best approach incorporates prototyping your set up, conducting load testing, monitoring key metrics, and using that information to scale your set up. The key part of the approach is to proactively monitor your entire system - this will help you understand how your production system will hold up before deploying, and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts.
To monitor your deployment, MongoDB provides some of the following commands −
This command checks the status of all running mongod instances and return counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. Command also shows when you’re hitting page faults, and showcase your lock percentage. This means that you're running low on memory, hitting write capacity or have some performance issue.
To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat.
D:\set up\mongodb\bin>mongostat

Following is the output of the command −
This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or are exceeding your working set size.
To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop.
D:\set up\mongodb\bin>mongotop

Following is the output of the command −
To change mongotop command to return information less frequently, specify a specific number after the mongotop command.
D:\set up\mongodb\bin>mongotop 30

The above example will return values every 30 seconds.
Apart from the MongoDB tools, 10gen provides a free, hosted monitoring service, MongoDB Management Service (MMS), that provides a dashboard and gives you a view of the metrics from your entire cluster.

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    54 Lectures 
     5.5 hours 

 Eduonix Learning Solutions

    44 Lectures 
     4.5 hours 

 Kaushik Roy Chowdhury

    40 Lectures 
     2.5 hours 

 University Code

    26 Lectures 
     8 hours 

 Bassir Jafarzadeh

    70 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Escape sequences in Java

A character preceded by a backslash (\) is an escape sequence and has a special meaning to the compiler.
The following table shows the Java escape sequences.
Let us see an example of Character Escape Sequences in Java.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      char ch = '\u039A';
      System.out.println(ch);
   }
}
K
Bootstrap 3 truncate long text inside rows of a table in a responsive way with HTML

To truncate long texts inside rows of a table, use the following CSS −
.table td.demo {
   max-width: 177px;
}
.table td.demo span {
   overflow: hidden;
   text-overflow: ellipsis;
   display: inline-block;
   white-space: nowrap;
   max-width: 100%;
}
The following is the HTML −
<td class = "demo">
   <span>This is demo text and we have made it a long text for a demo.</span>
</td>
PHP | DateTime format() Function

10 Oct, 2019
The DateTime::format() function is an inbuilt function in PHP which is used to return the new formatted date according to the specified format.
Syntax:
Object oriented stylestring DateTime::format( string $format )orstring DateTimeImmutable::format( string $format )orstring DateTimeInterface::format( string $format )
string DateTime::format( string $format )
or
string DateTimeImmutable::format( string $format )
or
string DateTimeInterface::format( string $format )
Procedural stylestring date_format( DateTimeInterface $object, string $format )
string date_format( DateTimeInterface $object, string $format )
Parameters: This function uses two parameters as mentioned above and described below:
$object: This parameter holds the DateTime object.
$format: This parameter holds the format accepted by date() function.
Return Value: This function return the new formatted date string on success or False on failure.
Below programs illustrate the DateTime::format() function in PHP:
Program 1:
<?php  // Initialising the DateTime() object with a date$datetime = new DateTime('2019-09-30');  // Calling the format() function with a // specified format 'd-m-Y'echo $datetime->format('d-m-Y');  ?>
30-09-2019

Program 2:
<?php  // Initialising the DateTime() object with a date$datetime = new DateTime('2019-09-30');  // Calling the format() function with a // specified format 'd-m-Y H:i:s'echo $datetime->format('d-m-Y H:i:s');  ?>
30-09-2019 00:00:00

Reference: https://www.php.net/manual/en/datetime.format.php
PHP-date-time
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Y Fractal tree in Python using Turtle

02 Jul, 2020
A fractal is a never-ending pattern. Fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop. Driven by recursion, fractals are images of dynamic systems – the pictures of Chaos.
In this article, we will draw a colorful Y fractal tree using a recursive technique in Python.
Examples:
Output for depth level: (a) 14 (b) 12
turtle: turtle library enables users to draw picture or shapes using commands, providing them with a virtual canvas. turtle comes with Python’s Standard Library. It needs a version of Python with Tk support, as it uses tkinter for the graphics.
Functions used:
fd(x) : draw the cursor forward by x pixels.
rt(x), lt(x) : rotates the facing direction of the cursor by x degrees to the right and left respectively.
colormode(): to change the colour mode to rgb.
pencolor(r, g, b): to set the colour of the turtle pen.
speed(): to set the speed of the turtle.
Approach :
We start by drawing a single ‘Y’ shape for the base(level 1) tree. Then both the branches of the ‘Y’ serve as the base of other two ‘Y’s(level 2).
This process is repeated recursively and size of the Y decreases as level increases.
Colouring of the tree is done level wise: darkest in the base level to lightest in the topmost.
In the implementation below, we will draw a tree of size 80 and level 7.
from turtle import *    speed('fastest')  # turning the turtle to face upwardsrt(-90)  # the acute angle between# the base and branch of the Yangle = 30  # function to plot a Ydef y(sz, level):         if level > 0:        colormode(255)                  # splitting the rgb range for green        # into equal intervals for each level        # setting the colour according        # to the current level        pencolor(0, 255//level, 0)                  # drawing the base        fd(sz)          rt(angle)          # recursive call for        # the right subtree        y(0.8 * sz, level-1)                  pencolor(0, 255//level, 0)                  lt( 2 * angle )          # recursive call for        # the left subtree        y(0.8 * sz, level-1)                  pencolor(0, 255//level, 0)                  rt(angle)        fd(-sz)                     # tree of size 80 and level 7y(80, 7)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
A Shell program To Find The GCD | Linux

18 Jan, 2021
The given problem asked in fico placement interview round. Find the gcd of two given numbers using shell scripting We are given two numbers A and B and now task is to find the Greatest Common divisor (gcd) of two given number using shell scripting .Asked in interview : FICOExample:  
Input
 25 15
Output
 5
 
CPP
// Script for finding gcd of two number// echo is for printing the message echo Enter two numbers with space in between // read for scanningread a b // Assigning the value of a to mm = $a // Condition checking if b greater than m// If yes the replace the value of m assign a new valueif [ $b -lt $m ]thenm = $bfi // In do while  loop we are checking the gcdwhile [ $m -ne 0 ]dox = `expr $a % $m`y = `expr $b % $m` // If x and y both are 0 then we complete over// process and we print  the gcdif [ $x -eq 0 -a $y -eq 0 ]then // Printing the greatest gcd of two given numberecho gcd of $a and $b is $mbreakfim = `expr $m - 1` done
The shell script for the above code is :
echo Enter two numbers with space in between
read a b
//reads numbers
m=$a
if [ $b -lt $m ]
then
m=$b
fi
while [ $m -ne 0 ]
do
x=`expr $a % $m`
y=`expr $b % $m`
if [ $x -eq 0 -a $y -eq 0 ]
then
echo gcd of $a and $b is $m
break
fi
m=`expr $m - 1`
done
This article is contributed by Ajay Puri. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
prachi21
FICO
Articles
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
Time complexities of different data structures
Difference Between Object And Class
SQL | DROP, TRUNCATE
Implementation of LinkedList in Javascript
Sed Command in Linux/Unix with examples
AWK command in Unix/Linux with examples
grep command in Unix/Linux
cut command in Linux with examples
cp command in Linux with examples
How to set or get the config variables in Codeigniter ?

28 Nov, 2021
Config Class: The Config class provides means to retrieve configuration preferences. The config items in Codeigniter can be set and get in the environment. The config value $this->config can be used to get and set items in the environment. The config items are contained within an array, namely, $config. The config file is stored at “application/config/config.php“, which may provide opportunities to add new items or create a separate entity of configuration items.
CodeIgniter by default loads the primary config file (application/config/config.php), whereas the custom files need to be externally loaded.
Setting config variable value: The config variable in CodeIgniter can be set in the environment using the following two methods. The config class method set_item() is used to set the value of a variable in Codeigniter. The set_item() can be used to dynamically set a config item or modify an existing one.
Syntax:
$this->config->set_item('item_name', 'item_value');
 
Arguments:
item_name: $config array item name to be changed.
item_value: The value to be changed.
PHP
<?php  // Setting the value of config variable  $this->config->set_item('str', "Hello GFG!");  echo($this->config->item('str'));?>
Output:
[1] "Hello GFG!"
The config item can also be modified or initialized using the key-value pair defined in the $config variable. The item value of the config variable can also be set using the key-value pair in CodeIgniter.
PHP
<?php  $config['str'] = "Hello GFG!";  echo($this->config->item('str'));?>
Output:
[1] "Hello GFG!"
Getting config variable value: The config items can also be easily fetched from the CodeIgniter environment. The config class function item() is used to get the value of a  config variable in Codeigniter.
Syntax:
$this->config->item('item_name');
Arguments:
item_name: $config array index to be retrieved.
Return Value: This function returns a value of the array index key specified, or NULL if no such key exists.
PHP
<?php  // Getting the value of config variable  $this->config->item('str');?>
Output:
[1] "Hello GFG!"
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
GATE | GATE CS 2020 | Question 43

01 Sep, 2021
Consider the productions A → PQ and A → XY. Each of the five non-terminals A,P,Q,X, and Y has two attributes: s is a synthesized attribute, and i is an inherited attribute. Consider the following rules.
Rule 1: P.i=A.i+2, Q.i=P.i+A.i, and A.s=P.s+Q.s
Rule 2: X.i=A.i+Y.s and Y.i=X.s+A.i 
Which one of the following is TRUE ?(A) Both Rule 1 and Rule 2 are L-attributed(B) Only Rule 1 is L-attributed(C) Only Rule 2 is L-attributed(D) Neither Rule 1 nor Rule 2 is L-attributedAnswer: (B)Explanation: According to L-attributed SDT:
If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.Semantic actions are placed anywhere in RHS.
If an SDT uses both synthesized attributes and inherited attributes with a restriction that inherited attribute can inherit values from left siblings only, it is called as L-attributed SDT.
Attributes in L-attributed SDTs are evaluated by depth-first and left-to-right parsing manner.
Semantic actions are placed anywhere in RHS.
Therefore,
Rule 1: P.i=A.i+2, Q.i=P.i+A.i, and A.s=P.s+Q.s 
Rule 1 is L-attributed by definition.
However,
Rule 2: X.i=A.i+Y.s and Y.i=X.s+A.i 
Rule 2 is not L-attributed because this expression (X. Rule 2: i = A.i + Y.s) fails to satisfy the definition of L-attributed.It is failed for X.i =A.i +Y.s since X take value from its sibling which is present of its right, i.e., (A → XY).
Option (B) is correct.
PYQ - Parsing and SDT with Joyojyoti Acharya | GeeksforGeeks GATE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersPYQ - Parsing and SDT with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0026:51 / 47:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3PBTUHdAonk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE-CS-2014-(Set-3) | Question 20
GATE | GATE CS 2008 | Question 40
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
GATE | GATE-CS-2004 | Question 31
Python | String Split including spaces

01 May, 2019
The problems and at the same time applications of list splitting is quite common while working with python strings. The spaces are usually tend to ignore in the use cases. But sometimes, we might not need to omit the spaces but include them in our programming output. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using split() + list comprehension
This kind of operation can be performed using the split function and list comprehension. The main difference in not omitting the space is that we specifically add the spaces that we might have omitted in the process, after each element.
# Python3 code to demonstrate# String Split including spaces# using list comprehension + split()  # initializing stringtest_string = "GfG is Best"  # printing original stringprint("The original string : " + str(test_string))  # using list comprehension + split()# String Split including spacesres = [i for j in test_string.split() for i in (j, ' ')][:-1]  # print resultprint("The list without omitting spaces : " + str(res))
The original string : GfG is Best
The list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']

 
Method #2 : Using zip() + chain() + cycle()
This particular task can also be performed using the combination of above 3 functions. The zip function can be used to bind the logic, chain and cycle function perform the task of inserting the space at appropriate position.
# Python3 code to demonstrate# String Split including spaces# using zip() + chain() + cycle()from itertools import chain, cycle  # initializing stringtest_string = "GfG is Best"  # printing original stringprint("The original string : " + str(test_string))  # using zip() + chain() + cycle()# String Split including spacesres = list(chain(*zip(test_string.split(), cycle(' '))))[:-1]  # print resultprint("The list without omitting spaces : " + str(res))
The original string : GfG is Best
The list without omitting spaces : ['GfG', ' ', 'is', ' ', 'Best']

Python list-programs
Python string-programs
Python
Python Programs
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
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python PIL | Image.transpose() method

17 Jun, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images.Image.transpose() Transpose image (flip or rotate in 90 degree steps) 
Syntax: Transpose image (flip or rotate in 90 degree steps)Parameters: method – One of PIL.Image.FLIP_LEFT_RIGHT, PIL.Image.FLIP_TOP_BOTTOM, PIL.Image.ROTATE_90, PIL.Image.ROTATE_180, PIL.Image.ROTATE_270 or PIL.Image.TRANSPOSE.Returns type: An Image object. 
Image Used:  
 
Python3
# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"C:\Users\System-Pc\Desktop\new.jpg") # Size of the image in pixels (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 6top = height / 4right = 174bottom = 3 * height / 4 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (200, 200)im1 = im1.transpose(Image.FLIP_LEFT_RIGHT)# Shows the image in image viewerim1.show()
Output:  
Another example:Here the transform parameter are changed. Image Used  
 
Python3
# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"C:\Users\System-Pc\Desktop\flower1.jpg") # Size of the image in pixels (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 3top = height / 2right = 164bottom = 3 * height / 2 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom))newsize = (1800, 1800)im1 = im1.transpose(Image.FLIP_TOP_BOTTOM)# Shows the image in image viewerim1.show()
Output:  
 
simranarora5sos
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.