code-rag-bench/online-tutorials huggingface dataset:
enum.auto() in Python

22 Apr, 2020
With the help of enum.auto() method, we can get the assigned integer value automatically by just using enum.auto() method.
Syntax : enum.auto()
Automatically assign the integer value to the values of enum class attributes.
Example #1 :In this example we can see that by using enum.auto() method, we are able to assign the numerical values automatically to the class attributes by using this method.
# import enum and autofrom enum import Enum, auto  # Using enum.auto() methodclass language(Enum):    Java = auto()    Python = auto()    HTML = auto()  print(list(language))
Output :
[,, ]
Example #2 :
# import enum and autofrom enum import Enum, auto  # Using enum.auto() methodclass language(Enum):    Cpp = auto()    JavaScript = auto()    Java = auto()    Python = auto()    HTML = auto()  print(list(language))
Output :
[,,,, ]
Python-enum
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Create a Pandas DataFrame from Lists
How to use split () in Android textview?

This example demonstrate about How to use split () in Android textview.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/name"
      android:layout_width="match_parent"
      android:hint="Enter name"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/click"
      android:text="Click"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/textview"
      android:layout_width="wrap_content"
      android:textSize="25sp"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and split the data using space regex.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   EditText name;
   Button button;
   TextView text;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.name);
      button = findViewById(R.id.click);
      text = findViewById(R.id.textview);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!name.getText().toString().isEmpty()) {
               if (name.getText().toString().length() >= 0) {
                  String[] replace = name.getText().toString().split("\\s");
                  text.setText(String.valueOf(replace[1]));
               }
            } else {
               name.setError("Plz enter name");
            }
         }
      });
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, enter the string as “Krishna sai sai” . It splited with space and returned 1st indexed value.
Click here to download the project code
SQL Query to Find Names of the Employees Whose Department Have Number of Employees Less than 2

29 Dec, 2021
In SQL, we need to find out the department wise information from the given table containing information about employees. One such data is the name of employee who belong to a department having less than 2(i.e. only 1) employees. We shall use the GROUP BY, IN and COUNT clause to achieve this. This is illustrated below. For this article, we will be using the Microsoft SQL Server as our database.
Step 1: Create a Database. For this use the below command to create a database named GeeksForGeeks.
Query:
CREATE DATABASE GeeksForGeeks
Output:
Step 2: Use the GeeksForGeeks database. For this use the below command.
Query:
USE GeeksForGeeks
Output:
Step 3: Create a table COMPANY inside the database GeeksForGeeks. This table has 4 columns namely EMPLOYEE_ID, EMPLOYEE_NAME, DEPARTMENT_NAME and SALARY containing the id, name, department and the salary of various employees.
Query:
CREATE TABLE COMPANY(
EMPLOYEE_ID INT PRIMARY KEY,
EMPLOYEE_NAME VARCHAR(10),
DEPARTMENT_NAME VARCHAR(10),
SALARY INT);
Output:
Step 4: Describe the structure of the table COMPANY.
Query:
EXEC SP_COLUMNS COMPANY;
Output:
Step 5: Insert 5 rows into the COMPANY table.
Query:
INSERT INTO COMPANY VALUES(1,'RAM','HR',10000);
INSERT INTO COMPANY VALUES(2,'AMRIT','MRKT',20000);
INSERT INTO COMPANY VALUES(3,'RAVI','HR',30000);
INSERT INTO COMPANY VALUES(4,'NITIN','MRKT',40000);
INSERT INTO COMPANY VALUES(5,'VARUN','IT',50000);
Output:
Step 6: Display all the rows of the COMPANY table.
Query:
SELECT * FROM COMPANY;
Output:
Step 7: Display the name of the employee and of his/her department belonging to a department having less than 2 i.e. 1 employee. We will use the IN clause here to compare the department names obtained from the outer query to department names obtained from the inner query. The inner query uses the GROUP BY clause and COUNT clause to count the number of employees belonging to each department. Then compare this returned count to ensure that the count is less than 2.
Syntax:
SELECT EMPLOYEE_NAME, DEPARTMENT_NAME 
FROM COMPANY WHERE DEPARTMENT_NAME IN
(SELECT DEPARTMENT_NAME FROM COMPANY
GROUP BY DEPARTMENT_NAME HAVING COUNT(*)<2);
Query:
SELECT EMPLOYEE_NAME, DEPARTMENT_NAME
FROM COMPANY WHERE DEPARTMENT_NAME IN
(SELECT DEPARTMENT_NAME FROM COMPANY GROUP
BY DEPARTMENT_NAME HAVING COUNT(*)<2);
Note – This query returns only 1 row i.e. VARUN and IT since IT has only 1 employee.
Output:
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Difference between SQL and NoSQL
Window functions in SQL
MySQL | Group_CONCAT() Function
SQL | GROUP BY
How to resize Image in Python – Tkinter?

