code-rag-bench/online-tutorials huggingface dataset:
How to invert the elements of a boolean array in Python? - GeeksforGeeks

17 Dec, 2020
Given a boolean array the task here is to invert its elements. A boolean array is an array which contains only boolean values like True or False, 1 or 0. 
Input : A=[true , true , false]
Output: A= [false , false , true]
Input: A=[0,1,0,1] 
Output: A=[1,0,1,0]
Method 1:
You can use simple if else method to invert the array. In the implementation shown below method you just need to check the value of each index in array if the value is true change it to false else change it to true. This is one of the simplest method you can use to invert elements of a boolean array.
Program:
Python3
a1 = ((0, 1, 0, 1))a = list(a1)  for x in range(len(a)):    if(a[x]):        a[x] = 0    else:        a[x] = 1  print(a)
Output:
[1, 0, 1, 0]
Method 2:
You can also use an inbuilt function of numpy library to invert the whole array.
Syntax:
np.invert(boolean[] a)
Program:
Python
import numpy as np    a = np.array((True, True, False, True, False))b = np.invert(a)print(b)
Output:
[False False  True False  True]
Method 3:
We can also use the Tilde operator (~) also known as bitwise negation operator in computing to invert the given array. It takes the number n as binary number and “flips” all  0 bits to 1 and 1 to 0 to obtain the complement binary number. 
So in the boolean array for True or 1 it will result in -2 and for False or 0 it will result as  -1. And again by using if..else we can convert the array into or required answer.
Program:
Python3
a1 = ((0, 1, 0, 1))a = list(a1)  for x in range(len(a)):    # using Tilde operator(~)    a[x] = ~a[x]  print(a)
Output:
[-1, -2, -1, -2]
Picked
Python-datatype
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
AngularJS | angular.forEach() Function - GeeksforGeeks

22 Apr, 2019
The angular.forEach() Function in AngularJS is used to iterate through each item in an array or object. It works similar to the for loop and this loop contains all properties of an object in key-value pairs of an object.
Syntax:
angular.forEach(object, iterator, [context])
Parameter Values:
object: It refers to the object to be iterated.
iterator: It refers to the iterator function(value, key, obj).
context: This is optional. It refers to the object which becomes context for iterator function.
Example:
<html>    <head>        <script src=        "//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">        </script>        <title>angular.forEach()</title>    </head>      <body ng-app="app" ng-cloak style="padding:30px">    <h1 style="color:green">GeeksforGeeks</h1>    <h2>angular.forEach()</h2>    <p>Searching techniques:</p>    <div ng-controller="geek">        <div ng-repeat="name in names">            <ul><li>{{name}}</li></ul>        </div>    </div>    <script>        var app = angular.module("app", []);        app.controller('geek', ['$scope', function ($scope) {            $scope.names = [];            var values = [            {name: 'Binary Search'},            {name: 'Linear Search'},            {name: 'Interpolation Search'}            ];              angular.forEach(values, function (value, key) {                $scope.names.push(value.name);            });          }]);          </script></body></html>
Output:
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
Node.js fs.readFileSync() Method
How to get selected option from Dropdown in jQuery ? - GeeksforGeeks

19 Sep, 2021
In this article, we learn how to get the selected option from the dropdown list. This article requires some familiarity with HTML, CSS, JavaScript, and jQuery. We can solve this challenge by using the jQuery val() method.
The val() method in jQuery is used to set or return the value of an attribute for the selected elements. This method applies to the HTML form elements.
Syntax:
$(selector).val()   // or
$(selector).val(value)  // or
$(selector).val(function(index, current_value))
This method returns the selected element with specified changes made by val() method.
 
Example:
HTML
<html>  <head>    <title>        How to get selected option from         Dropdown list using jQuery?    </title>      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"         rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"        crossorigin="anonymous">      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js">    </script></head>  <body style="border: 2px solid green; min-height: 240px;">    <div style="display: flex; justify-content: center;">        <h1 style="color:green;">            GeeksforGeeks        </h1>    </div>      <select class="form-select mx-auto"         aria-label="Default select example"         style="width: 200px; margin-top: 20px;"        id="lang">                  <option selected>Select Language</option>        <option>C</option>        <option>Java</option>        <option>Python</option>    </select>      <div id="show" style="display: flex;        justify-content: center; margin-top: 20px;">    </div></body>  <script>    $('#lang').on('input', function () {        $('#show').text($('#lang').val());    })</script>  </html>
Output:
output
How does it work?
Whenever you select an item from the dropdown, it will show below the dropdown at the same time.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
Blogathon-2021
HTML-Questions
jQuery-Methods
jQuery-Questions
Picked
Blogathon
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
How to Install Tkinter in Windows?
Python program to convert XML to Dictionary
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Program to sort given set of Cartesian points based on polar angles in Python

