code-rag-bench/online-tutorials huggingface dataset:
Iterate over characters of a string in Python

19 Dec, 2018
In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over characters of a string in Python.
Example #1: Using simple iteration and range()
# Python program to iterate over characters of a string  # Code #1string_name = "geeksforgeeks"  # Iterate over the stringfor element in string_name:    print(element, end=' ')print("\n")    # Code #2string_name = "GEEKS"  # Iterate over indexfor element in range(0, len(string_name)):    print(string_name[element])
g e e k s f o r g e e k s 

G
E
E
K
S

 Example #2: Using enumerate() function
# Python program to iterate over characters of a string  string_name = "Geeks"  # Iterate over the stringfor i, v in enumerate(string_name):    print(v)
G
e
e
k
s

 Example #3: Iterate characters in reverse order
# Python program to iterate over characters of a string  # Code #1string_name = "GEEKS"  # slicing the string in reverse fashion for element in string_name[ : :-1]:    print(element, end =' ')print('\n')  # Code #2string_name = "geeksforgeeks"  # Getting length of stringran = len(string_name)  # using reversed() functionfor element in reversed(range(0, ran)):    print(string_name[element])
S K E E G 

s
k
e
e
g
r
o
f
s
k
e
e
g

 Example #4: Iteration over particular set of element.
Perform iteration over string_name by passing particular string index values.
# Python program to iterate over particular set of element.string_name = "geeksforgeeks"  # string_name[start:end:step]for element in string_name[0:8:1]:     print(element, end =' ')
g e e k s f o r

Picked
Python string-programs
python-string
Technical Scripter 2018
Python
Python Programs
Technical Scripter
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 Program for Fibonacci numbers
Python – Check if previous element is smaller in List

04 Sep, 2021
Sometimes, while working with Python lists, we can have a problem in which we need to check for each element if its preceding element is smaller. This type of problem can have its use in data preprocessing domains. Let’s discuss certain problems in which this task can be performed. 
Input : test_list = [1, 3, 5, 6, 8] Output : [True, True, True, True]Input : test_list = [3, 1] Output : [False]  
Method #1 : Using loop This is one of the ways in which this task can be performed. In this, we perform the task of checking for elements using brute for in loop. 
Python3
# Python3 code to demonstrate working of# Check if previous element is smaller in List# Using loop # initializing listtest_list = [6, 3, 7, 3, 6, 7, 8, 3] # printing original listprint("The original list is : " + str(test_list)) # Check if previous element is smaller in List# Using loopres = []for idx in range(1, len(test_list)):    if test_list[idx - 1] < test_list[idx]:        res.append(True)    else:        res.append(False) # printing resultprint("List after filtering : " + str(res))
The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
 
 Method #2 : Using zip() + list comprehension This is one-liner approach to solve this problem. In this, we first, zip the list and its next element list, and then check for comparisons for result. 
Python3
# Python3 code to demonstrate working of# Check if previous element is smaller in List# Using zip() + list comprehension # initializing listtest_list = [6, 3, 7, 3, 6, 7, 8, 3] # printing original listprint("The original list is : " + str(test_list)) # Check if previous element is smaller in List# Using zip() + list comprehensionres = [int(sub1) < int(sub2) for sub1, sub2 in zip(test_list, test_list[1:])] # printing resultprint("List after filtering : " + str(res))
The original list is : [6, 3, 7, 3, 6, 7, 8, 3]
List after filtering : [False, True, False, True, True, True, False]
 
ruhelaa48
Python list-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
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
How to override the CSS properties of a class using another CSS class ?

27 Sep, 2019
To override the CSS properties of a class using another class, we can use the !important directive. In CSS, !important means “this is important”, and the property:value pair that has this directive is always applied even if the other element has higher specificity.
Syntax:
element1 {
    property-x: value_y  !important; /* This will be applied. */
}
element2 {
    property-x: value_z; /* This will not be applied. */
}