31 Aug, 2021
Prerequisite:
Tkinter
PIL
Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
In this article, we will learn how to resize an image using python in Tkinter. In Tkinter, there is no in-built method or any package to work with images. Here we will use pillow library for images.
Let’s Understand step by step implementation:-
Import Required Library
Python3
# Import Modulefrom tkinter import *from PIL import Image, ImageTk
Read the image using the open() method in pillow library
Syntax: 
Image.open("Enter Image File Path", mode='r', **attr)
Python3
# Read the Imageimage = Image.open("Image File Path")
Resize an image using resize() method. It returns a resized copy of this image.
Syntax: 
Image.resize((width,height) , resample=3, **attr)
Python3
# Resize the image using resize() methodresize_image = image.resize((width, height))
Add Label and add resized image
Python3
img = ImageTk.PhotoImage(resize_image) # create label and add resize imagelabel1 = Label(image=img)label1.image = imglabel1.pack()
Below is the implementation: 
Python3
# Import Modulefrom tkinter import *from PIL import Image, ImageTk # Create Tkinter Objectroot = Tk() # Read the Imageimage = Image.open("Image File Path") # Resize the image using resize() methodresize_image = image.resize((width, height)) img = ImageTk.PhotoImage(resize_image) # create label and add resize imagelabel1 = Label(image=img)label1.image = imglabel1.pack() # Execute Tkinterroot.mainloop()
Output:- 
250×200
In the above example, enter the file name or path at the Image File Path and enter the value of width and height according to your need. 
 
abhishek0719kadiyan
singghakshay
Picked
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Method overloading and null error in Java