Suppose we have a set of Cartesian points in a list called points. We have to sort them based on their polar angles. The polar angles vary in range 0 and 2*PI. If some points have same polar angles, then arrange them based on the distance of that point from the origin.
So, if the input is like points = [(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(-3,4)],
then the output will be [(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2)]
To solve this, we will follow these steps −
Define a comparator function key() . This will take x
atan := tan-inverse of x[1]/x[0]
return pair (atan, x[1]^2+x[0]^2) if atan >= 0 otherwise (2*pi + atan, x[0]^2+x[1]^2)
then sort points using comparator function key()
Let us see the following implementation to get better understanding −
import math
def solve(points):
   def key(x):
      atan = math.atan2(x[1], x[0])
      return (atan, x[1]**2+x[0]**2) if atan >= 0 else (2*math.pi + atan, x[0]**2+x[1]**2)

   return sorted(points, key=key)

points = [(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(-3,4)]
print(solve(points))
[(1,1), (1,-2),(-2,2),(5,4),(4,5),(2,3),(-3,4)]

[(5, 4), (1, 1), (4, 5), (2, 3), (-3, 4), (-2, 2), (1, -2)]
Bootstrap - Page Header

The page header is a nice little feature to add appropriate spacing around the headings on a page. This is particularly helpful on a web page where you may have several post titles and need a way to add distinction to each of them. To use a page header, wrap your heading in a <div> with a class of .page-header −
<div class = "page-header">
   <h1>
      Example page header 
      <small>Subtext for header</small>
   </h1>
</div>

<p>This is a sample text.This is a sample text.This is a sample text. This is a sample text.</p>
This is a sample text.This is a sample text.This is a sample text.
         This is a sample text.

    26 Lectures 
     2 hours 

 Anadi Sharma

    54 Lectures 
     4.5 hours 

 Frahaan Hussain

    161 Lectures 
     14.5 hours 

 Eduonix Learning Solutions

    20 Lectures 
     4 hours 

 Azaz Patel

    15 Lectures 
     1.5 hours 

 Muhammad Ismail

    62 Lectures 
     8 hours 

 Yossef Ayman Zedan
 Print
 Add Notes
 Bookmark this page
Getting every child widget of a Tkinter window

In order to get the information about the widgets, tkinter provides a set of methods that can be used to test the widgets in an application. In order to get the list of all the child widgets, we can use the winfo_children() method.
In this example, we have defined some widgets in a frame and by using the winfo_children() method, we will print the list containing the names of all the widgets.
#Import tkinter library
from tkinter import *
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("750x200")
#Create a frame
frame= Frame(win)
#Create label, button widgets
Label(frame, text= "Top Level Text", font= ('Helvetica 20 bold')).pack(pady=20)
Button(frame, text= "Left").pack(side=LEFT)
Button(frame, text= "Right").pack(side= RIGHT)
Button(frame, text= "Center").pack(side= BOTTOM)
frame.pack()
#Print the List of all Child widget Information
print(frame.winfo_children())
win.mainloop()
Executing the above code will display a window with a label and three buttons,
On the console, it will print the list of all the widgets defined in frame widget.
[<tkinter.Label object .!frame.!label>, <tkinter.Button object .!frame.!button>, <tkinter.Button object .!frame.!button2>, <tkinter.Button object .!frame.!button3>]
Statistics - Trimmed Mean

Trimmed Mean a method of averaging that removes a small percentage of the largest and smallest values before calculating the mean.
The Trimmed Mean can be calculated using the following formula.
Where − 
∑Xi = Sum of your Trimmed Set.
∑Xi = Sum of your Trimmed Set.
n = Total Numbers in Trimmed set.
n = Total Numbers in Trimmed set.
μ = Trimmed Mean.
μ = Trimmed Mean.
Problem Statement:
Figure out the 20% trimmed mean for the number set {8, 3, 7, 1, 3, and 9} 
Give us a chance to first ascertain the estimation of Trimmed check (g), where g alludes to number of qualities to be trimmed from the given arrangement.
g = Floor (Trimmed Mean Percent x Sample Size) g = Floor (0.2 x 6) g  = Floor (1.2) 
Trimmed check (g) = 1 

Record the given arrangement of numbers {8, 3, 7, 1, 3, 9} in rising request, = 1, 3, 3,7,8,9
As the trimmed tally is 1, we ought to expel one number from the earliest starting point and end. Along these lines, we uproot first number (1) and last number (9) from the above arrangement of numbers, = 3, 3, 7, 8.Now Trimmed mean can be computed as:
The Trimmed Mean of the given numbers is 5.25.

    40 Lectures 
     3.5 hours 

 Madhu Bhatia

    40 Lectures 
     2 hours 

 Megha Aggarwal

    66 Lectures 
     1.5 hours 

 Mike West

    22 Lectures 
     1 hours 

 Mike West

    60 Lectures 
     12 hours 

 Michael Miller

    65 Lectures 
     5 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Matplotlib.axes.Axes.can_zoom() 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.can_zoom() Function in axes module of matplotlib library is used to check whether the axes supports any zoom box button functionality or not.
Syntax: Axes.can_zoom(self)
Parameters: This method does not accept any parameters.
Return value: This method returns boolean value True if supports any zoom box button functionality.
Below examples illustrate the matplotlib.axes.Axes.can_zoom() function in matplotlib.axes:Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np       fig, ax = plt.subplots()ax.plot([1, 2, 3])  w = ax.can_zoom()  ax.text(0.45, 2.75, "Value return by function:",        fontweight ="bold")ax.text(0.9, 2.6, w, fontweight ="bold")  fig.suptitle('matplotlib.axes.Axes.can_zoom() function \Example\n\n', fontweight ="bold")  plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slider, Button, RadioButtons     fig, ax1 = plt.subplots()plt.subplots_adjust(bottom = 0.25)t = np.arange(0.0, 1.0, 0.001)a0 = 5f0 = 3delta_f = 5.0s = a0 * np.sin(2 * np.pi * f0 * t)     ax1.plot(t, s, lw = 2, color = 'green')ax1.set_ymargin(0.5)  w = ax1.can_zoom()  ax1.text(0.25, 7.5, "Value return by function:",         fontweight ="bold")ax1.text(0.47, 5.6, w, fontweight ="bold")  fig.suptitle('matplotlib.axes.Axes.can_zoom() function \Example\n\n', fontweight ="bold")  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
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
fmt.Sprintf() Function in Golang With Examples

05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprintf() function in Go language formats according to a format specifier and returns the resulting string. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Sprintf(format string, a ...interface{}) string

Parameters: This function accepts two parameters which are illustrated below:
format string: This includes some varbs along with some strings.
a ...interface{}: This is the specified constant variables.
Returns: It returns the resulting string.
Example 1:
// Golang program to illustrate the usage of// fmt.Sprintf() function  // Including the main packagepackage main  // Importing fmt, io and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Declaring some const variables    const name, dept = "GeeksforGeeks", "CS"      // Calling Sprintf() function    s := fmt.Sprintf("%s is a %s Portal.\n", name, dept)      // Calling WriteString() function to write the    // contents of the string "s" to "os.Stdout"    io.WriteString(os.Stdout, s)  }
Output:
GeeksforGeeks is a CS Portal.

Example 2:
// Golang program to illustrate the usage of// fmt.Sprintf() function  // Including the main packagepackage main  // Importing fmt, io and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Declaring some const variables    const num1, num2, num3 = 5, 10, 15      // Calling Sprintf() function    s := fmt.Sprintf("%d + %d = %d", num1, num2, num3)      // Calling WriteString() function to write the    // contents of the string "s" to "os.Stdout"    io.WriteString(os.Stdout, s)  }
Output:
5 + 10 = 15

Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | sympy.limit() method

11 Aug, 2021
With the help of sympy.limit() method, we can find the limit of any mathematical expression, e.g., 
(1)   
 
Syntax: limit(expression, variable, value)Parameters: expression – The mathematical expression on which limit operation is to be performed, i. e., f(x). variable – It is the variable in the mathematical expression, i. e., x value – It is the value to which the limit tends to, i. e., a.Returns: Returns the limit of the mathematical expression under given conditions.  
Example #1:
Python3
# import sympyfrom sympy import * x = symbols('x')expr = sin(x)/x;   print("Expression : {}".format(expr))     # Use sympy.limit() methodlimit_expr = limit(expr, x, 0)      print("Limit of the expression tends to 0 : {}".format(limit_expr)) 
Output:  
Expression : sin(x)/x
Limit of the expression tends to 0 : 1
Example #2:
Python3
# import sympyfrom sympy import * x = symbols('x')expr = sin(3 * x)/x;   print("Expression : {}".format(expr))     # Use sympy.limit() methodlimit_expr = limit(expr, x, 0)      print("Limit of the expression tends to 0 : {}".format(limit_expr)) 
Output: 
Expression : sin(3*x)/x
Limit of the expression tends to 0 : 3
varshagumber28
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Lodash - sortBy method

_.sortBy(collection, [iteratees=[_.identity]])

Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).
collection (Array|Object) − The collection to iterate over.
collection (Array|Object) − The collection to iterate over.
[iteratees=[_.identity]] (...(Function|Function[])) − The iteratees to sort by.
[iteratees=[_.identity]] (...(Function|Function[])) − The iteratees to sort by.
(Array) − Returns the new sorted array.
(Array) − Returns the new sorted array.
var _ = require('lodash');
var users = [
   { user: 'Joe', age: 48, active: false },
   { user: 'Robert', age: 34, active: true },
   { user: 'Julie', age: 40, active: false },
   { user: 'Stafey', age: 36, active: true }
];
var result = _.sortBy(users, [function(item) { return item.user; }]);
console.log(result);

var result = _.sortBy(users, ['user', 'age']);
console.log(result);
Save the above program in tester.js. Run the following command to execute this program.
\>node tester.js

[
   { user: 'Joe', age: 48, active: false },
   { user: 'Julie', age: 40, active: false },
   { user: 'Robert', age: 34, active: true },
   { user: 'Stafey', age: 36, active: true }
]
[
   { user: 'Joe', age: 48, active: false },
   { user: 'Julie', age: 40, active: false },
   { user: 'Robert', age: 34, active: true },
   { user: 'Stafey', age: 36, active: true }
Python | Pandas tseries.offsets.BusinessDay

23 Apr, 2019
Dateoffsets are a standard kind of date increment used for a date range in Pandas. It works exactly like relativedelta in terms of the keyword args we pass in. DateOffets work as follows, each offset specify a set of dates that conform to the DateOffset. For example, Bday defines this set to be the set of dates that are weekdays (M-F).
DateOffsets can be created to move dates forward a given number of valid dates. For example, Bday(2) can be added to a date to move it two business days forward. If the date does not start on a valid date, first it is moved to a valid date and then offset is created.
Pandas tseries.offsets.BusinessDay() function to create a Business day offset.
Syntax: pandas.tseries.offsets.BusinessDay()
Parameter :n : The number of time periods the offset represents.normalize : Whether to round the result of a DateOffset addition down to the previous midnight.offset : datetime.timedelta(0)
Returns : Business day offset
Example #1: Use pandas.tseries.offsets.BusinessDay() function to create an offset of 5 Business days.
# importing pandas as pdimport pandas as pd  # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11')  # Create an offset of 5 Business daysbd = pd.tseries.offsets.BusinessDay(n = 5)  # Print the Timestampprint(ts)  # Print the DateOffsetprint(bd)
Output :
Now we will add the Business day offset to the given timestamp object to increment the datetime value.
# Adding the Business day offset to the given timestampnew_timestamp = ts + bd  # Print the updated timestampprint(new_timestamp)
Output :
As we can see in the output, we have successfully created an offset of 5 Business days and added it to the given timestamp.
Example #2 : Use pandas.tseries.offsets.BusinessDay() function to create an offset of 10 Business days and 10 hours.
# importing pandas as pdimport pandas as pd  # Creating Timestampts = pd.Timestamp('2019-10-10 07:15:11')  # Create an offset of 10 Business days and 10 hoursbd = pd.tseries.offsets.BusinessDay(offset = datetime.timedelta(days = 10, hours = 10))  # Print the Timestampprint(ts)  # Print the DateOffsetprint(bd)
Output :
Now we will add the Business day offset to the given timestamp object to increment the datetime value.
# Adding the Business day offset to the given timestampnew_timestamp = ts + bd  # Print the updated timestampprint(new_timestamp)
Output :
As we can see in the output, we have successfully created an offset of 10 Business days & 10 hours and added it to the given timestamp.
Python pandas-datetime
Python-pandas
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
Enumerate() in Python
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
Iterate over a list in Python
Python OOPs Concepts
TypeScript | toFixed() Function

16 Jun, 2020
The toFixed() function in TypeScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal.
Syntax: 
number.toFixed( [digits] );

Parameters: This function accepts a parameter value- digits– The number of digits to appear after the decimal point.
Return Value: The toFixed() method in TypeScript returns a string representation of number that does not use exponential notation and has the exact number of digits after the decimal place.
Below examples illustrates the working of toFixed() function in TypeScript :Example 1:
Javascript
var num = 358.429 console.log("num.toFixed() is "+num.toFixed()) console.log("num.toFixed(2) is "+num.toFixed(2))
Output: 
num.toFixed() is 358 
num.toFixed(2) is 358.42

Example 2: 
Javascript
var num1 = 526.123 console.log("num1.toFixed() is "+num1.toFixed()) console.log("num1.toFixed(4) is "+num1.toFixed(4)) console.log("num1.toFixed(7) is "+num1.toFixed(7))
Output: 
num1.toFixed() is 526 
num1.toFixed(4) is 526.1230
num1.toFixed(7) is 526.1230000

TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Difference between Java and Kotlin in Android with Examples

27 May, 2020
KOTLIN is a cross platform, statically types, general purpose programming language with type inference. KOTLIN is designed to interoperate fully with java but type inference allows its syntax to be more concise.KOTLIN is sponsored by JetBrains and Google through the Kotlin Foundation.
JAVA is an Object Oriented Programming Language developed by JAMES GOSLING and colleagues at SUN MICRO SYSTEMS in 1991.The language was initially called OAK. It was developed as a full fledged programming language in which one can accomplish the same sorts of tasks and solve the similar problems that one can do in other programming languages such as BASIC,C++ etc.
Using Kotlin over Java language in Android
The most reason for introducing Kotlin to Android advancement was to decrease the number of lines of code and make development more convenient to prepare. Everything that can be done utilizing Java can be done utilizing Kotlin for Android development.
For example:
No need of findViewByIds: It is used to find the first descendant view with the given ID.JavaTextView text = (TextView) findViewById(R.id.textView);text.setText("Hello World");KotlintextView.setText("Hello World")
TextView text = (TextView) findViewById(R.id.textView);text.setText("Hello World");KotlintextView.setText("Hello World")
Free from Null Pointer ExceptionNullPointerExceptions are a tremendous source of disappointment for Java designers. In Kotlin, all sorts are non-nullable (incapable to hold null value) by default. If the code tries to use or return null in Kotlin, compile time error is shown.var a: String = "abc"// compilation errora = null
Data Class: We often create classes to hold some data in it. In such classes, some standard functions are often derivable from the data. In Kotlin, this type of class is known as data class and is marked as data.data class User(val name: String, val age: Int)
data class User(val name: String, val age: Int)
There are many differences in both these languages according to their features
Despite all the differences between the two languages, Java and Kotlin are 100% interoperable. You can call Kotlin code from Java, and you can call Java code from Kotlin. So it’s possible to have Kotlin and Java classes side-by-side within the same project, and everything will still compile.
harleenk_99
android
Kotlin Android
Difference Between
Java
Kotlin
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Stack vs Heap Memory Allocation
Difference between Clustered and Non-clustered index
Arrays in Java
Arrays.sort() in Java with examples
Split() String method in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
GATE | GATE-CS-2016 (Set 2) | Question 29

01 Sep, 2021
Match the following:
(P) Lexical analysis       (i) Leftmost derivation
(Q) Top down parsing       (ii) Type checking
(R) Semantic analysis      (iii) Regular expressions
(S) Runtime environments   (iv) Activation records
(A) A(B) B(C) C(D) DAnswer: (B)Explanation: Lexical analysis uses Regular expression to recognize identifiers.
Top down parsing uses Left Most Derivation to generate the string the of the language.
Type checking is done at Semantic analysis phase of the compiler.
Activation records of a function are loaded into stack memory at Run time.
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xcubPntmL3Y" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 2)
GATE-GATE-CS-2016 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to run ExpressJS server from browser ?

31 Mar, 2021
Express is the node module which is used to create a server, to take get request on our server. We can run the ExpressJS server from the browser using the following 5 simple steps:
Step 1: Install the Express locally into your system by the following command:
npm install express
Step 2: Check the version of the express server by using the below command in the terminal:
npm ls express
Step 3: Create a file with the name index.js in any project directory.
Step 4: Write down the following code in the index.js file.
index.js
// Requiring express.jsconst express = require('express')  // Changing the module to object to use its inbuilt functionsconst app = express()  // Port number to run the portconst port_no = 5555  // Get request to send the data to the serverapp.get('/' , (req,res) => {    res.send('hey geeks!')})  // Server Setupapp.listen(port_no, () => {    console.log('port running atport number : 5555')})
Step 5: Run the application using the following steps.
Run the index.js file using the following command:
node index.js
Output: You will see the following output on console screen.
Now go to your browser and go to http://localhost:5555/  to open the server:
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Windows
JWT Authentication with Node.js
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
Mongoose find() Function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Lex Program to accept string starting with vowel - GeeksforGeeks

30 Apr, 2019
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the lex program are:
lex abc.l (abc is the file name)
cc lex.yy.c -efl
./a.out 
Let’s see lex program to accept string starting with vowel.Examples:
Input: animal
Output: Accepted

Input: zebra
Output: Not Accepted 
Below is the implementation:
/* Lex Program to accept string starting with vowel */% {  int flag = 0;% }  %%  [aeiouAEIOU].[a-zA-Z0-9.]+ flag=1;[a-zA-Z0-9]+  %%  main(){ yylex(); if (flag == 1)     printf("Accepted");  else    printf("Not Accepted"); }
Output:
Lex program
C Programs
Compiler Design
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Producer Consumer Problem in C
Handling multiple clients on server with multithreading using Socket Programming in C/C++
Construction of LL(1) Parsing Table
Code Optimization in Compiler Design
Symbol Table in Compiler
Difference between Top down parsing and Bottom up parsing
Phases of a Compiler
How to Convert Character to a Timestamp in R? - GeeksforGeeks

28 Dec, 2021
In this article, we will convert character to timestamp in R Programming Language.
We can convert the character to timestamp by using strptime() method. strptime() function in R Language is used to parse the given representation of date and time with the given template.
Syntax: 
strptime(character, format, tz = “”)
Where,  
character: given representation of date and time   in string format
tz: a character string specifying the time zone to be used for the conversion
Example 1: Convert character to year , month and date format timestamp
R
# create charactercharacter = "2021-4-4" # convert character with year month and date formatprint(strptime(character, "%Y-%m-%d"))
Output:
[1] "2021-04-04 UTC"
Example 2: R program to convert character into timestamp
R
# create charactercharacter = "2021-4-4 02:23:34" # convert character with year month date# and Hours minutes and seconds formatprint(strptime(character, "%Y-%m-%d %H:%M:%S"))
Output:
[1] "2021-04-04 02:23:34 UTC"
Example 3: In this example, we are going to specify the timezone
R
# create charactercharacter = "2021-4-4 02:23:34" # convert character with year month date# and Hours minutes and seconds format# and specify time zone as UTCprint(strptime(character, "%Y-%m-%d %H:%M:%S",tz="UTC"))
Output:
[1] "2021-04-04 02:23:34 UTC"
surindertarika1234
Picked
R-DateTime
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?
append() and extend() in Python - GeeksforGeeks

01 Apr, 2020
Append: Adds its argument as a single element to the end of a list. The length of the list increases by one.
syntax: 
# Adds an object (a number, a string or a 
# another list) at the end of my_list
my_list.append(object)

my_list = ['geeks', 'for']my_list.append('geeks')print my_list
Output:
['geeks', 'for', 'geeks']

NOTE: A list is an object. If you append another list onto a list, the parameter list will be a single object at the end of the list.
my_list = ['geeks', 'for', 'geeks']another_list = [6, 0, 4, 1]my_list.append(another_list)print my_list
Output:
['geeks', 'for', 'geeks', [6, 0, 4, 1]]

 
extend(): Iterates over its argument and adding each element to the list and extending the list. The length of the list increases by number of elements in it’s argument.
syntax: 
# Each element of an iterable gets appended 
# to my_list
my_list.extend(iterable) 

my_list = ['geeks', 'for']another_list = [6, 0, 4, 1]my_list.extend(another_list)print my_list
Output:
['geeks', 'for', 6, 0, 4, 1]

NOTE: A string is an iterable, so if you extend a list with a string, you’ll append each character as you iterate over the string.
my_list = ['geeks', 'for', 6, 0, 4, 1]my_list.extend('geeks')print my_list
Output:
['geeks', 'for', 6, 0, 4, 1, 'g', 'e', 'e', 'k', 's']

Time Complexity:Append has constant time complexity i.e.,O(1).Extend has time complexity of O(k). Where k is the length of list which need to be added.
cffjob
python-list
python-list-functions
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
How to match a character from given string including case using Java regex?

The java.util.regex package of java provides various classes to find particular patterns in character sequences. The pattern class of this package is a compiled representation of a regular expression.
To match a specific character from the given input string −
Get the input string.
Get the input string.
This compile() method of this class accepts a string value representing a regular expression and an integer value representing a flag returns a Pattern object. Compile the regular expression bypassing −The pattern matcher “[ ]” with required character in it ex: “[t]”.The flag CASE_INSENSITIVE to ignore case.
This compile() method of this class accepts a string value representing a regular expression and an integer value representing a flag returns a Pattern object. Compile the regular expression bypassing −
The pattern matcher “[ ]” with required character in it ex: “[t]”.
The pattern matcher “[ ]” with required character in it ex: “[t]”.
The flag CASE_INSENSITIVE to ignore case.
The flag CASE_INSENSITIVE to ignore case.
The matcher() method of the Pattern class accepts an input string and returns a Matcher object. Create/Retrieve a matcher object using this method.
The matcher() method of the Pattern class accepts an input string and returns a Matcher object. Create/Retrieve a matcher object using this method.
find() − Using the find() method of the Matcher the matches.
find() − Using the find() method of the Matcher the matches.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CompileExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "[t]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("Number of matches: "+count);
   }
}
Enter input string
Tutorialspoint
Number of matches: 3
CSS Colors