Example:
<!DOCTYPE html><html>  <head>    <title>!important</title>    <meta charset="utf-8">    <meta name="viewport"           content="width=device-width, initial-scale=1">    <link rel="stylesheet"           href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">    <link href="https://fonts.googleapis.com/css?family=Indie+Flower&display=swap"           rel="stylesheet">    <link href="https://fonts.googleapis.com/css?family=Mansalva&display=swap"          rel="stylesheet">    <style>        h1 {            text-align: center;            color: green;        }                  .my_fav_font {            font-family: 'Indie Flower', cursive !important;            /* This will be applied. */        }                  .my_para {            font-family: 'Mansalva', cursive;            /* This will not be applied. */            text-align: justify;            background-color: powderblue;            font-size: 130%;        }    </style></head>  <body>    <div class="container">        <h1>GeeksforGeeks</h1>        <hr/>        <p class="my_fav_font my_para">Cascading Style Sheets,        fondly referred to as CSS, is a simply designed language        intended to simplify the process of making web pages        presentable. CSS allows you to apply styles to web pages.        More importantly, CSS enables you to do this independent         of the HTML that makes up each web page.</p>    </div></body>  </html>
Output:
CSS-Misc
Picked
CSS
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
On/Off Toggle Button Switch in Tkinter

19 Oct, 2021
Prerequisite: Tkinter
Python offers multiple options for developing a 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. Python with Tkinter is the fastest and easiest way to create GUI applications.
In this article, we will learn how to make an on/off switch using Tkinter.
Approach:
Make a global variable named as is_on; the default value is True, which indicates the switch is ON.
Make two Image Objects; one object has “on image” and another one has “off image”.
Create a button that has “on image” as default; set the border width to be zero.
Make a function that will change the button image, using the config() method.
The function will check, whether the is_on value is True or False
Image link:
Switch On
Switch Off
Below is the Implementation:
Python3
# Import Modulefrom tkinter import * # Create Objectroot = Tk() # Add Titleroot.title('On/Off Switch!') # Add Geometryroot.geometry("500x300") # Keep track of the button state on/off#global is_onis_on = True # Create Labelmy_label = Label(root,    text = "The Switch Is On!",    fg = "green",    font = ("Helvetica", 32)) my_label.pack(pady = 20) # Define our switch functiondef switch():    global is_on         # Determine is on or off    if is_on:        on_button.config(image = off)        my_label.config(text = "The Switch is Off",                        fg = "grey")        is_on = False    else:               on_button.config(image = on)        my_label.config(text = "The Switch is On", fg = "green")        is_on = True # Define Our Imageson = PhotoImage(file = "on.png")off = PhotoImage(file = "off.png") # Create A Buttonon_button = Button(root, image = on, bd = 0,                   command = switch)on_button.pack(pady = 50) # Execute Tkinterroot.mainloop()
Output:
adnanirshad158
Python Tkinter-exercises
Python-tkinter
Python
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
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 | Get unique values from a list
Python | datetime.timedelta() function
PyQt5 - Finding the item through text in ComboBox - GeeksforGeeks

22 Apr, 2020
In this article we will see how we can find the item index with the help of text in it. We know we can add items with the help of addItem and addItems method, in order to find the item with the help of findText method.
Syntax : combo_box.findText(text)
Argument : It takes string as argument.
Return : It return integer i.e index of text if text doesn’t exist it return -1
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, 120, 30)          # geek list        geek_list = ["Geek", "Geeky Geek", "Legend Geek", "Ultra Legend Geek"]          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # text        text = "Legend Geek"          # finding index of text        index = self.combo_box.findText(text)          # label to show index        label = QLabel(text + " index : " + str(index), self)          # setting geometry of label        label.setGeometry(200, 200, 200, 30)  # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
JavaScript Sum function on the click of a button