18 Apr, 2022
In Java it is very common to overload methods. Below is an interesting Java program. 
Java
public class Test{    // Overloaded methods    public void fun(Integer i)    {        System.out.println("fun(Integer ) ");    }    public void fun(String name)    {        System.out.println("fun(String ) ");    }     // Driver code    public static void main(String [] args)    {        Test mv = new Test();         // This line causes error        mv.fun(null);    }}
Output :
22: error: reference to fun is ambiguous
        mv.fun(null);
          ^
  both method fun(Integer) in Test and method fun(String) in Test match
1 error
The reason why we get compile time error in the above scenario is, here the method arguments Integer and String both are not primitive data types in Java. That means they accept null values. When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn’t happen unless we intentionally pass null value. For example see the below scenario which we follow generally while coding. 
Java
public class Test{    // Overloaded methods    public void fun(Integer i)    {        System.out.println("fun(Integer ) ");    }    public void fun(String name)    {        System.out.println("fun(String ) ");    }     // Driver code    public static void main(String [] args)    {        Test mv = new Test();                 Integer arg = null;         // No compiler error        mv.fun(arg);    }}
Output :
fun(Integer ) 
In the above scenario if the “arg” value is null due to the result of the expression, then the null value is passed to method1. Here we wouldn’t get compile time error because we are specifying that the argument is of type Integer, hence the compiler selects the method1(Integer i) and will execute the code inside that. Note: This problem wouldn’t persist when the overridden method arguments are primitive data type. Because the compiler will select the most suitable method and executes it. This article is contributed by Nageswara Rao Maridu. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
imeenalgrover
simmytarika5
Java-Overloading
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
mkdir() - Unix, Linux System Call

Unix - Home
Unix - Getting Started
Unix - File Management
Unix - Directories
Unix - File Permission
Unix - Environment
Unix - Basic Utilities
Unix - Pipes & Filters
Unix - Processes
Unix - Communication
Unix - The vi Editor
Unix - What is Shell?
Unix - Using Variables
Unix - Special Variables
Unix - Using Arrays
Unix - Basic Operators
Unix - Decision Making
Unix - Shell Loops
Unix - Loop Control
Unix - Shell Substitutions
Unix - Quoting Mechanisms
Unix - IO Redirections
Unix - Shell Functions
Unix - Manpage Help
Unix - Regular Expressions
Unix - File System Basics
Unix - User Administration
Unix - System Performance
Unix - System Logging
Unix - Signals and Traps
Unix - Useful Commands
Unix - Quick Guide
Unix - Builtin Functions
Unix - System Calls
Unix - Commands List
Unix Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
#include <sys/stat.h> 
#include <sys/types.h> 

int mkdir(const char *pathname, mode_t mode); 


int mkdir(const char *pathname, mode_t mode); 


The parameter
mode specifies the permissions to use. It is modified by the process’s
umask in the usual way: the permissions of the created directory are
(mode & ~umask & 0777). Other mode bits of the created directory depend on the operating system.
For Linux, see below.


The newly created directory will be owned by the effective user ID of the
process.  If the directory containing the file has the set-group-ID
bit set, or if the filesystem is mounted with BSD group semantics, the
new directory will inherit the group ownership from its parent;
otherwise it will be owned by the effective group ID of the process.


If the parent directory has the set-group-ID bit set then so will the
newly created directory.




There are many infelicities in the protocol underlying NFS.  Some
of these affect
mkdir(). 
mkdir (1)
mkdir (1)
chmod (2)
chmod (2)
mkdirat (2)
mkdirat (2)
mknod (2)
mknod (2)
mount (2)
mount (2)
path_resolution (2)
path_resolution (2)
rmdir (2)
rmdir (2)
stat (2)
stat (2)
umask (2)
umask (2)
unlink (2)
unlink (2)

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
Java Program for Radix Sort

Radix sort is a sorting technique that sorts the elements based on every digit in every element (or number). Based on the ones place digit (which is also known as least significant digit) and tens place digit (which is also known as most significant digit), hundreds place digit, and so on, the elements are sorted.
Following is an example for Radix Sort in Java −
 Live Demo
import java.util.*;
public class my_radix_sorting {
   static int get_max_val(int my_arr[], int arr_len) {
      int max_val = my_arr[0];
      for (int i = 1; i < arr_len; i++)
         if (my_arr[i] > max_val)
         max_val = my_arr[i];
      return max_val;
   }
   static void countSort(int my_arr[], int arr_len, int exp) {
      int result[] = new int[arr_len];
      int i;
      int count[] = new int[10];
      Arrays.fill(count,0);
      for (i = 0; i < arr_len; i++)
         count[ (my_arr[i]/exp)%10 ]++;
      for (i = 1; i < 10; i++)
         count[i] += count[i - 1];
      for (i = arr_len - 1; i >= 0; i--) {
         result[count[ (my_arr[i]/exp)%10 ] - 1] = my_arr[i];
         count[ (my_arr[i]/exp)%10 ]--;
      }
      for (i = 0; i < arr_len; i++)
         my_arr[i] = result[i];
   }
   static void radix_sort(int my_arr[], int arr_len) {
      int m = get_max_val(my_arr, arr_len);
      for (int exp = 1; m/exp > 0; exp *= 10)
      countSort(my_arr, arr_len, exp);
   }
   public static void main (String[] args) {
      int my_arr[] = {56, 78, 102, 345, 67, 90, 102, 45, 78};
      int arr_len = my_arr.length;
      System.out.println("The array after performing radix sort is ");
      radix_sort(my_arr, arr_len);
      for (int i=0; i<arr_len; i++)
      System.out.print(my_arr[i]+" ");
   }
}
The array after performing radix sort is
45 56 67 78 78 90 102 102 345
In radix sort, every element is sorted based on its digit, wherein the least significant digit in every element is sorted first, and the most significant digit is sorted in the end. It uses counting sort as a sub-function to perform its sorting functions.
Given an array of elements, the first step is that the elements are sorted based on the least significant place’s digit, i.e ones place. Next the elements in the array are sorted based on tens place digits. Then, the elements are sorted based on hundreds place digit and so on. This is done with the help of ‘get_max_val’ function. In the main function, the array is defined, and the array is passed as a parameter to the ‘radix_sort’ function.
Can Enum implements an interface in Java?


Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version. The Enums are constants, by default they are static and final so the names of an enum type fields are in uppercase letters.
interface EnumInterface {
   int calculate(int first, int second);
}
enum EnumClassOperator implements EnumInterface { // An Enum implements an interface
   ADD {
      @Override
      public int calculate(int first, int second) {
         return first + second;
      }
   },
   SUBTRACT {
      @Override
      public int calculate(int first, int second) {
         return first - second;
      }
   };
}
class Operation {
   private int first, second;
   private EnumClassOperator operator;
   public Operation(int first, int second, EnumClassOperator operator) {
      this.first = first;
      this.second = second;
      this.operator = operator;
   }
   public int calculate() {
      return operator.calculate(first, second);
   }
}
// Main Class
public class EnumTest {
   public static void main (String [] args) {
      Operation add = new Operation(20, 10, EnumClassOperator.ADD);
      Operation subtract = new Operation(20, 10, EnumClassOperator.SUBTRACT);
      System.out.println("Addition: " + add.calculate());
      System.out.println("Subtraction: " + subtract.calculate());
   }
}
Addition: 30
Subtraction: 10
C# - Miscellaneous Operators

There are few other important operators including sizeof and ? :  supported by C#.
StringReader r = obj as StringReader;
using System;

namespace OperatorsAppl {

