code-rag-bench/online-tutorials huggingface dataset:
Python | Maximum sum of elements of list in a list of lists

11 Jul, 2022
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples:
Input :  [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]
Output : 33 
Explanation: sum of all lists in the given list of lists are:
             list1 = 6, list2 = 15, list3 = 33, list4 = 24 
             so the maximum among these is of 

Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]]
Output : 12
Method 1 : Traversal of list in lists
We can traverse in the lists inside the list and sum up all the elements in a given list and by max function get the maximum of sum of all elements in lists of list. 
Python
# Python program to find the# list in a list of lists whose# sum of elements is the highest# using traversal def maximumSum(list1):    maxi = 0     # traversal in the lists    for x in list1:        sum = 0        # traversal in list of lists        for y in x:            sum+= y            maxi = max(sum, maxi)             return maxi     # driver code list1 = [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]print maximumSum(list1)
Output:
33
Time Complexity: O(n*m) where n is the number of lists and m is the maximum size of the list.Auxiliary Space: O(1)
Method 2 : Traversal of list
Traverse in the outer list only, and sum all elements in the inner lists by using sum() function, find the sum of all the lists and get the maximum of all the sum calculated. 
Python
# Python program to find the# list in a list of lists whose# sum of elements is the highest# using sum and max function and traversal def maximumSum(list1):    maxi = 0    # traversal    for x in list1:        maxi = max(sum(x), maxi)             return maxi      # driver code list1 = [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]print maximumSum(list1)
Output:
33
Time Complexity: O(n*m) where n is the number of lists and m is the maximum size of the list.Auxiliary Space: O(1)
Method 3 : Sum and Max function
sum(max(list1, key=sum))
The above syntax of max() function allows us to find the sum of list in list using the key=sum. max(list1, key=sum), this finds the list with maximum sum of elements and then sum(max(list1, key=sum)) returns us the sum of that list. 
Python
# Python program to find the# list in a list of lists whose# sum of elements is the highest# using sum and max function def maximumSum(list1):    return(sum(max(list1, key = sum)))      # driver code list1 = [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]]print maximumSum(list1)
Output:
33
Time Complexity: O(n*m) where n is the number of lists and m is the maximum size of the list.Auxiliary Space: O(1)
pushpeshrajdx01
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Script to Shutdown Computer

14 Jul, 2019
As we know, Python is a popular scripting language because of its versatile features. In this article, we will write a Python script to shutdown a computer.To shut down the computer/PC/laptop by using a Python script, you have to use the os.system() function with the code “shutdown /s /t 1” .
Note: For this to work, you have to import os library in the ide. If you don’t have it, then ‘pip install os‘ through the Command Prompt.
Causion: Please ensure that you save and close all the program before running this code on the IDLE, as the below program will immediately shut down your computer.
Below is the Python implementation –
import os  shutdown = input("Do you wish to shutdown your computer ? (yes / no): ")  if shutdown == 'no':    exit()else:    os.system("shutdown /s /t 1")
Output:
Here is the Python Program which will ask the user to shut down the computer providing the option of Yes or No. Also, when you type yes & then press the ENTER key, the system will be shut down instantly.
python-utility
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
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python program to find smallest number in a list

10 Feb, 2021
Given a list of numbers, the task is to write a Python program to find the smallest number in given list.Examples: 
Input : list1 = [10, 20, 4]
Output : 4

Input : list2 = [20, 10, 20, 1, 100]
Output : 1
Method 1 : Sort the list in ascending order and print the first element in the list.  
Python3
# Python program to find smallest# number in a list # list of numberslist1 = [10, 20, 4, 45, 99] # sorting the listlist1.sort() # printing the first elementprint("Smallest element is:", *list1[:1])
Output: 
smallest element is: 4
Method 2 : Using min() method  
Python3
# Python program to find smallest# number in a list # list of numberslist1 = [10, 20, 1, 45, 99]  # printing the maximum elementprint("Smallest element is:", min(list1))
Output: 
Smallest element is: 1
Method 3 : Find min list element on inputs provided by user. 
Python3
# Python program to find smallest# number in a list # creating empty listlist1 = [] # asking number of elements to put in listnum = int(input("Enter number of elements in list: ")) # iterating till num to append elements in listfor i in range(1, num + 1):    ele= int(input("Enter elements: "))    list1.append(ele)     # print maximum elementprint("Smallest element is:", min(list1))
Output: 
Enter number of elements in list: 4
Enter elements: 12
Enter elements: 19
Enter elements: 11
Enter elements: 99
Smallest element is: 11
Method 4: Find the smallest element in list.  
Python3
# Python program to find smallest# number in a list l=[ int(l) for l in input("List:").split(",")]print("The list is ",l) # Assign first element as a minimum.min1 = l[0] for i in range(len(l)):     # If the other element is min than first element    if l[i] < min1:        min1 = l[i] #It will change print("The smallest element in the list is ",min1)
Input: 
List: 23,-1,45,22.6,78,100,-5
Output: 
The list is ['23', '-1', '45', '22.6', '78', '100','-5']
The smallest element in the list is  -5
shyampopz0
juhi23priya
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
Plot multiple boxplots in one graph in R