Let’s say the following is our button −
<button type="button" onclick="addTheValue(10)">Sum </button>
</body>
We are calling the function addTheValue(10) with parameter 10 on button click. On clicking the
button, we are adding the value 10 as in the below code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/ 4.7.0/css/font-awesome.min.css">
</head>
<body>
<p>
<h1> Adding 10 each time whenever you click the Sum
Button......</h1>
</p>
<b id="firstValue">10</b>
<button type="button" onclick="addTheValue(10)">Sum </button>
<script>
   function addTheValue(secondValue) {
      var fValue = document.getElementById("firstValue");
      firstValue.innerHTML = parseInt(fValue.innerHTML) +
      parseInt(secondValue);
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now, I am going click the “Sum” button for the first time.
This will produce the following output −
IPython - IO Caching

The input and output cells on IPython console are numbered incrementally. In this chapter, let us look into IO caching in Python in detail.
In IPython, inputs are retrieved using up arrow key. Besides, all previous inputs are saved and can be retrieved. The variables _i, __i, and ___i always store the previous three input entries. In addition, In and _in variables provides lists of all inputs. Obviously _in[n] retrieves input from nth input cell. The following IPython session helps you to understand this phenomenon −
In [1]: print ("Hello")
Hello

In [2]: 2+2
Out[2]: 4

In [3]: x = 10

In [4]: y = 2

In [5]: pow(x,y)
Out[5]: 100

In [6]: _iii, _ii, _i
Out[6]: ('x = 10', 'y = 2', 'pow(x,y)')

In [7]: In
Out[7]:
['',
   'print ("Hello")',
   '2+2',
   'x = 10',
   'y = 2',
   'pow(x,y)',
   '_iii, _ii, _i',
   'In'
]
   
In [8]: In[5] 9. IPython — IO
Out[8]: 'pow(x,y)'

In [9]: _ih
Out[9]:
['',
   'print ("Hello")',
   '2+2',
   'x = 10',
   'y = 2',
   'pow(x,y)',
   '_iii, _ii, _i',
   'In',
   'In[5]',
   '_ih'
]
   
In [11]: _ih[4]
Out[11]: 'y = 2'

In [12]: In[1:4]
Out[12]: ['print ("Hello")', '2+2', 'x=10']
Similarly, single, double and triple underscores act as variables to store previous three outputs. Also Out and _oh form a dictionary object of cell number and output of cells performing action (not including assignment statements). To retrieve contents of specific output cell, use Out[n] or _oh[n]. You can also use slicing to get output cells within a range.
In [1]: print ("Hello")
Hello

In [2]: 2+2
Out[2]: 4

In [3]: x = 10

In [4]: y = 3

In [5]: pow(x,y)
Out[5]: 1000

In [6]: ___, __, _
Out[6]: ('', 4, 1000)

In [7]: Out
Out[7]: {2: 4, 5: 1000, 6: ('', 4, 1000)}

In [8]: _oh
Out[8]: {2: 4, 5: 1000, 6: ('', 4, 1000)}

In [9]: _5
Out[9]: 1000

In [10]: Out[6]
Out[10]: ('', 4, 1000)

    22 Lectures 
     49 mins

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Python – Negative index of Element in List

When it is required to get the negative index of an element in a list, the ‘len’ method and the ‘index’ method are used.
Below is a demonstration of the same −
 Live Demo
my_list = [52, 47, 18, 22, 23, 57, 13]

print("The list is :")
print(my_list)

my_key = 22
print("The value of key is ")
print(my_key)

my_result = len(my_list) - my_list.index(my_key)

print("The result is :")
print(my_result)
The list is :
[52, 47, 18, 22, 23, 57, 13]
The value of key is
22
The result is :
4
A list of integers is defined and is displayed on the console.
A list of integers is defined and is displayed on the console.
A key is defined and is displayed on the console.
A key is defined and is displayed on the console.
The difference between the length of the list and element present at specific key is determined.
The difference between the length of the list and element present at specific key is determined.
This is assigned to a variable.
This is assigned to a variable.
This is displayed as output on the console.
This is displayed as output on the console.
Tryit Editor v3.7

Tryit: Transition + transform
NEXTMONTH function

Returns a table that contains a column of all dates from the next month, based on the first date in the dates column in the current context.
NEXTMONTH (<dates>) 

dates
A column that contains dates.
A table containing a single column of date values.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
= CALCULATE (
   SUM (Sales [Sales Amount]), NEXTMONTH (Sales [Date])
)

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
SIN() and COS() Function in SQL Server

29 Sep, 2020
1. SIN() Function :The SIN() function returns the sine of a number.
Syntax :
SIN(number)
Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the float_expression of the sine of a number.
Example-1 :When the argument holds a positive number.
SELECT SIN(5);
Output :
-0.95892427466313845
Example-2 :When the argument holds a negative number.
SELECT SIN(-5);
Output :
0.95892427466313845
Example-3 :When the PI() function is the argument.
SELECT SIN(PI());
Output :
1.2246467991473532E-16
Example-4 :When the argument passed is an expression.
SELECT SIN(4 * 3);
Output :
-0.53657291800043494
2. COS() FunctionThe COS() function returns the cosine of a number.
Syntax :
COS(number)
Parameter : Required. A numeric value.number : It is a numeric value.Returns : It returns the cosine of a number.
Example-1 :When the argument holds a positive number.
SELECT COS(4);
Output :
-0.65364362086361194
Example-2 :When the argument is a fractional component.
SELECT COS(2.53);
Output :
-0.81873459927738157
Example-3 :When the PI() function is the argument.
SELECT COS(PI());
Output :
-1
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows
Python Program to generate one-time password (OTP)

21 Aug, 2021
One-time Passwords (OTP) is a password that is valid for only one login session or transaction in a computer or a digital device. Now a days OTP’s are used in almost every service like Internet Banking, online transactions, etc. They are generally combination of 4 or 6 numeric digits or a 6-digit alphanumeric. 
random() function can be used to generate random OTP which is predefined in random library. Let’s see how to generate OTP using Python.
Used Function:random.random(): This function returns any random number between 0 to 1. math.floor(): It returns floor of any floating number to a integer value.Using the above function pick random index of string array which contains all the possible candidates of a particular digit of the OTP.
Example #1 : Generate 4 digit Numeric OTP  
Python3
# import libraryimport math, random # function to generate OTPdef generateOTP() :     # Declare a digits variable     # which stores all digits    digits = "0123456789"    OTP = ""    # length of password can be changed   # by changing value in range    for i in range(4) :        OTP += digits[math.floor(random.random() * 10)]     return OTP # Driver codeif __name__ == "__main__" :         print("OTP of 4 digits:", generateOTP())
Output: 
OTP of 4 digits: 3211
Example #2: Generate alphanumeric OTP of length 6  
Python3
# import libraryimport math, random # function to generate OTPdef generateOTP() :     # Declare a string variable     # which stores all string    string = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'    OTP = ""    length = len(string)    for i in range(6) :        OTP += string[math.floor(random.random() * length)]     return OTP # Driver codeif __name__ == "__main__" :         print("OTP of length 6:", generateOTP())
Output: 
OTP of length 6: pyelJl
Example #3: Using String constants
Python3
# Importing random to generate# random string sequenceimport random    # Importing string library functionimport string    def rand_pass(size):            # Takes random choices from    # ascii_letters and digits    generate_pass = ''.join([random.choice( string.ascii_uppercase +                                            string.ascii_lowercase +                                            string.digits)                                            for n in range(size)])                                return generate_pass    # Driver Code password = rand_pass(10)print(password)
Output: 
2R8gaoDKqn
 
simmytarika5
ruhelaa48
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to replace values of select return in MySQL?

You can use select case statement for this. The syntax is as follows.
select yourColumnName1,yourColumnName2,...N,
case when yourColumnName=1 then 'true'
else 'false'
end as anyVariableName
from yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table selectReturnDemo
-> (
-> Id int,
-> Name varchar(100),
-> isGreaterthan18 tinyint(1)
-> );
Query OK, 0 rows affected (0.62 sec)
Now you can insert some records in the table using insert command. The query is as follows.
mysql> insert into selectReturnDemo values(1,'Carol',0);
Query OK, 1 row affected (0.23 sec)

mysql> insert into selectReturnDemo values(2,'Bob',1);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectReturnDemo values(3,'Mike',1);
Query OK, 1 row affected (0.18 sec)

mysql> insert into selectReturnDemo values(4,'David',0);
Query OK, 1 row affected (0.21 sec)

mysql> insert into selectReturnDemo values(5,'Adam',1);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from selectReturnDemo;
The following is the output.
+------+-------+-----------------+
| Id   | Name  | isGreaterthan18 |
+------+-------+-----------------+
| 1    | Carol | 0               |
| 2    | Bob   | 1               |
| 3    | Mike  | 1               |
| 4    | David | 0               |
| 5    | Adam  | 1               |
+------+-------+-----------------+
5 rows in set (0.00 sec)
Here is the query to replace value with select return. The query is as follows.
mysql> select Id,Name,
-> case when isGreaterthan18=1 then 'true'
-> else 'false'
-> end as AgeIsGreaterthan18
-> from selectReturnDemo;
The following is the output.
+------+-------+--------------------+
| Id   | Name  | AgeIsGreaterthan18 |
+------+-------+--------------------+
| 1    | Carol | false              |
| 2    | Bob   | true               |
| 3    | Mike  | true               |
| 4    | David | false              |
| 5    | Adam  | true               |
+------+-------+--------------------+
5 rows in set (0.00 sec)
Python List count() method

03 Aug, 2021
Python List count() is an inbuilt function in Python that returns the count of how many times a given object occurs in a List. The count() function is used to count elements on a list as well as a string.
Syntax: 
list_name.count(object) 
Parameters: 
The object is the things whose count is to be returned. 
Returns: 
count() method returns the count of how many times object occurs in the list.
Exception: 
If more then 1 parameter is passed in count() method, it returns a TypeError.
Python3
# Python3 program to count the number of times# an object appears in a list using count() method list1 = [1, 1, 1, 2, 3, 2, 1] # Counts the number of times 1 appears in list1print(list1.count(1)) list2 = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b'] # Counts the number of times 'b' appears in list2print(list2.count('b')) list3 = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat'] # Counts the number of times 'Cat' appears in list3print(list3.count('Cat'))
Output:
4
3
2
Python3
# Python3 program to demonstrate# the error in count() method list1 = [1, 1, 1, 2, 3, 2, 1] # Error when two parameters is passed.print(list1.count(1, 2))
Output:
Traceback (most recent call last):
  File "/home/41d2d7646b4b549b399b0dfe29e38c53.py", line 7, in 
    print(list1.count(1, 2))  
TypeError: count() takes exactly one argument (2 given)
Python3
# Python3 program to count the number of times# an object appears in a list using count() method list1 = [ ('Cat', 'Bat'), ('Sat', 'Cat'), ('Cat', 'Bat'),          ('Cat', 'Bat', 'Sat'), [1, 2], [1, 2, 3], [1, 2] ] # Counts the number of times 'Cat' appears in list1print(list1.count(('Cat', 'Bat'))) # Count the number of times sublist# '[1, 2]' appears in list1print(list1.count([1, 2]))
Output: 
2
2
 Let’s say we want to count each element in a list and store it in another list or say dictionary. 
Python3
# Python3 program to count the number of times# an object appears in a list using count() method lst = ['Cat', 'Bat', 'Sat', 'Cat', 'Mat', 'Cat', 'Sat'] # To get the number of occurrences# of each item in a listprint ([ [l, lst.count(l)] for l in set(lst)]) # To get the number of occurrences# of each item in a dictionaryprint (dict( (l, lst.count(l) ) for l in set(lst)))
Output:
[['Mat', 1], ['Cat', 3], ['Sat', 2], ['Bat', 1]]
{'Bat': 1, 'Cat': 3, 'Sat': 2, 'Mat': 1}
AmiyaRanjanRout
Python-Built-in-functions
python-list
python-list-functions
Python
python-list
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 ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Program to match vowels in a string using regular expression in Java

You can group all the required characters to match within the square braces “[ ]” i.e. The metacharacter/sub-expression “[ ]” matches all the specified characters. Therefore, to match all the letters specify the vowel letters within these as shown below −
[aeiouAEIOU]
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchVowels {
   public static void main( String args[] ) {
      String regex = "[aeiouAEIOU]";
      System.out.println("Enter input string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Compiling the regular expression
      Pattern.compile(regex);
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("The input string contains vowels");
      } else {
         System.out.println("The input string does not contain vowels");
      }
   }
}
Enter input string:
hello how are you welcome
The input string contains vowels
import java.util.Scanner;
public class Test {
   public static void main( String args[] ) {
      String regex = "[aeiouAEIOU]";
      System.out.println("Enter input string: ");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      boolean result = input.matches(regex);
      if(result) {
         System.out.println("The input string contains vowels");
      } else {
         System.out.println("The input string does not contain vowels");
      }
   }
}
Enter input string:
hello how are you welcome
The input string does not contain vowels
p5.js | pow() function

08 Apr, 2019
The pow() function in p5.js is used to calculate the power of a number to the given number. It is an efficient way of multiplying numbers by themselves (or their reciprocals) in large quantities.
Syntax
pow( n, e )

Parameters: The function accepts two parameters as mentioned above and described below:
n: This parameter stores the base of the exponential expression.
e: This parameter stores the power by which to raise the base.
Below program illustrates the pow() function in p5.js:
Example: This example uses pow() function to calculate power of a number.
function setup() {      // Create Canvas of size 270*80      createCanvas(350, 80);}   function draw() {          // Set the background color    background(220);          // Initialize the parameter      let n = 3;    let e = 4;          // Call to pow() function    let y = pow(n, e);          // Set the size of text    textSize(16);          // Set the text color    fill(color('red'));          text("Given number is " + n + " and exponent is "             +  e + " ", 50, 30);    text("Computed Number is : " + y, 50, 50);}
Output:
Reference: https://p5js.org/reference/#/p5/pow
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to mount usb drive in a linux system

Do you know “how to use USB memory sticks with Linux”, If you are not sure then this article describes “how to mount USB drive on a Linux system with command line interface”
Universal serial bus, or USB (also known as Flash drive), is an electronic communications protocol that is commonly used in computer accessories and other small devices. If you have an up-to-date Linux system and a modern Desktop environment, your device should show up on your desktop, with no need to open a console. There are few important factors which are involved in learning how to mount USB drive with Linux machine.
Following are the step by step instructions to understand further –
After you plug in your USB device to your Linux system USB port, It will add new block device into /dev/ directory. To verify it, use the following command –
$ sudo fdisk -l
The sample output should be like this –
Disk /dev/sdb: 15.7 GB, 15664676864 bytes
255 heads, 63 sectors/track, 1904 cylinders, total 30595072 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Device Boot Start End Blocks Id System
/dev/sdb1 * 32 30595071 15297520 c W95 FAT32 (LBA)
We can observe from the above result that, device boot, blocks, id and system format are displayed.
To mount the USB, use the following command –
$ mount /dev/sdb1 /mnt
To create a directory in the mounted device, use the following commands –
$ cd /mnt
/mnt$ mkdir john
The above command creates a directory called john in USB device.
To delete a directory in USB, use the following command –
/mnt$ rmdir john
You should unmount the device first to format the USB device, then use the following command to unmount the device –
$ sudo umount /dev/sdb1
Now use either of the commands as per file system based on your requirement. To format a USB drive, users generally prefer VFAT or NTFS file systems because they can be easily mounted on Windows operating systems and Linux systems.
To format USB with vFat File System, use the following command –
$ sudo mkfs.vfat /dev/sdb1
To format a USB Flash Drive with NTFS file system, use the following command –
$ sudo mkfs.ntfs /dev/sdb1
To format a USB with EXT4 file system, use the following command –
$ sudo mkfs.ext4 /dev/sdb1
Congratulations! Now, you know “How to Mount USB Drive in a Linux System?”. We’ll learn more about these types of commands in our next Linux post. Keep reading!
How to check whether a stored procedure exist in MySQL?

Let us first create a stored procedure −
mysql> DELIMITER //
mysql> CREATE PROCEDURE ExtenddatesWithMonthdemo(IN date1 datetime, IN NumberOfMonth int )
   -> BEGIN
   -> SELECT DATE_ADD(date1,INTERVAL NumberOfMonth MONTH) AS ExtendDate;
   -> END;
   -> //
Query OK, 0 rows affected (0.20 sec)
mysql> DELIMITER ;
Now you check whether the stored procedure exists with the help SHOW CREATE command.
The query is as follows −
mysql> SHOW CREATE PROCEDURE ExtenddatesWithMonthdemo;
The following is the output displaying the details of the stored procedure we created above:
+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| Procedure                | sql_mode                                   | Create Procedure                                                                                                                        | character_set_client | collation_connection | Database Collation |
+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
| ExtenddatesWithMonthdemo | STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION | CREATE DEFINER = `root`@`%` PROCEDURE `ExtenddatesWithMonthdemo`(IN date1 datetime, IN NumberOfMonth int )
BEGIN
SELECT DATE_ADD(date1,INTERVAL NumberOfMonth MONTH) AS ExtendDate;
END | utf8 | utf8_general_ci | utf8_general_ci |
+--------------------------+--------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)
Call the stored procedure with the help of the CALL command. The query is as follows −
mysql> call ExtenddatesWithMonthdemo('2019-02-13',6);
+---------------------+
| ExtendDate          |
+---------------------+
| 2019-08-13 00:00:00 |
+---------------------+
1 row in set (0.10 sec)
Query OK, 0 rows affected (0.12 sec)
Inserting random numbers into a table in MySQL?

To insert random numbers, use RAND() function from MySQL. Let us first create a table −
mysql> create table DemoTable
(
   Value int
);
Query OK, 0 rows affected (0.46 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.08 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
|    10 |
|    20 |
|    30 |
+-------+
3 rows in set (0.00 sec)
Let us insert random numbers into a table in MySQL −
mysql> update DemoTable set Value=FLOOR(@number * rand()) + 1;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check table records once again −
mysql> select *from DemoTable;
This will produce the following output −
+-------+
| Value |
+-------+
|     2 |
|     2 |
|     1 |
+-------+
3 rows in set (0.00 sec)
How to disable close button on a JFrame in Java?

To disable the close button, let us first create a frame −
JFrame frame = new JFrame("Login!");
Use the setDefaultCloseOperation() to set the status of the close button. Set it to DO_NOTHING_ON_CLOSE to disable it −
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
The following is an example to disable close button on a JFrame in Java −
package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Login!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("DeptId", SwingConstants.CENTER);
      label2 = new JLabel("SSN", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField deptid = new JTextField(20);
      JTextField ssn = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1); frame.add(label2); frame.add(label3); frame.add(deptid); frame.add(ssn); frame.add(passwd);
      frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setSize(550, 400);
      frame.setVisible(true);
   }
}
The output is as follows displaying the close button but it won’t work since we disabled it above −
Subset Sum Problem