   class Program {
   
      static void Main(string[] args) {
         /* example of sizeof operator */
         Console.WriteLine("The size of int is {0}", sizeof(int));
         Console.WriteLine("The size of short is {0}", sizeof(short));
         Console.WriteLine("The size of double is {0}", sizeof(double));
         
         /* example of ternary operator */
         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("Value of b is {0}", b);
         Console.ReadLine();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
The size of int is 4
The size of short is 2
The size of double is 8
Value of b is 30
Value of b is 20


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Behave - Installation

Behave installation can be done by the following ways −
For Behave installation, we should have pip – the package installer for the Python language installed in our system. The pip is installed by default, if the Python version is greater than 2(upto 2.7.9).
To install pip, run the below mentioned command −
pip install pip

To install pip with Behave, run the command given below −
pip install behave

The following screen will appear on your computer −
We can update an existing version of Behave with the following command −
pip install –U behave

We can also use the easy_install for the Behave installation.
To install Setuptools, run the below mentioned command−
pip install setuptools

Now, for the Behave installation, run the command stated below:
easy_install behave

We can update an existing version of behave with the command given below:
easy_install –U behave

Post unpacking of the source distribution of Behave, type the new generated directory 'behave-<version>' and execute the below mentioned command −
python setup.py install

We should first have the pip installed in the system.
Later on, to install the latest version of Behave with Git repository, run the below mentioned command −
pip install git+https://github.com/behave/behave

If we use the PyCharm Editor for writing the Behave code, we should have the Professional version of PyCharm along with the Gherkin plugin installed with it.
 Print
 Add Notes
 Bookmark this page
fillpoly() function in C

Now the header file graphics.h contains fillpoly() function which is implemented to draw and fill a polygon such as triangle, rectangle, pentagon, hexagon etc. So this function require same arguments as drawpoly().
void fillpoly( int number, int *polypoints );
In this case,number indicates (n + 1) number of points where, n is the number of vertices in a polygon and polypoints points to a sequence of (n*2) integers.
Input 
arr[] = {320, 150, 400, 250, 250, 350, 320, 150};
Output 
Explanation 
So the declaration of fillpoly() contains two arguments: number specifies (n + 1) number of points where n is indicated as the number of vertices in a polygon.The second argument, such as, polypoints points to a sequence of (n * 2) integers. As a result of this,each pair of integers provides x and y coordinates of a point on the polygon. So we indicate (n + 1) points because first point coordinates should be equal to (n + 1)th for drawing a complete figure.
// C Implementation for fillpoly()
#include <graphics.h>
// driver code
intmain(){
   // Here gm1 is Graphics mode which is a computer display mode that
   // produces image using pixels. DETECT is a macro defined in
   // "graphics.h" header file
   intgd1 = DETECT, gm1;
   // Different coordinates for polygon
   intarr1[] = {320, 150, 400, 250, 250, 350, 320, 150};
   // Here initgraph initializes the
   // graphics system by loading a
   // graphics driver from disk
   initgraph(&gd1, &gm1, "");
   // fillpoly function
   fillpoly(4, arr1);
   getch();
   // Here closegraph function closes the
   // graphics mode and deallocates
   // all memory allocated by
   // graphics system .
   closegraph();
   return0;
}
Jupyter Notebook - IPyWidgets

IPyWidgets is a Python library of HTML interactive widgets for Jupyter notebook. Each UI element in the library can respond to events and invokes specified event handler functions. They enhance the interactive feature of Jupyter notebook application.
In order to incorporate widgets in the notebook, we have to import the following module as shown below −
from ipywidgets import widgets

Some basic IPyWidgets are explained here −
The widgets.text() function renders widgets in the notebook. It is similar to text box form element in HTML. The object of this widget has on_submit() method which listens to activity of the text field and can invoke event handler given as an argument to it.
This widget is similar to HTML button. When it is clicked, the event is registered by on_click() method which calls the click event handler.
A slider control which displays the incrementing integer values. There is also a FloatSlider and IntRangeSlider (changing integer between a range)
This widget is useful to display non editable text in the notebook.
This function from ipywidgets module renders the widget object in notebook’s input cell.
This function automatically renders a widget depending upon type of data argument given to it. First argument to this function is the event handler and second is a value passed to event handler itself.
Following example shows three label widgets, two text widgets and a button with ‘add’ caption. When the button is clicked, sum of numbers in two text input fields is displayed on the lowermost label.

    22 Lectures 
     49 mins

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Python 3 - Nested loops

Python programming language allows the usage of one loop inside another loop. The following section shows a few examples to illustrate the concept.
for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

The syntax for a nested while loop statement in Python programming language is as follows −
while expression:
   while expression:
      statement(s)
   statement(s)

A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example a for loop can be inside a while loop or vice versa.
The following program uses a nested-for loop to display multiplication tables from 1-10.
#!/usr/bin/python3

import sys
for i in range(1,11):
   for j in range(1,11):
      k = i*j
      print (k, end=' ')
   print()
The print() function inner loop has end=' ' which appends a space instead of default newline. Hence, the numbers will appear in one row.
Last print() will be executed at the end of inner for loop.
When the above code is executed, it produces the following result −
1 2 3 4 5 6 7 8 9 10 
2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 
6 12 18 24 30 36 42 48 54 60 
7 14 21 28 35 42 49 56 63 70 
8 16 24 32 40 48 56 64 72 80 
9 18 27 36 45 54 63 72 81 90 
10 20 30 40 50 60 70 80 90 100 


    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
Sass - Functions

SASS supports the use of functions by providing some keyword arguments, which are specified using normal CSS function syntax.
p {
   color: hsl($hue: 0, $saturation: 50%, $lightness: 50%);
}

HSL stands for hue, saturation, and lightness, which are more intuitive for creating a set of matching colors by using saturation and lightness.
hue − It represents the degree of color such as 120 for red, 240 for green, 290 for pastel violet etc.
hue − It represents the degree of color such as 120 for red, 240 for green, 290 for pastel violet etc.
saturation − It is a percentage value that increases the saturation of color.
saturation − It is a percentage value that increases the saturation of color.
lightness − It is a percentage value which decreases the lightness of color.
lightness − It is a percentage value which decreases the lightness of color.
The following example demonstrates the use of functions in the SCSS file −
<html>
   <head>
      <title>Functions Example</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css" />
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
   </head>

   <body>
      <div class = "container">
         <h2>Example using Functions</h2>
         <p>SASS stands for Syntactically Awesome Stylesheet..</p>
      </div>
   </body>
</html>
Next, create file style.scss.
Use the following SCSS code which defines the HSL function on the SASS code.
p {
   color: hsl(290,60%,70%);
}
You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −
sass --watch C:\ruby\lib\sass\style.scss:style.css

Next, execute the above command; it will create the style.css file automatically with the following code −
p {
   color: #d185e0;
}
Let us carry out the following steps to see how the above given code works −
Save the above given html code in functions.html file.
Save the above given html code in functions.html file.
Open this HTML file in a browser, an output is displayed as shown below.
Open this HTML file in a browser, an output is displayed as shown below.

    50 Lectures 
     5.5 hours 

 Code And Create

    124 Lectures 
     30 hours 

 Juan Galvan

    162 Lectures 
     31.5 hours 

 Yossef Ayman Zedan

    167 Lectures 
     45.5 hours 

 Muslim Helalee
 Print
 Add Notes
 Bookmark this page
Recursive fibonacci method in Java

The fibonacci series is a series in which each number is the sum of the previous two numbers. The number at a particular position in the fibonacci series can be obtained using a recursive method.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   public static long fib(long n) {
      if ((n == 0) || (n == 1))
         return n;
      else
         return fib(n - 1) + fib(n - 2);
   }
   public static void main(String[] args) {
      System.out.println("The 0th fibonacci number is: " + fib(0));
      System.out.println("The 7th fibonacci number is: " + fib(7));
      System.out.println("The 12th fibonacci number is: " + fib(12));
   }
}
The 0th fibonacci number is: 0
The 7th fibonacci number is: 13
The 12th fibonacci number is: 144
Now let us understand the above program.
The method fib() calculates the fibonacci number at position n. If n is equal to 0 or 1, it returns n. Otherwise it recursively calls itself and returns fib(n - 1) + fib(n - 2). A code snippet which demonstrates this is as follows:
public static long fib(long n) {
   if ((n == 0) || (n == 1))
      return n;
   else
      return fib(n - 1) + fib(n - 2);
}
In main(), the method fib() is called with different values. A code snippet which demonstrates this is as follows:
public static void main(String[] args) {
   System.out.println("The 0th fibonacci number is: " + fib(0));
   System.out.println("The 7th fibonacci number is: " + fib(7));
   System.out.println("The 12th fibonacci number is: " + fib(12));
}
How to convert from string to date data type in MongoDB?

To convert from String to date data type, you need to write some script. Let us first create a
collection with documents
>db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Carol","ShippingDate":"2019-
01-21"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2071d66324ffac2a7dc60")
}
>db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Bob","ShippingDate":"2019-
02-24"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2073566324ffac2a7dc61")
}
>db.stringToDateDataTypeDemo.insertOne({"CustomerName":"Chris","ShippingDate":"2019-
04-01"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca2074266324ffac2a7dc62")
}
Following is the query to display all documents from a collection with the help of find() method
> db.stringToDateDataTypeDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca2071d66324ffac2a7dc60"),
   "CustomerName" : "Carol",
   "ShippingDate" : "2019-01-21"
}
{
   "_id" : ObjectId("5ca2073566324ffac2a7dc61"),
   "CustomerName" : "Bob",
   "ShippingDate" : "2019-02-24"
}
{
   "_id" : ObjectId("5ca2074266324ffac2a7dc62"),
   "CustomerName" : "Chris",
   "ShippingDate" : "2019-04-01"
}
Following is the query to convert String to date data type
> db.stringToDateDataTypeDemo.find().forEach(function(data){
...    data.ShippingDate= ISODate(data.ShippingDate);
...    db.stringToDateDataTypeDemo.save(data);
... });
Let us display all documents once again to check the string is converted to date data type or
not. Following is the query
> db.stringToDateDataTypeDemo.find().pretty();
This will produce the following output
{
   "_id" : ObjectId("5ca2071d66324ffac2a7dc60"),
   "CustomerName" : "Carol",
   "ShippingDate" : ISODate("2019-01-21T00:00:00Z")
}
{
   "_id" : ObjectId("5ca2073566324ffac2a7dc61"),
   "CustomerName" : "Bob",
   "ShippingDate" : ISODate("2019-02-24T00:00:00Z")
}
{
   "_id" : ObjectId("5ca2074266324ffac2a7dc62"),
   "CustomerName" : "Chris",
   "ShippingDate" : ISODate("2019-04-01T00:00:00Z")
}
C# How To Add Two Numbers