CSS supports 140+ color names, HEX values, RGB values, RGBA 
values, HSL values, HSLA values, and opacity.
RGBA color values are an extension of RGB color values with an alpha channel - which specifies the opacity 
for a color.
An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0 
(fully transparent) and 1.0 (fully opaque).
The following example defines different RGBA colors:
HSL stands for Hue, Saturation and Lightness.
An HSL color value is specified with: hsl(hue, saturation, lightness).

Hue is a degree on the color wheel (from 0 to 360):
  
0 (or 360) is red
120 is green
240 is blue


Saturation is a percentage value: 100% is the full color.
Lightness is also a percentage; 0% is dark (black) and 100% is white.

Hue is a degree on the color wheel (from 0 to 360):
  
0 (or 360) is red
120 is green
240 is blue


0 (or 360) is red
120 is green
240 is blue
Saturation is a percentage value: 100% is the full color.
Lightness is also a percentage; 0% is dark (black) and 100% is white.
The following example defines different HSL colors:
HSLA color values are an extension of HSL color values with an alpha channel - which specifies the opacity 
for a color.
An HSLA color value is specified with: hsla(hue, saturation, lightness, alpha), where the 
alpha parameter defines the opacity. The alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).
The following example defines different HSLA colors:
The CSS opacity property sets the opacity for 
the whole element (both background color and text will be opaque/transparent).
The opacity property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).
Notice that the text above will also be 
transparent/opaque!
The following example shows different elements with opacity:
Insert the RGBA color value for a full red background color of the <h1> element, with no transparency.
<style>
h1 {
  background-color: ;
}
</style>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph</p>
  <p>This is a paragraph</p>