In this problem, there is a given set with some integer elements. And another some value is also provided, we have to find a subset of the given set whose sum is the same as the given sum value.
Here backtracking approach is used for trying to select a valid subset when an item is not valid, we will backtrack to get the previous subset and add another element to get the solution.
Input:
This algorithm takes a set of numbers, and a sum value.
The Set: {10, 7, 5, 18, 12, 20, 15}
The sum Value: 35
Output:
All possible subsets of the given set, where sum of each element for every subsets is same as the given sum value.
{10,  7,  18}
{10,  5,  20}
{5,  18,  12}
{20,  15}
subsetSum(set, subset, n, subSize, total, node, sum)
Input − The given set and subset, size of set and subset, a total of the subset, number of elements in the subset and the given sum.
Output − All possible subsets whose sum is the same as the given sum.
Begin
   if total = sum, then
      display the subset
      //go for finding next subset
      subsetSum(set, subset, , subSize-1, total-set[node], node+1, sum)
      return
   else
      for all element i in the set, do
         subset[subSize] := set[i]
         subSetSum(set, subset, n, subSize+1, total+set[i], i+1, sum)
      done
End
#include <iostream>
using namespace std;

void displaySubset(int subSet[], int size) {
   for(int i = 0; i < size; i++) {
      cout << subSet[i] << "  ";
   }
   cout << endl;
}