Learn how to add two numbers in C#:
int x = 5;
int y = 6;
int sum = x + y;
Console.WriteLine(sum); // Print the sum of x + y


Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Eroding an image using the OpenCV function erode()

In this program, we will erode an image using the OpenCV function erode(). Erosion of image means to shrink the image. If any of the pixels in a kernel is 0, then all the pixels in the kernel are set to 0. One condition before applying an erosion function on image is that the image should be a grayscale image.
Step 1: Import cv2
Step 2: Import numpy.
Step 3: Read the image using imread().
Step 4: Define the kernel size using numpy ones.
Step 5: Pass the image and kernel to the erode function.
Step 6: Display the output.
import cv2
import numpy as np
image = cv2.imread('testimage.jpg')
kernel = np.ones((7,7), np.uint8)
image = cv2.erode(image, kernel)
cv2.imshow('Eroded Image', image)
How to select first and last data row from a MySQL result?

You can select the first and last data row using MIN() and MAX(). The syntax is as follows −
SELECT *
FROM yourTableName
WHERE yourColumnName = (SELECT MIN(yourColumnName) FROM yourTableName)
UNION
SELECT *
FROM yourTableName
WHERE yourColumnName = (SELECT MAX(yourColumnName) FROM yourTableName) ;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table FirstAndLastDataDemo
   -> (
   -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> EmployeeName varchar(20),
   -> EmployeeAge int
   -> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23);