</body>

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to loop through an associative array and get the key in PHP? - GeeksforGeeks

30 Apr, 2019
Associative Array: Associative arrays are used to store key-value pairs. For example, to store the marks of the different subject of a student in an array, a numerically indexed array would not be the best choice. Instead, we could use the respective subject’s names as the keys in our associative array, and the value would be their respective marks gained. In associative array, the key-value pairs are associated with => symbol.
Method 1: In this method, traverse the entire associative array using foreach loop and display the key elements.Program: Program to loop through associative array and print keys.
<?php// Loop through associative array and get// the key of associative array  // Associative array$person_weight = array(    "Rajnish" => 58,     "Sanjeev" => 55,     "Ravi" => 60,     "Yash" => 60,    "Suraj" => 48);   // Use for-each loop and display the// key of associative arrayforeach($person_weight as $key => $value) {     echo "Key: " . $key . "\n"; }  ?>
Key: Rajnish
Key: Sanjeev
Key: Ravi
Key: Yash
Key: Suraj

Method 2: Using array_keys() function: The array_keys() is an inbuilt function in PHP which is used to return either all the keys of array or the subset of the keys.
Syntax:
array array_keys( $input_array, $search_value, $strict )
Program: Below program illustrate the use of array_keys() function to accessing the keys of associative array.
<?php// Use array_keys() function to display// the key of associative array  // Associative array$assoc_array = array(    "Geeks" => 30,    "for" => 20,    "geeks" => 10);   // Using array_keys() function$key = array_keys($assoc_array);  // Calculate the size of array$size = sizeof($key);  // Using loop to access keysfor( $i = 0; $i < $size; $i++) {    echo "key: ${key[$i]}\n";}  ?>
key: Geeks
key: for
key: geeks

Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Download file from URL using PHP
How to fetch data from localserver database and display on HTML table using PHP ?
How to run JavaScript from PHP?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
Split a comma delimited string into an array in PHP
C# | BitConverter Class - GeeksforGeeks