23 May, 2021
In this article, we will learn how to plot multiple boxplot in one graph in R Programming Language. This can be accomplished by using boxplot() function, and we can also pass in a list, data frame or multiple vectors to it. For this purpose, we need to put name of data into boxplot() function as input. 
Syntax: boxplot(x, data, notch, varwidth, names, main)
Parameters:
x: This parameter sets as a vector or a formula.
data: This parameter sets the data frame.
notch: This parameter is the label for horizontal axis.
varwidth: This parameter is a logical value. Set as true to draw width of the box proportionate to the sample size.
main: This parameter is the title of the chart.
names: This parameter are the group labels that will be showed under each boxplot.
For this, the individual data for which a boxplot representation is required is based on the function. By default, the orientation of the boxplots will be vertical hence nothing extra needs to be done here.
Example 1:
R
set.seed(20000)                                           data <- data.frame( A = rpois(900, 3),                    B = rnorm(900),                    C = runif(900)                                         )  # Applying boxplot functionboxplot(data)   
Output:
Example 2:
R
# Multiple boxplot using dataset# ToothGrowth dataset  boxplot( len~dose,         data=ToothGrowth,         main="Different boxplots for per day growth",         xlab="Tooth length",         ylab=" numeric Dose in milligrams/day",         col="blue",         border="black"       )
Output:
The approach is the same as for vertical boxplots but to make them work horizontally, the horizontal parameter of the boxplot() function has to be set TRUE.
Example:
R
# Multiple boxplot using dataset# ToothGrowth dataset  boxplot(len~dose,        data=ToothGrowth,        main="Different boxplots for per day growth",        xlab="Tooth length",        ylab=" numeric Dose in milligrams/day",        col="yellow",        border="brown",        horizontal=TRUE       )
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Python program to hide the mouse cursor on the Terminal screen

18 Aug, 2020
Write a program to hide the mouse cursor on the terminal screen.
Approach:
The curses package is imported and used for this task in C language, napms function call is used for the delay, and curs_set() function is called to make the cursor disappear.
In Python, a package called UniCurses, which is similar to the curses package, is imported and used. In the program, the sleep() function is used for the delay and the curs_set() function is called to make the cursor disappear and then appear again.
Below is the implementation of the above approach:
Python3
# Python program for the above approachimport cursesimport time  # Initializing curses stdscr = curses.initscr()  # Setting the cursor to visible by # inserting 1 as argumentcurses.curs_set(1)    # Delay of 2 secondstime.sleep(2)  # Setting the cursor to invisible by # inserting 0 as argumentcurses.curs_set(0)   # Delay of 2 secondstime.sleep(2)  # Setting the cursor to visible by # inserting 1 as argumentcurses.curs_set(1)    # Delay of 2 secondstime.sleep(2)  # Restoring terminal to it's# original statecurses.endwin()
Output:After running the program, a new window appears:
After 2 seconds, the mouse cursor disappears:
After 4 seconds, the mouse cursor appears again:
After 6 seconds, the program ends:
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
Python | os.path.join() method
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
Python – Extract tuples with elements in Range

02 Sep, 2020
Given list of tuples, extract tuples having elements in range.
Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 5, 6Output : [(5, 6)]Explanation : Only 1 tuple lies in range of 5-6.
Input : test_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)], strt, end = 1, 10Output : [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)]Explanation : All lie in specified range.
Method #1 : Using list comprehension + all()
In this, we check for all elements in range using comparison operator and all() returns true for tuples that contain tuples in range specified.
Python3
# Python3 code to demonstrate working of # Extract tuples with elements in Range# Using all() + list comprehension  # initializing listtest_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)]  # printing original listprint("The original list is : " + str(test_list))  # initializing range strt, end = 4, 7  # list comprehension to encapsulate in 1 liner # all() checks for all elements in range res = [sub for sub in test_list if all(ele >= strt and ele <= end for ele in sub)]          # printing resultsprint("Filtered tuples : " + str(res))
The original list is : [(4, 5, 7), (5, 6), (3, 8, 10), (4, 10)]
Filtered tuples : [(4, 5, 7), (5, 6)]