Query OK, 1 row affected (0.15 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13);
Query OK, 1 row affected (0.11 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24);
Query OK, 1 row affected (0.14 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14);
Query OK, 1 row affected (0.18 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31);
Query OK, 1 row affected (0.10 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('James',18);
Query OK, 1 row affected (0.16 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge)
values('Maxwell',28);
Query OK, 1 row affected (0.17 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27);
Query OK, 1 row affected (0.12 sec)
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement −
mysql> select *from FirstAndLastDataDemo;
+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|          1 | John         |          23 |
|          2 | Bob          |          13 |
|          3 | Larry        |          24 |
|          4 | Sam          |          14 |
|          5 | Mike         |          31 |
|          6 | James        |          18 |
|          7 | Maxwell      |          28 |
|          8 | David        |          27 |
|          9 | Chris        |          22 |
+------------+--------------+-------------+
9 rows in set (0.00 sec)
Here is the query to get first row data and last row data −
mysql> SELECT *
-> FROM FirstAndLastDataDemo
-> WHERE EmployeeId = (SELECT MIN(EmployeeId) FROM FirstAndLastDataDemo)
-> UNION
-> SELECT *
-> FROM FirstAndLastDataDemo
-> WHERE EmployeeId = (SELECT MAX(EmployeeId) FROM FirstAndLastDataDemo);
+------------+--------------+-------------+
| EmployeeId | EmployeeName | EmployeeAge |
+------------+--------------+-------------+
|          1 |         John |          23 |
|          9 |        Chris |          22 |
+------------+--------------+-------------+
2 rows in set (0.00 sec)
How to find the first 10 characters of a string in C#?

To get the first 10 characters, use the substring() method.
Let’s say the following is our string −
string str = "Cricket is a religion in India!";
Now to get the first 10 characters, set the value 10 in the substring() method as shown below −
string res = str.Substring(0, 10);
Let us see the complete code.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      string str = "Cricket is a religion in India!";
      string res = str.Substring(0, 10);
      Console.WriteLine(res);
   }
}
Cricket is
How to customize spines of Matplotlib figures?