20 Feb, 2019
The use of BitConverter Class is to convert a base data types to an array of bytes and an array of bytes to base data types. This class is defined under System namespace. This class provides different types of methods to perform the conversion. Basically, a byte is defined as an 8-bit unsigned integer. This class helps in manipulating the value types in their fundamental form, as a series of bytes. It is done with the help of static methods. The static methods of BitConverter class are used to convert each of the primitive types to and from an array of bytes.
Field:
IsLittleEndian: This indicates the byte order (“endianness”) in which data is stored in this computer architecture.
Example 1:
// C# program to illustrate the// use of GetBytes(Int64) methodusing System;  class GFG {      // Main method    static public void Main()    {          // Creating and initializing an array        long[] ele = {0, long.MaxValue, long.MinValue,                         1000000000000000, -100000000,                        0xDDDDDDDDD, -0xAAAAAAAAAAAA };          // Display the elements        Console.WriteLine("Elements are:");        foreach(long i in ele)        {            Console.WriteLine(i);        }          foreach(var num in ele)        {              // Get the specified 64-bit signed            // integer value as an array of bytes.            // using GetBytes(Int64) method            byte[] BArr = BitConverter.GetBytes(num);              // Display the elements            Console.WriteLine("Element: {0}",                 BitConverter.ToString(BArr));        }    }}
Output:
Elements are:
0
9223372036854775807
-9223372036854775808
1000000000000000
-100000000
59556879837
-187649984473770
Element: 00-00-00-00-00-00-00-00
Element: FF-FF-FF-FF-FF-FF-FF-7F
Element: 00-00-00-00-00-00-00-80
Element: 00-80-C6-A4-7E-8D-03-00
Element: 00-1F-0A-FA-FF-FF-FF-FF
Element: DD-DD-DD-DD-0D-00-00-00
Element: 56-55-55-55-55-55-FF-FF