void subsetSum(int set[], int subSet[], int n, int subSize, int total, int nodeCount ,int sum) {
   if( total == sum) {
      displaySubset(subSet, subSize);     //print the subset
      subsetSum(set,subSet,n,subSize-1,total-set[nodeCount],nodeCount+1,sum);     //for other subsets
      return;
   }else {
      for( int i = nodeCount; i < n; i++ ) {     //find node along breadth
         subSet[subSize] = set[i];
         subsetSum(set,subSet,n,subSize+1,total+set[i],i+1,sum);     //do for next node in depth
      }
   }
}

void findSubset(int set[], int size, int sum) {
   int *subSet = new int[size];     //create subset array to pass parameter of subsetSum
   subsetSum(set, subSet, size, 0, 0, 0, sum);
   delete[] subSet;
}

int main() {
   int weights[] = {10, 7, 5, 18, 12, 20, 15};
   int size = 7;
   findSubset(weights, size, 35);
}
10   7  18
10   5  20
5   18  12
20  15
Pre & post increment operator behavior in C, C++, Java, and C#

The Pre increment and post increment both operators are used as increment operations. The pre increment operator is used to increment the value of some variable before using it in an expression. In the pre increment the value is incremented at first, then used inside the expression.
if the expression is a = ++b; and b is holding 5 at first, then a will hold 6. Because increase b by 1, then set the value of a with it.
#include <iostream>
using namespace std;
main () {
   int a, b = 15;
   a = ++b;
   cout << a;
}
16
#include <stdio.h>
main () {
   int a, b = 15;
   a = ++b;
   printf(“%d”, a);
}
16
public class IncDec {
   public static void main(String[] args) {
      int a, b = 15;
      a = ++b;
      System.out.println(“” + a);
   }
}
16
using System;
namespace IncDec {
   class Inc {
      static void Main() {
         int a, b = 15;
          a = ++b;
          Console.WriteLine(""+a);
       }
   }
}
16
The post increment operator is used to increment the value of some variable after using it in an expression. In the post increment the value is used inside the expression, then incremented by one.
if the expression is a = b++; and b is holding 5 at first, then a will also hold 5. Because increase b by 1 after assigning it into a.
#include <iostream>
using namespace std;
main () {
   int a, b = 15;
   a = b++;
   cout << a;
   cout << b;
}
15
16
#include <stdio.h>
main () {
   int a, b = 15;
   a = ++b;
   printf(“%d”, a);
   printf(“%d”, b);
}
15
16
public class IncDec {
   public static void main(String[] args) {
      int a, b = 15;
      a = ++b;
      System.out.println(“” + a);
      System.out.println(“” + b);
   }
}
15
16
using System;
namespace IncDec {
   class Inc {
      static void Main() {
         int a, b = 15;
         a = ++b;
         Console.WriteLine(""+a);
         Console.WriteLine(""+b);
     }
   }
}
15
16
DAX Filter - HASONEFILTER function