When we plot a figure in Matplotlib, it creates four spines around the figure, top, left, bottom and right. Spines are nothing but a box surrounded with the pictorial representation of the grid which displays some ticks and tickable axes on left(y) and bottom(x).
Let us see how to customize the spines in a given figure. We will create six figures to see and customize the spines for it.
First import the required libraries for the workbook.
import numpy as np
import matplotlib.pyplot as plt
Let us draw graph for sines,
theta = np.linspace(0, 2*np.pi, 128)
y = np.sin(theta)
fig = plt.figure(figsize=(8,6))
Define the axes with default spines,
ax1 = fig.add_subplot(2, 3, 1)
ax1.plot(theta, np.sin(theta), 'b-*')
ax1.set_title('default spines')
Define the function to plot the graph,
def plot_graph(axs, title, lposition, bposition):
   ax = fig.add_subplot(axs)
   ax.plot(theta, y, 'b-*')
   ax.set_title(title)
   ax.spines['left'].set_position(lposition)
   ax.spines['right'].set_visible(False)
   ax.spines['bottom'].set_position(bposition)
   ax.spines['top'].set_visible(False)
   ax.xaxis.set_ticks_position('bottom')
   ax.yaxis.set_ticks_position('left')
Let us plot 3 graphs.
plot_graph(232, 'centered spines', 'center', 'center')
plot_graph(233, 'zeroed spines', 'zero', 'zero')
plot_graph(234, 'spines at axes [0.25, 0.75]', ('axes', 0.25),('axes', 0.75))
plot_graph(235, 'spines at data [1.0, -1.0]', ('data', 1.0),('data', -1.0))
plot_graph(236, 'adjusted spines', ('outward', 10), ('outward', 10))
Let us fit the plot in the grid and show.
plt.tight_layout()
plt.show()
How to update the _id of a MongoDB Document?

