code-rag-bench/online-tutorials huggingface dataset:
How to create custom color maps in Java using OpenCV?

The applyColorMap() method of the Imgproc class applies specified color map to the given image. This method accepts three parameters −
Two Mat objects representing the source and destination images.
Two Mat objects representing the source and destination images.
An integer variable representing the type of the color map to be applied.
An integer variable representing the type of the color map to be applied.
You can pass any of the following as color map value to this method.
COLORMAP_AUTUMN, COLORMAP_BONE, COLORMAP_COOL, COLORMAP_HOT,
COLORMAP_HSV, COLORMAP_JET, COLORMAP_OCEAN , COLORMAP_PARULA,
COLORMAP_PINK, COLORMAP_RAINBOW, COLORMAP_SPRING,
COLORMAP_SUMMER, COLORMAP_WINTER.
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
public class CustomColorMaps {
   public static void main(String args[]) {
      // Loading the OpenCV core library
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      // Reading the Image from the file and storing it in to a Matrix object
      String file ="D:\\images\\cat.jpg";
      Mat src = Imgcodecs.imread(file);
      // Creating an empty matrix to store the result
      Mat dst = new Mat();
      // Applying color map to an image
      Imgproc.applyColorMap(src, dst, Imgproc. COLORMAP_PINK);
      // Writing the image
      Imgcodecs.imwrite("D:\\images\\color_map.jpg", dst);
      System.out.println("Image processed");
   }
}
On executing, the above program generates the following output −
Java Program to calculate Sum of squares of first n natural numbers

To calculate the sum of squares of first n natural numbers, the Java code is as follows −
 Live Demo
import java.io.*;
import java.util.*;
public class Demo{
   public static int sum_of_squares(int val){
      return (val * (val + 1) / 2) * (2 * val + 1) / 3;
   }
   public static void main(String[] args){
      int val = 8;
      System.out.println("The sum of squares of first 8 natural numbers is ");
      System.out.println(sum_of_squares(val));
   }
}
The sum of squares of first 8 natural numbers is
204
A class named Demo contains a function named ‘sum_of_squares’. This function is used to add up
the first ‘n’ natural numbers. This returns the sum of the numbers. In the main function, a value for ‘n’ is defined and the function is called with this ‘n’ value. Relevant output is displayed on the console.
Find and replace a part of URL records in MySQL?

The simplest way to replace records is using MySQL REPLACE() −
mysql> create table DemoTable2025
   -> (
   -> URL text
   -> );