Returns TRUE when the number of directly filtered values on columnName is one and only one. Otherwise, returns FALSE.
HASONEFILTER (<columnName>) 

columnName
The name of an existing column, using standard DAX syntax. It cannot be an expression.
TRUE or FALSE.
DAX HASONEFILTER function is similar to DAX HASONEVALUE function, with the difference that HASONEFILTER works by a direct filter, while HASONEVALUE works based on crossfilters.
= HASONEFILTER (Sales[Product]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
JavaScript - RegExp multiline Property

multiline is a read-only boolean property of RegExp objects. It specifies whether a particular regular expression performs multiline matching, i.e., whether it was created with the "m" attribute.
Its syntax is as follows −
RegExpObject.multiline

Returns "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Try the following example program.
<html>   
   <head>
      <title>JavaScript RegExp multiline Property</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var re = new RegExp( "string" );
         
         if ( re.multiline ) {
            document.write("Test1-multiline property is set"); 
         } else {
            document.write("Test1-multiline property is not set"); 
         }
         re = new RegExp( "string", "m" );
         
         if ( re.multiline ) {
            document.write("<br/>Test2-multiline property is set"); 
         } else {
            document.write("<br/>Test2-multiline property is not set"); 
         }
      </script>      
   </body>
</html>
Test1 - multiline property is not set
Test2 - multiline property is set


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Redis - Hash Hmset Command

Redis HMSET command is used to set the specified fields to their respective values in the hash stored at the key. This command overwrites any existing fields in the hash. If the key does not exist, a new key holding a hash is created.
Simple string reply.
Following is the basic syntax of Redis HMSET command.
redis 127.0.0.1:6379> HMSET KEY_NAME FIELD1 VALUE1 ...FIELDN VALUEN

redis 127.0.0.1:6379> HMSET myhash field1 "foo" field2 "bar" 
OK 
redis 127.0.0.1:6379> HGET myhash field1 
"foo" 
redis 127.0.0.1:6379> HGET myhash field2 
"bar"


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Hello World Program in Java

Let us look at a simple code that will print the words Hello World.
Online Demo
public class MyFirstJavaProgram {

   /* This is my first java program.
    * This will print 'Hello World' as the output
    */

   public static void main(String []args) {
      System.out.println("Hello World"); // prints Hello World
   }
}
Let's look at how to save the file, compile, and run the program. Please follow the subsequent steps −
Open notepad and add the code as above.
Open notepad and add the code as above.
Save the file as − MyFirstJavaProgram.java.
Save the file as − MyFirstJavaProgram.java.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Open a command prompt window and go to the directory where you saved the class. Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption − The path variable is set).
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption − The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
You will be able to see ' Hello World ' printed on the window.
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World
Difference between count(*) and count(columnName) in MySQL?