Method #2 : Using filter() + lambda + all() 
In this, we employ filter() to extract out tuples, according to function provided by lambda, and all() as utility to test for all elements in range tuple.
Python3
# Python3 code to demonstrate working of # Extract tuples with elements in Range# Using filter() + lambda + all()   # initializing listtest_list = [(4, 5, 7), (5, 6), (3, 8, 10 ), (4, 10)]  # printing original listprint("The original list is : " + str(test_list))  # initializing range strt, end = 4, 7  # list() to get back result as list  # all() checks for all elements in range res = list(filter(lambda sub : all(ele >= strt and ele <= end for ele in sub), test_list))          # printing resultsprint("Filtered tuples : " + str(res))
The original list is : [(4, 5, 7), (5, 6), (3, 8, 10), (4, 10)]
Filtered tuples : [(4, 5, 7), (5, 6)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Scan Vulnerabilities of Websites using Nikto in Linux?

03 Jun, 2020
Nikto is an open-source web server scanner which performs comprehensive tests against web servers for multiple items. You can use Nikto with any web servers like Apache, Nginx, IHS, OHS, Litespeed, and so on. Nikto can check for server configuration items such as the presence of multiple index files, HTTP server options, and will attempt to identify installed web servers and software. Items and plugins scanned by Nikto are frequently updated and can be automatically updated.
If you are using a Kali Linux machine then Nikto is already pre-installed in it. You can find it under Vulnerability analysis menu or you can just type in the terminal
nikto -Help
It will launch an option menu which gives a brief about the tool and how to use it, Which looks like this
If you are using any other machine other than Kali you can install Nikto by using package manager example
Arch Linux
pacman -S nikto
Debian 
apt-get install nikto
or you can simply get the github repository by using wget command and use it:
~ wget https://github.com/sullo/nikto/archive/master.zip .
~ unzip master.zip
~ cd /nikto-master/program
Let’s see a very simple example of how to use Nikto in scanning websites for some vulnerability. Use the command:
nikto -h 128.199.222.244
if you are using git hub repository then just navigate to directory and use:
./nikto.pl -h 128.199.222.244
where 128.199.222.244 is scan against the Nginx web server, the scan may take several minutes. You can see the results in the screenshot
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python os.rename() Method

Python method rename() renames the file or directory src to dst.If dst is a file or directory(already present), OSError will be raised.
Following is the syntax for rename() method −
os.rename(src, dst)

src − This is the actual name of the file or directory.
src − This is the actual name of the file or directory.
dst − This is the new name of the file or directory.
dst − This is the new name of the file or directory.
This method does not return any value.
The following example shows the usage of rename() method.
# !/usr/bin/python

import os, sys

# listing directories
print "The dir is: %s"%os.listdir(os.getcwd())

# renaming directory ''tutorialsdir"
os.rename("tutorialsdir","tutorialsdirectory")

print "Successfully renamed."

# listing directories after renaming "tutorialsdir"
print "the dir is: %s" %os.listdir(os.getcwd())\
When we run above program, it produces following result −
The dir is:
 [  'a1.txt','resume.doc','a3.py','tutorialsdir','amrood.admin' ]
Successfully renamed.
The dir is:
 [  'a1.txt','resume.doc','a3.py','tutorialsdirectory','amrood.admin' ]
Python - Variable Exercises

Now you have learned a lot about variables, and how to use them in Python.
Are you ready for a test?
Try to insert the missing part to make the code work as expected:
Create a variable named carname and assign the value Volvo to it.
 = ""

Go to the Exercise section and test all of our Python Variable Exercises:

Python Variable Exercises

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to Use Bitmap images in Button in Tkinter? - GeeksforGeeks

13 Jan, 2021
Prerequisite: Python GUI – tkinter
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python.
A bitmap is an array of binary data representing the values of pixels in an image. A GIF is an example of a graphics image file that has a bitmap.
To create a bitmap image ‘bitmap’ attribute of the button() function is used display. It can take the following values:
error
gray75
gray50
gray25
gray12
hourglass
info
questhead
question
warning
Syntax:
Button(..., bitmap=”<value>”)
Approach 1:
Import module
Create object
Create buttons 
Execute code
Program:
Python3
# Import Modulefrom tkinter import *  # Create Objectsroot = Tk()  # ButtonsButton(root, relief=RAISED, bitmap="error").pack(pady=10)Button(root, relief=RAISED, bitmap="hourglass").pack(pady=10)Button(root, relief=RAISED, bitmap="info").pack(pady=10)Button(root, relief=RAISED, bitmap="question").pack(pady=10)Button(root, relief=RAISED, bitmap="warning").pack(pady=10)Button(root, relief=RAISED, bitmap="gray75").pack(pady=10)Button(root, relief=RAISED, bitmap="gray50").pack(pady=10)Button(root, relief=RAISED, bitmap="gray25").pack(pady=10)Button(root, relief=RAISED, bitmap="gray12").pack(pady=10)Button(root, relief=RAISED, bitmap="questhead").pack(pady=10)  # Execute Tkinterroot.mainloop()
Output:
Approach 2:
In this method, we will create a list of bitmaps and iterate through all bitmaps while passing them to button() function.
Import module
Create object
Create bitmap list
Iterate through the list
Create buttons while iterating
Execute code
Program:
Python3
# Import Modulefrom tkinter import *  # Create Objectsroot = Tk()  # Create Bitmaps Listbitmaps = ["error",           "gray75",           "gray50",           "gray25",           "gray12",           "hourglass",           "info",           "questhead",           "question",           "warning"]  # Iterate through all bitmap listfor bit in bitmaps:    Button(root, relief=RAISED, bitmap=bit).pack(pady=10)  # Execute Tkinterroot.mainloop()
Output:
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to convert a string to camel case in JavaScript?

Camel case is the practice of writing phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation. For example, Concurrent hash maps in camel case would be written as −
ConcurrentHashMaps
We can implement a method to accept a string in JavaScript to convert it to camel case in the following way −
function camelize(str) {
   // Split the string at all space characters
   return str.split(' ')
      // get rid of any extra spaces using trim
      .map(a => a.trim())
      // Convert first char to upper case for each word
      .map(a => a[0].toUpperCase() + a.substring(1))
      // Join all the strings back together
      .join("")
}
console.log(camelize("Concurrent hash maps"))
ConcurrentHashMaps
How to set the Y-axis tick marks using ggplot2 in R?

The default value of Y-axis tick marks using ggplot2 are taken by R using the provided data but we can set it by using scale_y_continuous function of ggplot2 package. For example, if we want to have values starting from 1 to 10 with a gap of 1 then we can use scale_y_continuous(breaks=seq(1,10,by=1)).
 Live Demo
Consider the below data frame:
x<-rpois(20,5)
y<-rpois(20,2)
df<-data.frame(x,y)
df
   x y
1  8 1
2  4 3
3  1 1
4  4 1
5  3 2
6  3 6
7  6 4
8  3 3
9  7 1
10 4 1
11 5 1
12 6 3
13 3 1
14 6 3
15 8 2
16 0 2
17 8 1
18 5 0
19 4 1
20 4 3
Loading ggplot2 package and creating a point chart between x and y −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Creating the point chart with Y-axis tick marks with a difference of 1 −
ggplot(df,aes(x,y))+geom_point()+scale_y_continuous(breaks=seq(1,10,by=1))
C++ | const keyword | Question 1 - GeeksforGeeks

28 Jun, 2021
Predict the output of following program
#include <iostream>using namespace std;int main(){    const char* p = "12345";    const char **q = &p;    *q = "abcde";    const char *s = ++p;    p = "XYZWVU";    cout << *++s;    return 0;}
(A) Compiler Error(B) c(C) b(D) Garbage ValueAnswer: (B)Explanation: Output is ‘c’
const char* p = “12345′′ declares a pointer to a constant. So we can’t assign something else to *p, but we can assign new value to p.
const char **q = &p; declares a pointer to a pointer. We can’t assign something else to **q, but we can assign new values to q and *q.
*q = “abcde”; changes p to point to “abcde”
const char *s = ++p; assigns address of literal ”bcde” to s. Again *s can’t be assigned a new value, but s can be changed.
The statement printf(“%cn”, *++s) changes s to “cde” and first character at s is printed.Quiz of this Question
C++-const keyword
const keyword
C Language
C++ Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
rand() and srand() in C/C++
Substring in C++
Core Dump (Segmentation fault) in C/C++
Left Shift and Right Shift Operators in C/C++
Command line arguments in C/C++
C++ | Exception Handling | Question 3
C++ | new and delete | Question 4
C++ | Inheritance | Question 7
C++ | Operator Overloading | Question 10
C++ | Inheritance | Question 1
GATE | GATE CS 2021 | Set 1 | Question 31 - GeeksforGeeks

11 Aug, 2021
Consider the following sequence of operations on an empty stack.
Push(54);push(52);pop();push(55);push(62);s=pop(); 
Consider the following sequence of operations on an empty queue.
enqueue(21);enqueue(24);dequeue();enqueue(28);enqueue(32);q=dequeue(); 
The value of s+q is ___________.(A) 86(B) 68(C) 24(D) 94Answer: (A)Explanation: Let’s construct an empty stack and do the operations. Stack follows LIFO order.
1.Push(54) // (54)2.Push(52) // (54,52)3.Pop() // (54)4.Push(55) //(54,55)5.Push(62) //(54,55,62)6.s=pop() // (54,55)s=62;
Let’s construct an empty queue and do the operations. Queue follows FIFO order.
1.Enqueue(21) // [21]2.Enqueue(24) // [21,24]3.Dequeue() // [24]4.Enqueue(28) // [24,28]5.Enqueue(32) // [24,28,32]6.q=Dequeue() // [28,32]q=24;
s+q=62+24
So, s+q=86 . 
Alternative Way :
Stack is last in first out data structure, so s = pop() = 62
Queue is first in first out data structure, so q = dequeue() = 24
Therefore,s+q = 62+24 = 86
YouTubeGeeksforGeeks GATE Computer Science16.4K subscribersGATE PYQs 2021 (Set1 and Set2) with Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:001:29 / 1:05:22•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=I43aLH5qEBc" 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
BhanwarRajSingh
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Python - Itertools.compress() - GeeksforGeeks

19 Feb, 2020
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.
Note: For more information, refer to Python Itertools
The itertools.compress() falls under the category of terminating iterators. It means that these iterators are used to work on the short input sequences and produce the output based on the functionality of the method used.
Compress(): This iterator selectively picks the values to print from the passed container according to the boolean list value passed as other arguments. The arguments corresponding to boolean true are printed else all are skipped.
In this, we give two parameters to the function. The first parameter will the iterator and the second parameter will be a selector either True/1 or False/0. If the first parameter’s corresponding selector is True, then the corresponding data will be printed and we will get the output accordingly.
Syntax:
compress(iter, selector)
Example 1 :
# Python code to demonstrate the working of   # compress()     import itertoolsimport operator    Codes =['C', 'C++', 'Java', 'Python']selectors = [False, False, False, True]  Best_Programming = itertools.compress(Codes, selectors)  for each in Best_Programming:    print(each)
Output:
Python

In the above code, in the Codes list, we have stored four variables and in the selectors’ list, we have four boolean values. When we use the itertools.compress() then the value False is assigned to ‘C’, False to ‘C++’, False to ‘Java’ and True to ‘Python’. Now while iterating through the loop we will get the output to which the value True is assigned. So, we get only “Python” while iterating ‘Best Programming’.
Example 2 :
# Python code to demonstrate the working of   # compress()       import itertoolsimport operator    example = itertools.compress('ABCDE', [1, 0, 1, 0, 0])  for each in example:    print(each)
Output:
A
C

Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
C++ Program to Implement Adjacency List

The adjacency list representation of a graph is linked list representation. In this representation we have an array of lists The array size is V. Here V is the number of vertices. In other words, we can say that we have an array to store V number of different lists. If a list header is vertex u, then it signifies that it will hold all of the adjacent vertices of u.
This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased.
This representation takes O(V+2E) for undirected graph, and O(V+E) for directed graph. If the number of edges are increased, then the required space will also be increased.
Input:
Output:
Input: The u and v of an edge {u,v}, and the adjacency list
Output: Adjacency List of the graph G
Begin
   Append v into the list at index u
   Append u into the list at index v
End
#include<iostream>
#include<list>
#include<iterator>
using namespace std;
void displayAdjList(list<int> adj_list[], int v) {
   for(int i = 0; i<v; i++) {
      cout << i << "--->";
      list<int> :: iterator it;
      for(it = adj_list[i].begin(); it != adj_list[i].end(); ++it) {
         cout << *it << " ";
      }
      cout << endl;
   }
}
void add_edge(list<int> adj_list[], int u, int v) {    //add v into the list u, and u into list v
   adj_list[u].push_back(v);
   adj_list[v].push_back(u);
}
main(int argc, char* argv[]) {
   int v = 6;    //there are 6 vertices in the graph
   //create an array of lists whose size is 6
   list<int> adj_list[v];
   add_edge(adj_list, 0, 4);
   add_edge(adj_list, 0, 3);
   add_edge(adj_list, 1, 2);
   add_edge(adj_list, 1, 4);
   add_edge(adj_list, 1, 5);
   add_edge(adj_list, 2, 3);
   add_edge(adj_list, 2, 5);
   add_edge(adj_list, 5, 3);
   add_edge(adj_list, 5, 4);
   displayAdjList(adj_list, v);
}
0--->4 3
1--->2 4 5
2--->1 3 5
3--->0 2 5
4--->0 1 5
5--->1 2 3 4
How to split string on whitespace in Python?

You can usesplit() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters. For example:
 >>>"Please split this string".split()
['Please','split', 'this', 'string']
 Regex can also be used to solve this problem. You can call the re.split() method using the regex '\s+' as delimiter. Note that this method is slower than the above method. 
>>>import re
>>>re.split('\s+', 'Please split this string')
['Please','split', 'this', 'string']
What is unexpected indent in Python?


Python not only insists on indentation, it insists on consistent indentation. If we indent one line by 4 spaces, but then if we indent the next by 3 (or 5, 6, .), we get this error of unexpected indent in python.
In the given code, line 3 has more spaces at the start than line 2. All lines of code in a block must start with exactly the same number of spaces. Both print statements must be indented same number of spaces. So the corrected code that does not show unexpected indent is as follows.
def a():
    print "foo"
    print "baz"
Relational Operators Overloading in C++

There are various relational operators supported by C++ language like (<, >, <=, >=, ==, etc.) which can be used to compare C++ built-in data types.
You can overload any of these operators, which can be used to compare the objects of a class.
Following example explains how  a < operator can be overloaded and similar way you can overload other relational operators.
#include <iostream>
using namespace std;
 
class Distance {
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
      
   public:
      // required constructors
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         feet = f;
         inches = i;
      }
      
      // method to display distance
      void displayDistance() {
         cout << "F: " << feet << " I:" << inches <<endl;
      }
      
      // overloaded minus (-) operator
      Distance operator- () {
         feet = -feet;
         inches = -inches;
         return Distance(feet, inches);
      }
      
      // overloaded < operator
      bool operator <(const Distance& d) {
         if(feet < d.feet) {
            return true;
         }
         if(feet == d.feet && inches < d.inches) {
            return true;
         }
         
         return false;
      }
};