Example 2:
// C# program to illustrate the// use of Int64BitsToDouble(Int64)// methodusing System;  class GFG {      // Main method    static public void Main()    {          long ele = 0xFFFFFFFFFFFFFFF;          // Converts the given 64-bit signed        // integer to a double-precision         // floating point number using the         // Int64BitsToDouble(Int64) method        double R = BitConverter.Int64BitsToDouble(ele);          // Display the element        Console.WriteLine("Converted Element is : {0}", R);    }}
Output:
Converted Element is : 1.28822975391943E-231
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter?view=netframework-4.7.2
CSharp-BitConverter-Class
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to .NET Framework
Difference between Abstract Class and Interface in C#
C# | Method Overriding
C# | Arrays of Strings
C# Dictionary with examples
C# | Constructors
Program to calculate Electricity Bill
C# | Delegates
C# | Class and Object
C# | IsNullOrEmpty() Method
Daily Temperatures in Python

Suppose we have a list of daily temperatures T, we have to return a list such that, for each day in the input, shows how many days we would have to wait until a warmer temperature. If there is no future day for which this is possible, store 0 instead. For example, if T = [73, 74, 75, 71, 69, 72, 76, 73], output will be [1, 1, 4, 2, 1, 1, 0, 0].
To solve this, we will follow these steps −
ans := an array of size same as T, and fill this with 0
define one stack, and insert 0 into the stack, and i := 1
while i < length of Twhile stack element count is not 0 and T[i] > T[stack top element]index := stack top elementans[index] := i – indexdelete top element from stackif length of stack is 0 or T[i] <= T[stack top element]insert i into stackincrease i by 1
while stack element count is not 0 and T[i] > T[stack top element]index := stack top elementans[index] := i – indexdelete top element from stack
index := stack top element
ans[index] := i – index
delete top element from stack
if length of stack is 0 or T[i] <= T[stack top element]insert i into stack
insert i into stack
increase i by 1
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def dailyTemperatures(self, T):
      ans = [0 for i in range(len(T))]
      stack = []
      stack.append(0)
      i=1
      while i <len(T):
         while len(stack) and T[i]>T[stack[-1]]:
            index = stack[-1]
            ans[index] = i-index
            stack.pop()
         if not len(stack) or T[i]<=T[stack[-1]]:
            stack.append(i)
         i+=1
      return ans
ob1 = Solution()
print(ob1.dailyTemperatures([73,74,75,71,69,72,76,73]))
[73,74,75,71,69,72,76,73]
[1, 1, 4, 2, 1, 1, 0, 0]