The count(*) returns all rows whether column contains null value or not while count(columnName) returns the number of rows except null rows.
Let us first create a table.
Following is the query
mysql> create table ifNotNullDemo
   -> (
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.54 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into ifNotNullDemo values('Chris');
Query OK, 1 row affected (0.15 sec)

mysql> insert into ifNotNullDemo values('');
Query OK, 1 row affected (0.13 sec)

mysql> insert into ifNotNullDemo values('Robert');
Query OK, 1 row affected (0.24 sec)

mysql> insert into ifNotNullDemo values(null);
Query OK, 1 row affected (0.30 sec)

mysql> insert into ifNotNullDemo values(0);
Query OK, 1 row affected (0.16 sec)
Following is the query to display all records from the table using select statement:
mysql> select *from ifNotNullDemo;
This will produce the following output
+--------+
| Name   |
+--------+
| Chris  |
|        |
| Robert |
| NULL   |
| 0      |
+--------+
5 rows in set (0.00 sec)
Case 1: Following is the demo of count(*) that includes null as well in the count:
mysql> select count(*) from ifNotNullDemo;
This will produce the following output
+----------+
| count(*) |
+----------+
| 5        |
+----------+
1 row in set (0.02 sec)
Case 2: Following is the query for count(columnName).
mysql> select count(Name) from ifNotNullDemo;
This will produce the following output
+-------------+
| count(Name) |
+-------------+
| 4           |
+-------------+
1 row in set (0.00 sec)