int main() {
   Distance D1(11, 10), D2(5, 11);
 
   if( D1 < D2 ) {
      cout << "D1 is less than D2 " << endl;
   } else {
      cout << "D2 is less than D1 " << endl;
   }
   
   return 0;
}
When the above code is compiled and executed, it produces the following result −
D2 is less than D1


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
C library function - tmpnam()

The C library function char *tmpnam(char *str) generates and returns a valid temporary filename which does not exist. If str is null then it simply returns the tmp file name.
Following is the declaration for tmpnam() function.
char *tmpnam(char *str)
str − This is the pointer to an array of chars where the proposed tempname will be stored as a C string.
str − This is the pointer to an array of chars where the proposed tempname will be stored as a C string.
Return value is a pointer to the C string containing the proposed name for a temporary file. If str was a null pointer, this points to an internal buffer that will be overwritten the next time this function is called.
Return value is a pointer to the C string containing the proposed name for a temporary file. If str was a null pointer, this points to an internal buffer that will be overwritten the next time this function is called.
If str was not a null pointer, str is returned. If the function fails to create a suitable filename, it returns a null pointer.
If str was not a null pointer, str is returned. If the function fails to create a suitable filename, it returns a null pointer.
The following example shows the usage of tmpnam() function.
#include <stdio.h>