Query OK, 0 rows affected (0.88 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2025 values('http=//www.facebook.com');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable2025 values('http=//www.google.com');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable2025 values('http=//www.gmail.com');
Query OK, 1 row affected (0.26 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2025;
This will produce the following output −
+-------------------------+
| URL                     |
+-------------------------+
| http=//www.facebook.com |
| http=//www.google.com   |
| http=//www.gmail.com    |
+-------------------------+
3 rows in set (0.00 sec)
Here is the query to find and replace a part of URL records −
mysql> update DemoTable2025
   -> set URL=replace(URL,'http=','https:');
Query OK, 3 rows affected (0.21 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again −
mysql> select *from DemoTable2025;
This will produce the following output −
+--------------------------+
| URL                      |
+--------------------------+
| https://www.facebook.com |
| https://www.google.com   |
| https://www.gmail.com    |
+--------------------------+
3 rows in set (0.00 sec)
Can we define a parameterized constructor in an abstract class in Java?

Yes, we can define a parameterized constructor in an abstract class.
We need to make sure that the class which is extending an abstract class have a constructor and it can call the superclass parameterized constructor.
We can call the superclass parameterized constructor in a subclass by using super() call.
If we are not placing super() call in the subclass constructor, a compile-time error will occur.
Live Demo
abstract class AbstractClassTest {
   AbstractClassTest(int a) { // Parameterized Constructor
      System.out.println("Parameterized Constructor of an abstract class a="+ x);
   }
}
public class Test extends AbstractDemo {
   Test() {
      super(20);
      System.out.println("Test Class Constructor");
   }
   public static void main(String[] args) {
      Test obj = new Test();
   }
}
In the above example, we must place a super() call in the subclass constructor (Test), if not a compile-time error will occur.
Parameterized Constructor of an abstract class a=20
Test Class Constructor
What is the maximum size of list in Python?

Maximum length of a list is platform dependent and depends upon address space and/or RAM. The maxsize constant defined in sys module returns 263-1 on 64 bit system.
>>> import sys
>>> sys.maxsize
   9223372036854775807
The largest positive integer supported by the platform's Py_ssize_t type, is the maximum size lists, strings, dicts, and many other containers can have.
Python | Split flatten String List - GeeksforGeeks

07 Feb, 2022
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Lets discuss certain ways in which this task can be performed.Method #1 : Using list comprehension + split() + extend() The combination of above functions can be used to perform this task. In this, we perform the task of split, using split() and add split elements in list using extend(). 
Python3
# Python3 code to demonstrate working of# Split flatten String List# Using list comprehension + split() + extend()     # initializing listtest_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS'] # printing original listprint("The original list is : " + str(test_list)) # Split flatten String List# Using list comprehension + split() + extend()res = [][res.extend(idx.split("-")) for idx in test_list] # printing resultprint("The String List after extension : " + str(res))
The original list is : ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
The String List after extension : ['gfg', 'is', 'best', 'for', 'all', 'geeks', 'and', 'CS']
 
 Method #2 : Using split() + join() This is one of the way in which this task can be performed. In this, we perform the task of extension using join() and split(). 
Python3
# Python3 code to demonstrate working of# Split flatten String List# Using split() + join()     # initializing listtest_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS'] # printing original listprint("The original list is : " + str(test_list)) # Split flatten String List# Using split() + join()res = '-'.join(test_list).split('-') # printing resultprint("The String List after extension : " + str(res))
The original list is : ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
The String List after extension : ['gfg', 'is', 'best', 'for', 'all', 'geeks', 'and', 'CS']
 
saurabh1990aror
Python list-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
logger - Unix, Linux Command

Options:




The
 logger
utility exits 0 on success, and >0 if an error occurs.


Valid facility names are: auth, authpriv (for security information of
a sensitive nature), cron, daemon, ftp, kern, lpr, mail, news,
security (deprecated synonym for auth), syslog, user, uucp, and local0
to local7, inclusive.


Valid level names are):
alert, crit, debug, emerg, err, error (deprecated synonym for err),
info, notice, panic (deprecated synonym for emerg), warning,
warn (deprecated synonym for warning).
For the priority order and intended purposes of these levels, see
syslog(3).

logger System rebooted

logger -p local0.notice -t HOSTIDM -f /dev/idmc


logger -p local0.notice -t HOSTIDM -f /dev/idmc


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
C# Orderby Descending

Use Orderby descending in C# to sort elements in descending order.
The following is our list −
IList<Employee> emp = new List<Employee>() {
new Employee() { EmployeeRank = 3, EmpName = "Tom", EmpMarks = 90 } ,
new Employee() { EmployeeRank = 4, EmpName = "Katie", EmpMarks = 95 }
};
Now to sort the list according to Student name, use Orderby. The default is ascending, therefore for descending order, use descending.
var res = from str in emp orderby str.EmpName descending select str;
Here is the complete code.
 Live Demo
using System;
using System.Linq;
using System.Collections.Generic;
public class Demo {
   public static void Main() {
      IList<Employee> emp = new List<Employee>() {
         new Employee() { EmployeeRank = 4, EmpName = "Amit", EmpMarks = 90 } ,
         new Employee() { EmployeeRank = 05, EmpName = "Raman", EmpMarks = 95 }
      };
      var res = from str in emp orderby str.EmpName descending select str;
      Console.WriteLine("Student List (Descending Order):");
      foreach (var list in res)
      Console.WriteLine(list.EmpName);
   }
}

public class Employee {
   public int EmployeeRank { get; set; }
   public string EmpName { get; set; }
   public int EmpMarks { get; set; }
}
Student List (Descending Order):
Raman
Amit
Average of even numbers till a given even number?

To find the average of even numbers till a given even number, we will add all the even number till the given number and t count the number of even numbers. Then divide the sum by the number of even numbers.
Average of even numbers till 10 is 6 i.e.
2 + 4 + 6 + 8 + 10 = 30 => 30/ 5 = 6
There are two methods for calculating the average of even number till n which is an
even number.
Using Loops
Using Formula
To calculate the average of even numbers till n, we will add all even numbers till n and then divide in by the number of even number till than.
Program to calculate the average of even natural numbers till n −
 Live Demo
#include <stdio.h>
int main() {
   int n = 14,count = 0;
   float sum = 0;
   for (int i = 1; i <= n; i++) {
      if(i%2 == 0) {
         sum = sum + i;
         count++;
      }
   }
   float average = sum/count;
   printf("The average of even numbers till %d is %f",n, average);
   return 0;
}
The average of even numbers till 14 is 8.000000
To calculate the average of even numbers till n we can use a mathematical formula (n+2)/2 where n is an even number which is the given condition in our problem.
Program to calculate the average of n even natural numbers −
 Live Demo
#include <stdio.h>
int main() {
   int n = 15;
   float average = (n+2)/2;
   printf("The average of even numbers till %d is %f",n, average);
   return 0;
}
The average of even numbers till 14 is 8.000000
Best Time to Buy and Sell Stock in Python

Suppose we have an array A, here A[i] is indicating the price of a given stock on day i. We have to find the maximum profit. We can complete at most one transaction. (Transaction means to buy and sell stocks). But we have to keep in mind that we may not engage in multiple transactions at the same time. So we have to sell the stock before buying the new one.
Suppose the array is like A = [7, 1, 5, 3, 6, 4], then the result will be 5. As we can see, if we buy on day 2 (index 1), then it will take 1 as a buying price. Then if we sell on day 5, the profit will be 6 – 1 = 5.
To solve this, follow these steps −
create two arrays leftMin, and rightMax of size same as A, and fill them with 0s
leftMin[0] = A[0]
for i in range 1 to length of A – 1, leftMin[i] = minimum of leftMin[i – 1] and A[i]
rightMax[n-1] = A[n – 1]
for i in range length of A – 1 down to 1, rightMax[i] = maximum of rightMax[i + 1] and A[i]
set answer := 0
for i in range 0 to length of A – 1, answer := max of answer and rightMax[i + 1] – leftMin[i]
return answer
Let us see the implementation to get better understanding
 Live Demo
class Solution(object):
   def maxProfit(self, prices):
      """
      :type prices: List[int]
      :rtype: int
      """
      if not prices:
         return 0
      leftMin,rightMax = [0 for i in range(len(prices))],[0 for i in range(len(prices))]
      leftMin[0] = prices[0]
      for i in range(1,len(prices)):
         leftMin[i] = min(leftMin[i-1],prices[i])
      #print(leftMin)
      rightMax[-1]= prices[-1]
      for i in range(len(prices)-2,-1,-1):
         rightMax[i] = max(rightMax[i+1],prices[i])
      #print(rightMax)
      ans = 0
      for i in range(len(prices)-1):
         ans = max(ans,rightMax[i+1]-leftMin[i])
      return ans
ob1 = Solution()
print(ob1.maxProfit([7,2,5,8,6,3,1,4,5,4,7]))
prices = [7,2,5,8,6,3,1,4,5,4,7]
6
C library function - tanh()

The C library function double tanh(double x) returns the hyperbolic tangent of x.
Following is the declaration for tanh() function.
double tanh(double x)
x − This is the floating point value.
x − This is the floating point value.
This function returns hyperbolic tangent of x.
The following example shows the usage of tanh() function.
#include <stdio.h>
#include <math.h>

int main () {
   double x, ret;
   x = 0.5;

   ret = tanh(x);
   printf("The hyperbolic tangent of %lf is %lf degrees", x, ret);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
The hyperbolic tangent of 0.500000 is 0.462117 degrees


    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
Find the Nth term of the series 5, 13, 37, 109, 325, . . . - GeeksforGeeks

28 Jan, 2022
Given a positive integer N. The task is to find Nth term of the series 5, 13, 37, 109, 325, .....
Examples:
Input: N = 5Output: 325Explanation:  From the sequence it can be seen that the 5th term is 325
Input: N = 1Output: 5Explanation: The 1st term of the given sequence is 5
Approach: The sequence formed by using the following pattern. For any value N 
TN = 4 * 3N – 1 + N
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to return Nth term// of the seriesint calcNum(int N){  return 4 * pow(3, N - 1) + 1;} // Driver Codeint main(){    int N = 5;     cout << calcNum(N);    return 0;}
// Java program to implement// the above approachimport java.util.*;public class GFG{   // Function to return Nth term  // of the series  static int calcNum(int N)  {    return 4 * (int)Math.pow(3, N - 1) + 1;  }   // Driver Code  public static void main(String args[])  {    int N = 5;    System.out.println(calcNum(N));  }} // This code is contributed by Samim Hossain Mondal.
# Python 3 program for the above approach # Function to return Nth term# of the seriesdef calcNum(N):         return 4 * pow(3, N - 1) + 1 # Driver Codeif __name__ == "__main__":     N=5     print(calcNum(N)) # This code is contributed by Abhishek Thakur.
// C# program to implement// the above approachusing System; public class GFG{   // Function to return Nth term  // of the series  static int calcNum(int N)  {    return 4 * (int)Math.Pow(3, N - 1) + 1;  }   // Driver Code  static public void Main ()  {    int N = 5;    Console.Write(calcNum(N));  }}  // This code is contributed by SHubham Singh
<script>       // JavaScript code for the above approach        // Function to return Nth term       // of the series       function calcNum(N) {           return 4 * Math.pow(3, N - 1) + 1;       }        // Driver Code       let N = 5;       document.write(calcNum(N));  // This code is contributed by Potta Lokesh   </script>
  
325
Time Complexity: O(1)Auxiliary Space: O(1)
lokeshpotta20
samim2000
athakur42u
SHUBHAMSINGH10
germanshephered48
Algo-Geek 2021
series
Algo Geek
Mathematical
Pattern Searching
Mathematical
series
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count of operation required to water all the plants
Check if the given string is valid English word or not
Lexicographically smallest string formed by concatenating any prefix and its mirrored form
Encode given String by inserting in Matrix column-wise and printing it row-wise
Sort strings on the basis of their numeric part
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
MomentJS - Is After

This method gives true or false if the given moment is after another moment.
moment().isAfter(Moment|String|Number|Date|Array);
moment().isAfter(Moment|String|Number|Date|Array, String);

var isafter = moment().isAfter();
If no param to isAfter it considers it as the current date. It gives the output as false since the current date is not after the moment compared.
var isafter = moment([2015, 10, 01]).isAfter([2014, 05, 10]);
If the given date to isAfter is less, it gives true as the date is after the another moment.
var isafter = moment([2015, 10, 01]).isAfter([2018, 05, 10]);
Here the date given to isAfter is greater than the date compared, so the output is false.
Consider the following examples to check isAfter() method with units.
var isafter = moment([2015, 10, 01]).isAfter([2011, 05, 10], 'year');
 Print
 Add Notes
 Bookmark this page
Python 3 - String count() Method

The count() method returns the number of occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
Following is the syntax for count() method −
str.count(sub, start = 0,end = len(string))

sub − This is the substring to be searched.
sub − This is the substring to be searched.
start − Search starts from this index. First character starts from 0 index. By default search starts from 0 index.
start − Search starts from this index. First character starts from 0 index. By default search starts from 0 index.
end − Search ends from this index. First character starts from 0 index. By default search ends at the last index.
end − Search ends from this index. First character starts from 0 index. By default search ends at the last index.
Centered in a string of length width.
#!/usr/bin/python3

str = "this is string example....wow!!!"
sub = 'i'
print ("str.count('i') : ", str.count(sub))
sub = 'exam'
print ("str.count('exam', 10, 40) : ", str.count(sub,10,40))
When we run above program, it produces the following result −
str.count('i') :  3
str.count('exam', 4, 40) :  1


    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
Python | shutil.which() method - GeeksforGeeks

25 Jun, 2019
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.which() method tells the path to an executable application which would be run if the given cmd was called. This method can be used to find a file on computer which is present on the PATH.
Syntax: shutil.which(cmd, mode = os.F_OK | os.X_OK, path = None)Parameters:cmd: A string representing the file.mode: This parameter specifies mode by which method should execute. os.F_OK tests existence of the path and os.X_OK Checks if path can be executed or we can say mode determines if the file exists and executable.path: This parameter specifies the path to be used, if no path is specified then the results of os.environ() are usedReturn Value: This method returns the path to an executable application
Example #1 :Using shutil.which() method to get location of Python
# Python program to explain shutil.which() method       # importing os module import os   # importing shutil module import shutil   # cmd cmd = 'python'  # Using shutil.which() methodlocate = shutil.which(cmd)  # Print resultprint(locate)
/usr/bin/python

Example #2 :Using shutil.which() method to get location of C++
# Python program to explain shutil.which() method       # importing os module import os   # importing shutil module import shutil   # cmd cmd = 'c++'  # Using shutil.which() methodlocate = shutil.which(cmd)  # Print resultprint(locate)
/usr/bin/c++

Python-shutil
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
C++ mutable keyword?

Mutable data members are those members whose values can be changed in runtime even if the object is of constant type. It is just opposite to constant.
Sometimes logic required to use only one or two data member as a variable and another one as a constant to handle the data. In that situation, mutability is very helpful concept to manage classes.
#include <iostream>
using namespace std;
code
class Test {
   public:
      int a;
   mutable int b;
   Test(int x=0, int y=0) {
      a=x;
      b=y;
   }
   void seta(int x=0) {
      a = x;
   }
   void setb(int y=0) {
      b = y;
   }
   void disp() {
      cout<<endl<<"a: "<<a<<" b: "<<b<<endl;
   }
};
int main() {
   const Test t(10,20);
   cout<<t.a<<" "<<t.b<<"\n";
   // t.a=30; //Error occurs because a can not be changed, because object is constant.
   t.b=100; //b still can be changed, because b is mutable.
   cout<<t.a<<" "<<t.b<<"\n";
   return 0;
}
RIOT.JS - Tags

RIOT works by building custom, reusable html tags. These tags are similar to Web components and are reusable across pages and web apps. When you include the RIOT framework in your HTML page, the imported js creates a riot variable pointing to a riot object. This object contains the functions which is required to interact with the RIOT.js like creating and mounting tags.
We can create and use tags in two ways.
Inline HTML − By calling riot.tag() function. This function takes the tag name and tag definition to create a tag. Tag definition can contain HTML, JavaScript and CSS etc.
Inline HTML − By calling riot.tag() function. This function takes the tag name and tag definition to create a tag. Tag definition can contain HTML, JavaScript and CSS etc.
Seperate Tag file − By storing the tag definition in tag file. This tag file contains tag definition to create a tag . This file needs to be imported inplace of riot.tag() call.
Seperate Tag file − By storing the tag definition in tag file. This tag file contains tag definition to create a tag . This file needs to be imported inplace of riot.tag() call.
<script src = "/riotjs/src/messageTag.tag" type = "riot/tag"></script<
Following is the example of inline tag.
<!DOCTYPE html>
<html>
   <head>
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/riot/3.13.2/riot+compiler.min.js"></script>
   </head>
   <body>
      <messageTag></messageTag>
      <script>
         var tagHtml = "<h1>Hello World!</h1>";
         riot.tag("messageTag", tagHtml);
         riot.mount("messageTag");
      </script>
   </body>
</html>
This will produce following result −
Following is the example of external file tag.
<messageTag>
   <h1>Hello World!</h1>
</messageTag>
<!DOCTYPE html>
<html>
   <head>
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/riot/3.13.2/riot+compiler.min.js"></script>
   </head>
   <body>
      <messageTag></messageTag>
      <script src = "messageTag.tag" type = "riot/tag"></script>
      <script>
         riot.mount("messageTag");
      </script>
   </body>
</html>
This will produce following result −
 Print
 Add Notes
 Bookmark this page
How to create a download progress bar in Tkinter?

Let’s suppose that we are creating an application which interacts with sources and files such as downloading the files, tracking the file. In order to make a progressbar for such an application, we will use the tkinter.ttk package that includes the Progressbar module.
Initially, we will instantiate an object of Progressbar which has orientation of Horizontal. Then, we will define a function to increase the value of the progressbar and keep updating it.
In the following example, we have created a download progress bar by updating its value.
#Import the required libraries
from tkinter import *
from tkinter.ttk import *
import time

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("620x400")

#Define a function
def start():
   task=10
   x=0
   while(x<task):
      time.sleep(1)
      bar['value']+=10
      x+=1
      win.update_idletasks()

bar= Progressbar(win, orient=HORIZONTAL, length=300)
bar.pack(pady=20)

#Create a button
Button(win, text="Download", command=start).pack(pady=20)

win.mainloop()
Running the code will display a download bar and once we click on the “Download” Button, it will automatically get completed.
Python - Concatenate Strings in the Given Order - GeeksforGeeks

06 Nov, 2021
Given a String List and order list, perform string concatenation in a specific order.
Input : test_list = [“best”, “Gfg”, “for”, “is”], sort_order = [1, 3, 0, 2] Output : Gfgisbestfor Explanation : Combined as per order of indices.
Input : test_list = [“best”, “Gfg”], sort_order = [1, 0] Output : Gfgbest Explanation : Combined as per order of indices.  
Method #1: Using loop
In this, we iterate order elements in the loop and perform concatenation of strings of the similar index in similar order.
Python3
# Python3 code to demonstrate working of# Concatenate Strings in Order# Using loop # initializing listtest_list = ["best", "Gfg", "for", "is", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing join ordersort_order = [1, 3, 0, 2, 4] res = ''for order in sort_order:         # concatenating by order    res += test_list[order] # printing resultprint("Ordered concatenation : " + str(res))
The original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks
Method #2: Using join() + list comprehension
In this, we perform the task of concatenation using join(), list comprehension is used for iteration of order.
Python3
# Python3 code to demonstrate working of# Concatenate Strings in Order# Using join() + list comprehension # initializing listtest_list = ["best", "Gfg", "for", "is", "geeks"] # printing original listprint("The original list is : " + str(test_list)) # initializing join ordersort_order = [1, 3, 0, 2, 4] # join() performs concatenationres = ''.join([test_list[order] for order in sort_order]) # printing resultprint("Ordered concatenation : " + str(res))
The original list is : ['best', 'Gfg', 'for', 'is', 'geeks']
Ordered concatenation : Gfgisbestforgeeks
 
kapoorsagar226
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Pandas Timestamp.date - GeeksforGeeks

08 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.date() function return a datetime object with same year, month and day as that of the given Timestamp object.
Syntax : Timestamp.date()
Parameters : None
Return : date
Example #1: Use Timestamp.date() function to return the date of the given Timestamp object as a datetime object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,           hour = 10, second = 49, tz = 'US/Central')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.date() function to return the date as a datetime object.
# return as a datetime object ts.date()
Output :
As we can see in the output, the Timestamp.date() function has returned a datetime object containing the same year, month and day as that of the given Timestamp object. Example #2: Use Timestamp.date() function to return the date of the given Timestamp object as a datetime object.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009,  month = 5, day = 31,        hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.date() function to return the date as a datetime object.
# return as a datetime object ts.date()
Output :
As we can see in the output, the Timestamp.date() function has returned a datetime object containing the same year, month and day as that of the given Timestamp object.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
NLP | Part of Speech - Default Tagging - GeeksforGeeks

11 Apr, 2022
What is Part-of-speech (POS) tagging ? It is a process of converting a sentence to forms – list of words, list of tuples (where each tuple is having a form (word, tag)). The tag in case of is a part-of-speech tag, and signifies whether the word is a noun, adjective, verb, and so on.  Default tagging is a basic step for the part-of-speech tagging. It is performed using the DefaultTagger class. The DefaultTagger class takes ‘tag’ as a single argument. NN is the tag for a singular noun. DefaultTagger is most useful when it gets to work with most common part-of-speech tag. that’s why a noun tag is recommended.  Code #1 : How it works ? 
Python3
# Loading Librariesfrom nltk.tag import DefaultTagger # Defining Tagtagging = DefaultTagger('NN') # Taggingtagging.tag(['Hello', 'Geeks'])
Output :
[('Hello', 'NN'), ('Geeks', 'NN')]
Each tagger has a tag() method that takes a list of tokens (usually list of words produced by a word tokenizer), where each token is a single word. tag() returns a list of tagged tokens – a tuple of (word, tag). How DefaultTagger works ? It is a subclass of SequentialBackoffTagger and implements the choose_tag() method, having three arguments.
list of tokens
index of the current token, to choose the tag.
list of the previous tags
  Code #2 : Tagging Sentences 
Python3
# Loading Librariesfrom nltk.tag import DefaultTagger # Defining Tagtagging = DefaultTagger('NN') tagging.tag_sents([['welcome', 'to', '.'], ['Geeks', 'for', 'Geeks']])
Output :
[[('welcome', 'NN'), ('to', 'NN'), ('.', 'NN')],
 [('Geeks', 'NN'), ('for', 'NN'), ('Geeks', 'NN')]]
Note: Every tag in the list of tagged sentences (in the above code) is NN as we have used DefaultTagger class. Code #3 : Illustrating how to untag. 
Python3
from nltk.tag import untaguntag([('Geeks', 'NN'), ('for', 'NN'), ('Geeks', 'NN')])
Output :
['Geeks', 'for', 'Geeks']
nidhi_biet
rkbhola5
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Activation functions in Neural Networks
Decision Tree Introduction with example
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
What is an array in Java?

An array is a data structure/container/object that stores a fixed-size sequential collection of elements of the same type. The size/length of the array is determined at the time of creation.
The position of the elements in the array is called as index or subscript. The first element of the array is stored at the index 0 and, the second element is at the index 1 and so on.
Each element in an array is accessed using an expression which contains the name of the array followed by the index of the required element in square brackets.
For example, if an array of five elements is created with name myArray, you can access the element of the array at index 3 as:
myArray[3]

 
 Live Demo
public class ArrayExample {
   public static void main(String args[]){
      //Declaring an array
      int[] myArray = {233, 783, 453};
      
      //Printing the array
      for(int i=0; i<myArray.length; i++){
         System.out.println(myArray[i]);
      }
   }
}
233
783
453
MongoDB regex to display records whose first five letters are uppercase?

Let us first create a collection with documents −
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"JOHN Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7edef1a844af18acdffb2")
}
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"SAM Williams"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ee011a844af18acdffb3")
}
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"CAROL Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ee101a844af18acdffb4")
}
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"Bob Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ee351a844af18acdffb5")
}
> db.upperCaseFiveLetterDemo.insertOne({"StudentFullName":"DAVID Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ee451a844af18acdffb6")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.upperCaseFiveLetterDemo.find().pretty();
This will produce the following output −
{
   "_id" : ObjectId("5cd7edef1a844af18acdffb2"),
   "StudentFullName" : "JOHN Smith"
}
{
   "_id" : ObjectId("5cd7ee011a844af18acdffb3"),
   "StudentFullName" : "SAM Williams"
}
{
   "_id" : ObjectId("5cd7ee101a844af18acdffb4"),
   "StudentFullName" : "CAROL Taylor"
}
{
   "_id" : ObjectId("5cd7ee351a844af18acdffb5"),
   "StudentFullName" : "Bob Taylor"
}
{
   "_id" : ObjectId("5cd7ee451a844af18acdffb6"),
   "StudentFullName" : "DAVID Miller"
}
Following is the query to get the count of the records whose first five letters are in uppercase −
> db.upperCaseFiveLetterDemo.find({StudentFullName : {$regex : /[A-Z]{5}/ } }).count();
This will produce the following output −
2
There are two documents with first five letters uppercase. Let us now display those documents −
> db.upperCaseFiveLetterDemo.find({StudentFullName : {$regex : /[A-Z]{5}/ } });
This will produce the following output −
{ "_id" : ObjectId("5cd7ee101a844af18acdffb4"), "StudentFullName" : "CAROL Taylor" }
{ "_id" : ObjectId("5cd7ee451a844af18acdffb6"), "StudentFullName" : "DAVID Miller" }
for loop in Objective-C

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in Objective-C programming language is −
for( init; condition; increment ) {
   statement(s);
}
Here is the flow of control in a for loop −
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
#import <Foundation/Foundation.h>
 
int main () {
   
   /* for loop execution */
   int a;
   for( a = 10; a < 20; a = a + 1 ) {
      NSLog(@"value of a: %d\n", a);
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
2013-09-07 22:34:05.044 demo[12321] value of a: 10
2013-09-07 22:34:05.044 demo[12321] value of a: 11
2013-09-07 22:34:05.044 demo[12321] value of a: 12
2013-09-07 22:34:05.044 demo[12321] value of a: 13
2013-09-07 22:34:05.044 demo[12321] value of a: 14
2013-09-07 22:34:05.044 demo[12321] value of a: 15
2013-09-07 22:34:05.044 demo[12321] value of a: 16
2013-09-07 22:34:05.044 demo[12321] value of a: 17
2013-09-07 22:34:05.044 demo[12321] value of a: 18
2013-09-07 22:34:05.044 demo[12321] value of a: 19


    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
Lambda and filter in Python Examples

In this article, we will learn about lambda expressions and filter() functions in Python 3.x. Or earlier. These functions are present in the built-in Python standard library.
An inline function may be defined by the help of lambda expressions. A lambda expression consists of the lambda keyword followed by a comma seperated list of arguments and the expression to be evaluated using the list of arguments in the following format:
 Lambda arguments: expression
Return value: The value computed by substituting arguments in the expressions.
Lambda expressions are often abbreviated by the name of anonymous functions as they are not given any name. Here no def keyword dis required for the declaration of function
Python provides a function filter() that takes a function and an iterable object as the input arguments and returns only those elements from the iterable object for which the function returns True.
filter(function , <list type>)
Return Type: a list of computed values
Let us look at some Illustration to get a better overview abut their implementation.
inp_list = ['t','u','t','o','r','i','a','l']
result = list(filter(lambda x: x!='t' , inp_list))

print(result)
['u', 'o', 'r', 'i', 'a', 'l']
Here all elements in the list other than ‘t’ are filtered by the condition and list is formed by the help of lambda expression.
inp_list = [1,2,3,4,5,6,7,8,9,10]
result = list(filter(lambda x: x%2==0 , inp_list))

print(result)
[2, 4, 6, 8, 10]
Here we filter out all the even elements from the given list and display in the form of the list by typecasting the returned value.
In this article, we learnt how to implement the lambda and filter() functions in Python 3.x. Or earlier. We also learnt about the combined usage of both functions to get the desired output.
These functions are often used together as they provide a better way to filter out output in the desired format.
Where does Array stored in JVM memory in Java?

Array is a container which can hold a fix number of entities, which are of the of the same type. Each entity of an array is known as element and, the position of each element is indicated by an integer (starting from 0) value known as index.
import java.util.Arrays;
public class ArrayExample {
   public static void main(String args[]) {
      Number integerArray[] = new Integer[3];
      integerArray[0] = 25;
      integerArray[1] = 32;
      integerArray[2] = 56;
      System.out.println(Arrays.toString(integerArray));
   }
}
[25, 32, 56]
Arrays are two types −
Single dimensional arrays: Normal arrays.
Multi-dimensional arrays: Arrays storing arrays.
JVM has five memory locations namely −
Heap − Runtime storage allocation for objects (reference types).
Stack − Storage for local variables and partial results. A stack contains frames and allocates one for each thread. Once a thread gets completed, this frame also gets destroyed. It also plays roles in method invocation and returns.
PC Registers − Program Counter Registers contains the address of an instruction that JVM is currently executing.
Execution Engine − It has a virtual processor, interpreter to interpret bytecode instructions one by one and a JIT, just in time compiler.
Native method stacks − It contains all the native methods used by the application.
As discussed, the reference types in Java are stored in heap area. Since arrays are reference types (we can create them using the new keyword) these are also stored in heap area.
In addition to primitive datatypes arrays also store reference types: Another arrays (multi-dimensional), Objects. In this case the object array/multi-dimensional stores the references of the objects/arrays init, which points to the location of the objects/arrays.
For suppose, if we have a class with name Std with constructor that accepts the name of a student and if we have defined an array of this class and populated it as shown below.
class Std {
   private String name;
   public Std(String name){
      this.name = name;
   }
}
public class Sample {
   public static void main(String args[]) throws Exception {
      //Creating an array to store objects of type Std
      Std myArray[] = new Std[3];
      //Populating the array
      myArray [0] = new Std("Ravi");
      myArray [1] = new Std("Raju");
      myArray [2] = new Std("Ramu");
   }
}
The memory of the array myArray might be like −
How to print Colored text in C++ - GeeksforGeeks

01 Jun, 2020
In C++ programming, the background of the output screen is black and text color is in white color. We can color both the background and text color in the output screen in the following ways.
Header File:
#include <windows.h>  
   or
#include <stdlib.h>

Syntax:
system("Color XY")

In the above command to change the background color change the value X of the above syntax to the corresponding color you want and to change the text color change the value Y of the above syntax to the corresponding color you want.
Below is the table for allow color in C++:
Below is the illustration of Text coloring in C++:
Program 1:
// C++ program to illustrate coloring#include <iostream>#include <windows.h>using namespace std;  // Driver Codeint main(){    // 0 for background Color(Black)    // A for text color(Green)    system("Color 0A");      // Print any message    cout << "Geeks For Geeks!";    return 0;}
Output:
Program 2:
// C++ program to illustrate coloring#include <iostream>#include <stdlib.h>using namespace std;  // Driver Codeint main(){    // Print any message    cout << "Geeks For Geeks!";      // We can print the statement first    // and then changed the color      // E for background Color(Light Yellow)    // 4 for text color(Red)    system("Color E4");      return 0;}
Output:
Program 3:
// C++ program to illustrate coloring#include <iostream>#include <stdlib.h>using namespace std;  // Driver Codeint main(){    // B for background Color(Light Aqua)    // 5 for text color(Purple)    system("Color B5");    cout << "Geeks";      // 1 for background Color(Blue)    // 6 for text color(Yellow)    system("Color 16");    cout << " For ";      // D for background Color(Light Purple)    // E for text color(Light Yellow)    system("Color DE");    cout << "Geeks";      return 0;}
Output:
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program for QuickSort
Shallow Copy and Deep Copy in C++
cin in C++
Passing a function as a parameter in C++
Generics in C++
C Program to Swap two Numbers
How to find the minimum and maximum element of a Vector using STL in C++?
Iterative Letter Combinations of a Phone Number
Const keyword in C++
How to find the minimum and maximum element of an Array using STL in C++?