You cannot update it but you can save a new id and remove the old id. Follow some steps in order to update the _id of a MongoDB. The steps are as follows:
Step1: In the first step, you need to store ObjectId into a variable.
anyVariableName=db.yourCollectionName.findOne({_id:yourObjectIdValue)});
Step 2: In the second step, you need to set a new id.
yourDeclaredVariableName._id=yourNewObjectIdValue;
Step 3: In the third step, you need to insert new id on a document.
db.yourCollectionName.insert(yourDeclaredVariableName);
Step 4: In the fourth step, you need to remove the old id.
db.yourCollectionName.remove({_id:yourOldObjectIdValue)});
To understand the above steps, let us create a collection with document. The query to create a collection with document is as follows:
> db.updateIdDemo.insertOne({"StudentName":"Robert"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebfec6fd07954a4890683")
}
> db.updateIdDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebff66fd07954a4890684")
}
> db.updateIdDemo.insertOne({"StudentName":"Maxwell"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebfff6fd07954a4890685")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.updateIdDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6ebfec6fd07954a4890683"), "StudentName" : "Robert" }
{ "_id" : ObjectId("5c6ebff66fd07954a4890684"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c6ebfff6fd07954a4890685"), "StudentName" : "Maxwell" }
The following is the query to update the _id of a MongoDB document:
Step1:
> myId=db.updateIdDemo.findOne({_id:ObjectId("5c6ebfec6fd07954a4890683")});
{ "_id" : ObjectId("5c6ebfec6fd07954a4890683"), "StudentName" : "Robert" }

Step 2:
> myId._id=ObjectId("5c6ebfec6fd07954a4890689");
ObjectId("5c6ebfec6fd07954a4890689")

Step 3:
> db.updateIdDemo.insert(myId);
WriteResult({ "nInserted" : 1 })

Step 4:
> db.updateIdDemo.remove({_id:ObjectId("5c6ebfec6fd07954a4890683")});
WriteResult({ "nRemoved" : 1 })
Let us check the _id has been updated or not. Display all documents from a collection with the help of find() method:
> db.updateIdDemo.find().pretty();
The following is the output:
{ "_id" : ObjectId("5c6ebff66fd07954a4890684"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5c6ebfff6fd07954a4890685"), "StudentName" : "Maxwell" }
{ "_id" : ObjectId("5c6ebfec6fd07954a4890689"), "StudentName" : "Robert" }
Look at the sample output, the _id of “StudentName”:”Robert” has been changed.
Matplotlib.axes.Axes.set_title() in Python - GeeksforGeeks

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.set_title() function in axes module of matplotlib library is used to set a title for the axes.
Syntax: Axes.set_title(self, label, fontdict=None, loc=’center’, pad=None, **kwargs)
Parameters: This method accepts the following parameters.
label : This parameter is the Text to use for the title.
fontdict : This parameter is the dictionary controlling the appearance of the title text.
loc : This parameter is used to set the location of the title {‘center’, ‘left’, ‘right’}.
pad : This parameter is the offset of the title from the top of the axes, in points.
Returns:This method returns the matplotlib text instance representing the title.
Below examples illustrate the matplotlib.axes.Axes.set_title() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport osfrom matplotlib import font_manager as fm, rcParamsimport matplotlib.pyplot as plt  fig, ax = plt.subplots()  fpath = os.path.join(rcParams["datapath"],                      "fonts/ttf/cmr10.ttf")  prop = fm.FontProperties(fname = fpath)fname = os.path.split(fpath)[1]ax.set_title('Title with special font: {}'.format(fname),             fontproperties = prop,              fontsize = 14)  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  x = np.arange(0.1, 5, 0.1)y = np.exp(-x)  yerr = 0.1 + 0.1 * np.sqrt(x)  fig, axs = plt.subplots(nrows = 1,                        ncols = 2,                         sharex = True)ax = axs[0]ax.errorbar(x, y, yerr = yerr,             color ="green")ax.set_title('Title of Axes 1',              fontweight ="bold")  ax = axs[1]ax.errorbar(x, y, yerr = yerr,            errorevery = 5,             color ="green")  ax.set_title('Title of Axes 2',             fontweight ="bold")      fig.suptitle('matplotlib.axes.Axes.set_title() \function Example\n')  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
MomentJS - Week of year

This method will get/set the week of the year. The output will depend on the locale being used, as first day of week differs from country to country.
moment().week(Number);
moment().week();
moment().weeks(Number);
moment().weeks();

var m = moment().week();
var d = moment().week(50);
var a = moment().week(90);
 Print
 Add Notes
 Bookmark this page
How to remove html tags from a string in JavaScript?

We can remove HTML/XML tags in a string using regular expressions in javascript. HTML elements such as span, div etc. are present between left and right arrows for instance <div>,<span> etc. So replacing the content within the arrows, along with the arrows, with nothing('') can make our task easy.
str.replace( /(<([^>]+)>)/ig, '');
Live Demo
<html>
<body>
<script>
   function removeTags(str) {
      if ((str===null) || (str===''))
      return false;
      else
      str = str.toString();
      return str.replace( /(<([^>]+)>)/ig, '');
   }
   document.write(removeTags('<html> <body> Javascript<body> is not Java'));;
</script>
</body>
</html>
Javascript is not Java
Live Demo
<html>
<body>
<script>
   function removeTags(str) {
      if ((str===null) || (str===''))
      return false;
      else
      str = str.toString();
      return str.replace( /(<([^>]+)>)/ig, '');
   }
   document.write(removeTags('<html> Tutorix is <script> the best <body> e-learning platform'));;
</script>
</body>
</html>
Tutorix is the best e-learning platform