int main () {
   char buffer[L_tmpnam];
   char *ptr;

   tmpnam(buffer);
   printf("Temporary name 1: %s\n", buffer);
 
   ptr = tmpnam(NULL);
   printf("Temporary name 2: %s\n", ptr);

   return(0);
}
Let us compile and run the above program to produce the following result −
Temporary name 1: /tmp/filebaalTb
Temporary name 2: /tmp/filedCIbb0


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Ant - Property Task

Ant build files are written in XML, which does not allow declaring variables as you do in your favorite programming language. However, as you may have imagined, it would be useful if Ant allowed declaring variables such as project name, project source directory, etc.
Ant uses the property element which allows you to specify the properties. This allows the properties to be changed from one build to another or from one environment to another.
By default, Ant provides the following pre-defined properties that can be used in the build file −
ant.file
The full location of the build file.
ant.version
The version of the Apache Ant installation.
basedir
The basedir of the build, as specified in the basedir attribute of the project element.
ant.java.version
The version of the JDK that is used by Ant.
ant.project.name
The name of the project, as specified in the name attribute of the project element.
ant.project.default-target
The default target of the current project.
ant.project.invoked-targets
Comma separated list of the targets that were invoked in the current project.
ant.core.lib
The full location of the Ant jar file.
ant.home
The home directory of Ant installation.
ant.library.dir
The home directory for Ant library files - typically ANT_HOME/lib folder.
Ant also makes the system properties (Example: file.separator) available to the build file.
In addition to the above, the user can define additional properties using the property element.
The following example shows how to define a property called sitename −
<?xml version="1.0"?>
<project name="Hello World Project" default="info">

   <property name="sitename" value="www.tutorialspoint.com"/>
   <target name="info">
      <echo>Apache Ant version is ${ant.version} - You are at ${sitename} </echo>
   </target>
</project>
Running Ant on the above build file produces the following output −
C:\>ant
Buildfile: C:\build.xml

info: [echo] Apache Ant version is Apache Ant(TM) version 1.10.12
   compiled on October 13 2021 - You are at www.tutorialspoint.com

BUILD SUCCESSFUL
Total time: 0 seconds
C:\>


    20 Lectures 
     2 hours 

 Deepti Trivedi

    19 Lectures 
     2.5 hours 

 Deepti Trivedi

    139 Lectures 
     14 hours 

 Er. Himanshu Vasishta

    30 Lectures 
     1.5 hours 

 Pushpendu Mondal

    65 Lectures 
     6.5 hours 

 Ridhi Arora

    10 Lectures 
     2 hours 

 Manish Gupta
 Print
 Add Notes
 Bookmark this page
How to open port for the Azure VM using Azure CLI in PowerShell?

To open the specific port for the Azure VM using Azure CLI, we can use az vm open-port command. Before running this command, make sure that you are connected with the Azure Cloud account and the proper Azure subscription.
To open port 80 we can use the below command.
az vm open-port -n Win2k16VM1 -g testvmrg --port 80
The above command will open port 80 on the VM win2k16vm1 and the resource group testvmrg.
To open the port with the highest priority, you can add the --priority parameter
az vm open-port -n Win2k16VM1 -g testvmrg --port 80 --priority 100
To open the port range,
az vm open-port -n Win2k16VM1 -g testvmrg --port 80-100 --priority 100
The above command will open ports 80 to 100 with the highest priority.
If you have multiple ports to open then,
PS C:\> az vm open-port -n Win2k16VM1 -g testvmrg --port 300, 330-400
The above command will open ports 300 and 330 to 400 on the Azure VM.
How to set mnemonics in a label using JavaFX?

You can display a text element/image on the User Interface using the Label component. It is a not editable text control, mostly used to specify the purpose of other nodes in the application.
In JavaFX, you can create a label by instantiating the javafx.scene.control.Label class.
A mnemonic is a number or character, in the menu title of User interface component (button, text field, etc.) typically with an underscore. If you press this character along with the Alt key the respective menu item will be focused.
To create a mnemonic −
Create any node by instantiating its respective class.
Create any node by instantiating its respective class.
Create a label to associate the node, with an underscore character (“_”) before the desired mnemonic character.
Create a label to associate the node, with an underscore character (“_”) before the desired mnemonic character.
By default, the Mnemonic Parsing value for a label will be false, set this value to true using the setMnemonicParsing() method.
By default, the Mnemonic Parsing value for a label will be false, set this value to true using the setMnemonicParsing() method.
Set/Associate the label to the desired node.
Set/Associate the label to the desired node.
Add the label and field to the scene.
Add the label and field to the scene.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class LabelForExample extends Application {
   public void start(Stage stage) {
      //Creating nodes
      TextField textField = new TextField();
      PasswordField pwdField = new PasswordField();
      //creating labels
      Label label1 = new Label("_Email");
      label1.setMnemonicParsing(true);
      label1.setLabelFor(textField);
      Label label2 = new Label("_Password");
      label2.setMnemonicParsing(true);
      label2.setLabelFor(pwdField);
      //Adding labels for nodes
      HBox box1 = new HBox(5);
      box1.setPadding(new Insets(25, 5 , 5, 50));
      box1.getChildren().addAll(label1, textField, label2, pwdField);
      //Setting the stage
      Scene scene = new Scene(box1, 595, 150, Color.BEIGE);
      stage.setTitle("Check Box Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
IF you press Alt+e in the keyboard, the focus will be shifted to the 1st text field and, if you press Alt+p in the keyboard the focus will be shifted to the 2nd text field
PHP | geoip_country_code_by_name() Function - GeeksforGeeks

03 Jul, 2018
The geoip_country_code_by_name() is an inbuilt function in PHP which helps to generate the two-letter country code (Each country is assigned a two-letter country code. For Example: US for United States). The function takes the hostname or IP Address as an argument and generates the two letter country code.
Syntax :
string geoip_country_code_by_name ( string $hostname )

Parameters : The function geoip_country_code_by_name() accepts a single parameter as mentioned above and explained below.
$hostname : This is the only parameter accepted by the above function . This is the IP address or the hostname which the function accepts and returns the two letter country code .
Return Values : It returns a two letter ISO country code on success otherwise returns FALSE on Failure.
Below programs illustrate the geoip_country_code_by_name() function :
Program 1:
<?php  // PHP code implementing the// geoip_country_code_by_name() function   // The function takes the hostname// 'www.example.com' as an argument$country = geoip_country_code_by_name('www.example.com');  if ($country) {    // displays the two letter ISO country code    echo 'This host is located in: ' . $country;                                                   }  ?>
Output:
This host is located in: US

Program 2:
<?php  // PHP code implementing the// geoip_country_code_by_name() function   // The function takes the hostname// 'www.example.com' as an argument$country = geoip_country_code_by_name('www.geeksforgeeks.org');  if ($country) {    // displays the two letter ISO country code    echo 'This host is located in: ' . $country;                                                   }  ?>
Output:
This host is located in: US

Reference : http://php.net/manual/en/function.geoip-country-code-by-name.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to fetch data from localserver database and display on HTML table using PHP ?
Download file from URL using PHP
How to pass JavaScript variables to PHP ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
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?
Python os.chmod() Method

Python method chmod() changes the mode of path to the passed numeric mode. The mode may take one of the following values or bitwise ORed combinations of them −
stat.S_ISUID − Set user ID on execution.
stat.S_ISUID − Set user ID on execution.
stat.S_ISGID − Set group ID on execution.
stat.S_ISGID − Set group ID on execution.
stat.S_ENFMT − Record locking enforced.
stat.S_ENFMT − Record locking enforced.
stat.S_ISVTX − Save text image after execution.
stat.S_ISVTX − Save text image after execution.
stat.S_IREAD − Read by owner.
stat.S_IREAD − Read by owner.
stat.S_IWRITE − Write by owner.
stat.S_IWRITE − Write by owner.
stat.S_IEXEC − Execute by owner.
stat.S_IEXEC − Execute by owner.
stat.S_IRWXU − Read, write, and execute by owner.
stat.S_IRWXU − Read, write, and execute by owner.
stat.S_IRUSR − Read by owner.
stat.S_IRUSR − Read by owner.
stat.S_IWUSR − Write by owner.
stat.S_IWUSR − Write by owner.
stat.S_IXUSR − Execute by owner.
stat.S_IXUSR − Execute by owner.
stat.S_IRWXG − Read, write, and execute by group. 
stat.S_IRWXG − Read, write, and execute by group. 
stat.S_IRGRP − Read by group.
stat.S_IRGRP − Read by group.
stat.S_IWGRP − Write by group.
stat.S_IWGRP − Write by group.
stat.S_IXGRP − Execute by group.
stat.S_IXGRP − Execute by group.
stat.S_IRWXO − Read, write, and execute by others.
stat.S_IRWXO − Read, write, and execute by others.
stat.S_IROTH − Read by others.
stat.S_IROTH − Read by others.
stat.S_IWOTH − Write by others.
stat.S_IWOTH − Write by others.
stat.S_IXOTH − Execute by others.
stat.S_IXOTH − Execute by others.
Following is the syntax for chmod() method −
os.chmod(path, mode);

path − This is the path for which mode would be set.
path − This is the path for which mode would be set.
mode − This may take one of the above mentioned values or bitwise ORed combinations of them.
mode − This may take one of the above mentioned values or bitwise ORed combinations of them.
This method does not return any value.
The following example shows the usage of chmod() method −
#!/usr/bin/python

import os, sys, stat

# Assuming /tmp/foo.txt exists, Set a file execute by the group.
os.chmod("/tmp/foo.txt", stat.S_IXGRP)

# Set a file write by others.
os.chmod("/tmp/foo.txt", stat.S_IWOTH)
print "Changed mode successfully!!"
When we run above program, it produces following result −
Changed mode successfully!!


    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
Find specific key value in array of objects using JavaScript

Suppose we have a JSON object like this −
const obj = {
   "LAPTOP": [{
      "productId": "123"
   }],
   "DESKTOP": [{
      "productId": "456"
   }],
   "MOUSE": [{
      "productId": "789"
   }, {
      "productId": "012"
   }],
   "KEY-BOARD": [{
      "productId": "345"
   }]
};
We are required to write a JavaScript function that takes in one such object as the first argument, and a key value pair as the second argument.
The key value pair is basically nothing but an object like this −
const pair = {"productId": 456};
The function should then search the object for the key with specified "productId" and return that.
The code for this will be −
const obj = {
   "LAPTOP": [{
      "productId": "123"
   }],
   "DESKTOP": [{
      "productId": "456"
   }],
   "MOUSE": [{
      "productId": "789"
   }, {
      "productId": "012"
   }],
   "KEY-BOARD": [{
      "productId": "345"
   }]
};
const searchByPair = (obj = {}, pair = {}) => {
   const toSearch = Object.values(pair)[0];
   let required = undefined;
   Object.keys(obj).forEach((key) => {
      if(obj[key].find((pid) => pid.productId === toSearch)){
         required = key;
      }
   });
   return required;
};
console.log(searchByPair(obj, {
   'productId': '123'
}));
And the output in the console will be −
LAPTOP
Tk - Canvas Arc Widget

Arc widget is used to draw an arc in canvas. The syntax for arc widget is shown below −
canvasName create arc x1 y1 x2 y2 options

x1 y1 and x2 y2 are the end points of an arc.
The options available for the arc widget are listed below in the following table −
-fill color
The fill color fills the arc with the color.
-start angle
The start location in degrees for this arc. The default is 0.
-extent angle
The number of degrees to extend the arc from the start position. The default is 90 degrees.
-style styleType
The style of arc to draw. The options are pieslice, chord and arc.
A simple example for arc widget is shown below −
#!/usr/bin/wish

canvas .myCanvas -background red -width 100 -height 100 
pack .myCanvas
.myCanvas create arc 10 10 80 80 -fill yellow
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page