code-rag-bench/online-tutorials huggingface dataset:
How to Append or Concatenate Strings in Dart? - GeeksforGeeks

18 Apr, 2022
In Dart concatenation of string can be done in four different ways:
By using ‘+’ operator.By string interpolation.By directly writing string literals.By Strings.join() method.
By using ‘+’ operator.
By string interpolation.
By directly writing string literals.
By Strings.join() method.
In Dart, we can use the ‘+’ operator to concatenate the strings.
Example: Using ‘+’ operator to concatenate strings in Dart.
Dart
// Main functionvoid main() {     // Assigning values  // to the variable  String gfg1 = "Geeks";  String gfg2 = "For";     // Printing concatenated result  // by the use of '+' operator  print(gfg1 + gfg2 + gfg1);}
 
Output:
GeeksForGeeks
In Dart, we can use string interpolation to concatenate the strings.
Example: Using string interpolation to concatenate strings in Dart. 
Dart
// Main functionvoid main() {     // Assigning values to the variable  String gfg1 = "Geeks";  String gfg2 = "For";     // Printing concatenated result  // by the use of string  // interpolation without space  print('$gfg1$gfg2$gfg1');     // Printing concatenated result  // by the use of  // string interpolation  // with space  print('$gfg1 $gfg2 $gfg1');}
 
Output:
GeeksForGeeks
Geeks For Geeks
In Dart, we concatenate the strings by directly writing string literals and appending it.
Example: By directly writing string literals to concatenate strings in Dart. 
Dart
// Main functionvoid main() {     // Printing concatenated  // result without space  print('Geeks''For''Geeks');     // Printing concatenated  // result with space  print('Geeks ''For ''Geeks');}
 
Output:
GeeksForGeeks
Geeks For Geeks
In Dart, we can also convert the elements of the list into one string.
list_name.join("input_string(s)");
This input_string(s) are inserted between each element of the list in the output string.
Example: Using list_name.join() concatenate strings in Dart. 
Dart
// Main functionvoid main() {      // Creating List of strings  List<String> gfg = ["Geeks", "For" , "Geeks"];     // Joining all the elements  // of the list and  // converting it to String  String geek1 = gfg.join();     // Printing the  // concatenated string  print(geek1);     // Joining all the elements  // of the list and converting  // it to String  String geek2 = gfg.join(" ");     // Printing the  // concatenated string  print(geek2);}
 
Output:
GeeksForGeeks
Geeks For Geeks
simranarora5sos
Dart-String
Dart
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
ListView Class in Flutter
Flutter - Checkbox Widget
Flutter - Flexible Widget
Flutter - BoxShadow Widget
Dart Tutorial
Flutter - Stack Widget
Operators in Dart
Android Studio Setup for Flutter Development
AngularJS | angular.isElement() Function - GeeksforGeeks

12 Apr, 2019
The angular.isElement() Function in AngularJS is used to determine if the parameter inside isElement function is a HTML DOM element or not. It returns true if the reference is a DOM element else false.
Syntax:
angular.isElement(value)
Return Value: It returns true if the value passed is a HTML DOM element else false.
Example:
<!DOCTYPE html><html>  <head>    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js">    </script>    <title>      angular.isElement()  </title></head>  <body ng-app="testApp"       style="text-align:center">        <h1 style="color:green">      GeeksforGeeks  </h1>    <h2>      angular.isElement()  </h2>      <div ng-controller="geek">        <br>        <b>Input1:</b>        <code>            {'destroy': true, 'create': false}        </code>        <br>        <b>isElement:</b> {{ isElement1 }}        <br>        <br>        <br>        <b>Input2:</b>        <code>             window.getElementByID('myButton')        </code>        <br>        <b>isElement:</b> {{ isElement2 }}        <br>        <br>        <button id="myButton"> Button</button>    </div>    <script>        var app = angular.module('testApp', []);          app.controller('geek', function($scope) {              $scope.obj1 = {                'destroy': true,                'create': false            };            $scope.obj2 = document.getElementById('myButton');            $scope.isElement1 =               angular.isElement($scope.obj1);                        $scope.isElement2 =               angular.isElement($scope.obj2);        });    </script></body>  </html>
Output:
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular File Upload
Angular PrimeNG Dropdown Component
Angular | keyup event
Auth Guards in Angular 9/10/11
How to Display Spinner on the Screen till the data from the API loads using Angular 8 ?
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Python - Row with Maximum Record Element - GeeksforGeeks

02 Jun, 2020
Sometimes, while working with Python Records, we can have a problem in which we need to find the row with maximum record element. This kind of problem can come in domains of web development and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[(70, 4), (6, 7)], [(15, 2), (19, 3)]]Output : [(70, 4), (6, 7)]
Input : test_list = [[(20, 4)], [(15, 2)], [(34, 6)]]Output : [(34, 6)]
Method #1 : Using max() + keyThe combination of above functions can be used to solve this problem. In this, we extract maximum row using max() and key is used to check for initial element of records.
# Python3 code to demonstrate working of # Row with Maximum Record Element# Using max() + key  # initializing listtest_list = [[(12, 4), (6, 7)],              [(15, 2), (19, 3)],              [(18, 3), (12, 4)],              [(17, 1), (11, 3)]]  # printing original listprint("The original list is : " + str(test_list))  # Row with Maximum Record Element# Using max() + keyres = max(test_list, key = max)  # printing result print("The row with Maximum Value : " + str(res)) 
The original list is : [[(12, 4), (6, 7)], [(15, 2), (19, 3)], [(18, 3), (12, 4)], [(17, 1), (11, 3)]]The row with Maximum Value : [(15, 2), (19, 3)]
 
Method #2 : Using max() + itemgetter()This is yet another way to solve this problem. This approach provides flexibility to make a choice on element index for comparison, rather than just initial as in above method by the usage of itemgetter().
# Python3 code to demonstrate working of # Row with Maximum Record Element# Using max() + itemgetter()from operator import itemgetter  # initializing listtest_list = [[(12, 4), (6, 7)],              [(15, 2), (19, 3)],              [(18, 3), (12, 4)],              [(17, 1), (11, 3)]]  # printing original listprint("The original list is : " + str(test_list))  # Row with Maximum Record Element# Using max() + itemgetter()res = max(test_list, key = itemgetter(1))  # printing result print("The row with Maximum Value : " + str(res)) 
The original list is : [[(12, 4), (6, 7)], [(15, 2), (19, 3)], [(18, 3), (12, 4)], [(17, 1), (11, 3)]]The row with Maximum Value : [(15, 2), (19, 3)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
GATE CS 1998 - GeeksforGeeks

11 Oct, 2021
x+2y = 5
4x+8y = 12
3x+6y+3z = 15
Consider the function y = |x| in the interval [-1,1]. In this interval, the function is
I stay only if you go.
(0+1)* 
= (0*+1*)* 
= (01*)* 
= (0*+1)* 
= (0+1*)* 
= 0*(10*)* 
= 1*(01*)* 
(01+1)* = ((01)* 1* )*  
L = {1, 10, 100, 1000, 10000, ...} 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
How to open a file to write in Python?

To open files in just write mode, specify 'w' as the mode. For example,
f = open('my_file.txt', 'w')
f.write('Hello World')
f.close()
Above code opens my_file.txt in write mode and rewrites the file to contain "Hello World". A safer approach would be using the with open syntax to avoid file from not closeing in case of an exception:
with open('my_file.txt', 'r') as f:
    f.write('Hello World')
Java Program to get the beginning and end date of the week

At first, set a date:
LocalDate date = LocalDate.of(2019, 4, 16);
Now, get the date for the beginning of the week:
LocalDate start = date;
while (start.getDayOfWeek() != DayOfWeek.MONDAY) {
   start = start.minusDays(1);
}
Now, get the date for the end of the week:
LocalDate end = date;
while (end.getDayOfWeek() != DayOfWeek.SUNDAY) {
   end = end.plusDays(1);
}
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Demo {
   public static void main(String[] argv) {
      LocalDate date = LocalDate.of(2019, 4, 16);
      System.out.println("Date = " + date);
      LocalDate start = date;
      while (start.getDayOfWeek() != DayOfWeek.MONDAY) {
         start = start.minusDays(1);
      }
      System.out.println("Start of the Week = " + start);
      LocalDate end = date;
      while (end.getDayOfWeek() != DayOfWeek.SUNDAY) {
         end = end.plusDays(1);
      }
      System.out.println("End of the Week = " + end);
   }
}
Date = 2019-04-16
Start of the Week = 2019-04-15
End of the Week = 2019-04-21
base64.decodestring(s) in Python - GeeksforGeeks

22 Apr, 2020
With the help of base64.decodestring(s) method, we can decode the binary string with the help of base64 data into normal form.
Syntax : base64.decodestring(b_string)
Return : Return the decoded string.
Example #1 :In this example we can see that by using base64.decodestring(s) method, we are able to get the decoded string which can be in binary form by using this method.
# import base64from base64 import encodestringfrom base64 import decodestring  s = b'GeeksForGeeks's = encodestring(s)# Using base64.decodestring(s) methodgfg = decodestring(s)  print(gfg)
Output :
b’GeeksForGeeks’
Example #2 :
# import base64from base64 import encodestringfrom base64 import decodestring  s = b'Hello World's = encodestring(s)# Using base64.decodestring(s) methodgfg = decodestring(s)  print(gfg)
Output :
b’Hello World’
Python base64-module
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
Defaultdict in Python
Create a directory in Python
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
ifdown command in Linux with Examples

20 Mar, 2019
Unlike ifup command the user can use ifdown command to bring network interface down, not allowing the user to transmit and receive data. Technically it places the network interface in a state where it cannot transmit or receive data. It is used to configure network interfaces based on interface definitions in the file /etc/network/interfaces.
Syntax:
ifdown [-nv] [–no-act] [–verbose] [-i FILE|–interfaces=FILE] [–allow CLASS] -a|IFACE...
Options:
-a(–all): This option is used to bring all the interface down which are defined in /etc/network/interfaces.
–allow=CLASS: This option will only allow interfaces listed in an allow-CLASS line in /etc/network/interfaces to be acted upon.
-v(–verbose): Show or verbose commands as they are executed.
-V(–version): Prints the Copyright and version information.
Example:
Let us execute a ping command to check the working of my interfaces, they are already configured.
Now try to down the interface down using the following command. Here, sudo is used for permissions, -a to work on all devices and v for verbose the output.sudo ifdown -av
sudo ifdown -av
Let us check our ping test and browser.
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
TCP Server-Client implementation in C
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
echo command in Linux with Examples
Node.js trim() function

14 Oct, 2021
The trim() function is a string function of Node.js which is used to remove white spaces from the string.
Syntax:
string.trim()
Parameter: This function does not accepts any parameter.
Return Value: The function returns the string without white spaces.
Below programs demonstrate the working of trim() function:
Program 1:
function trim(str) {          // Use trim() function    var trimContent = str.trim();          console.log(trimContent);}  // Initialize variablevar str = "       *GeeksforGeeks*          ";  // Function calltrim(str);
Output:
*GeeksforGeeks*
Program 2:
function trim(str) {          // Use trim() function    var trimContent = str.trim();          console.log(trimContent);}  // Initialize variablevar str = "       Welcome to GeeksforGeeks          ";  // Function calltrim(str);    
Output:
Welcome to GeeksforGeeks
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
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
How to create a clickable button in HTML ?

18 Jun, 2020
In this article, we will create a Button by using the <Button> Element in the Document.It is used to submit the content. The images and text content can use inside a button tag.
Syntax:
<button type = "button">
Example: Using HTML <button> type Attribute
<!DOCTYPE html> <html>     <head>         <title>            How to create a clickable button?              </title>     </head>           <body>       <center>        <p>            <h2>                GeeksForGeeks        </h2>        </p>         <h2>            HTML: How to create a clickable button?          </h2>                  <!-- button tag starts from here -->        <button type = "button" onclick =             "alert('Welcome to GeeksforGeeks')">             Click Here         </button>         <!-- button tag ends here -->              </body> </html>                     
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML-Attributes
HTML-Basics
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
Installation of Node.js on Linux
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 ?
How to open any file with its default application with PowerShell?

To open any file using its default application, we can use the Invoke-Expression command. For example, we want to open a file on the C:\temp and the file name is NewUsers.CSV then you can run the below command.
Invoke-Expression C:\Temp\NewUsers.csv
The above command will open the file from that location. If the default application is not set then Windows will ask for the default application to select.
If you know any application name and which can be opened with the shortcut then you can directly type the name of the application. For example, Notepad.exe, Calc.exe
Generally, they can be opened directly but this command also helps to open the application as shown below.
PS C:\> Invoke-Expression notepad.exe
PS C:\> Invoke-Expression calc.exe
Change Object Display Name using __str__ function - Django Models | Python - GeeksforGeeks

13 Feb, 2020
How to Change Display Name of an Object in Django admin interface? Whenever an instance of model is created in Django, it displays the object as ModelName Object(1). This article will explore how to make changes to your Django model using def __str__(self) to change the display name in the model.
Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into models.py file of geeks app.
from django.db import modelsfrom django.db.models import Model# Create your models here.  class GeeksModel(Model):    geeks_field = models.CharField(max_length = 200)
After running makemigrations and migrate on Django and rendering above model, let us try to create an instance using string “GfG is Best“.Now it will display the same object created as GeeksModel object(1) in the admin interface.
To change the display name we will use def __str__() function in a model. str function in a django model returns a string that is exactly rendered as the display name of instances for that model.For example, if we change above models.py to
from django.db import modelsfrom django.db.models import Model# Create your models here.  class GeeksModel(Model):    geeks_field = models.CharField(max_length = 200)         def __str__(self):         return "something"
This will display the objects as something always in the admin interface.
Most of the time we name the display name which one could understand using self object. For example return self.geeks_field in above function will return the string stored in geeks_field of that object and it will be displayed in admin interface..
Note that str function always returns a string and one can modify that according to one’s convenience.
Render Model in Django Admin Interface
Built-in Field Validations – Django Models
NaveenArora
Django-models
Python Django
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
How to compare two different files line by line in Python?

The Python standard library has a module specifically for the purpose of finding diffs between strings/files. To get a diff using the difflib library, you can simply call the united_diff function on it. For example, Lets say you have 2 files, file1 and file2 with the following content −
file1:
Hello
People
of
the
world
file2:
Hello
People
from
India
Now to take their diff use the following code −
import difflib
with open('file1') as f1:
    f1_text = f1.read()
with open('file2') as f2:
    f2_text = f2.read()
# Find and print the diff:
for line in difflib.unified_diff(f1_text, f2_text, fromfile='file1', tofile='file2', lineterm=''):
    print line
This will give the output −
--- file1
+++ file2
@@ -1,5 +1,4 @@
 Hello
 People
-of
-the
-world
+from
+India
How to Create an Empty Plot in R ? - GeeksforGeeks

16 May, 2021
In this article, we will discuss how to create an empty plot in R. Before moving to create the empty plot let’s first discuss what is an empty plot? The plot on which nothing is plotted is known as an empty plot also known as a blank plot.
R language provides the plot() function to draw the plot.
Syntax: plot(x,y,...)
Parameters:
x stands for the x-axis
y stands for the y-axis
... stands for the other features like title, color etc
Now we discuss some methods through which we can create an empty plot:
Method 1: Using plot.new()
The plot.new() function will create the empty plot. This will give a signal to R that a new window of the plot is created. So, an empty window of the plot is created with the help of this function.
R
# plot function is used # to draw the plot and # new is used to make # that plot newplot.new()
Output:
fig 1: Empty plot
Method 2: Using plot.window()
The plot.window() function will create the empty plot. This will give a signal to R that a new window of the plot is created. So, an empty window of the plot is created with the help of this function. But the arguments are necessary for this function to set the limit of the plot. So in this, we give the limits of both the axis.
R
# plot is used to create the plot# window is used to create the plot# window and limits are set of the# axis because limit arguments are # necessaryplot.window(xlim = c(0 , 1), ylim = c( 5, 10))
Output:
fig 2: Empty plot
Method 3: Using plot()
The plot function is used to create a plot. So, in this method first, we create the plot using the plot function and then we remove the dots or the data which is plotted on the plot. To remove the plotted data we use the type = “n” as an argument in the plot function here “n” is used to remove the plotted data.
R
# plot function is used to plot# the data type with "n" is used# to remove the plotted dataplot(1, type = "n", xlab = "",     ylab = "", xlim = c(0, 5),      ylim = c(0, 5))
Output :
fig 3: Plot with removed data
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
Time Series Analysis in R
Java String Methods

String class has a lot of methods in Java to manipulate strings, finding length, format strings, concatenate, etc.
Following are some of the string methods in Java −
Here, we will find the length of strings and concatenate them −
public class Main {
   public static void main(String args[]) {
      String str1 = "This is ";
      String str2 = "it!";
      System.out.println("String1 = "+str1);
      System.out.println("String2 = "+str2);
      int len1 = str1.length();
      System.out.println( "String1 Length = " + len1 );
      int len2 = str2.length();
      System.out.println( "String2 Length = " + len2 );
      System.out.println("Performing Concatenation...");
      System.out.println(str1 + str2);
   }
}
String1 = This is
String2 = it!
String1 Length = 8
String2 Length = 3
Performing Concatenation...
This is it!
Let us see another example wherein we are comparing this string to the specified object −
import java.util.*;
public class Demo {
   public static void main( String args[] ) {
      String Str1 = new String("This is really not immutable!!");
      String Str2 = Str1;
      String Str3 = new String("This is really not immutable!!");
      boolean retVal;
      retVal = Str1.equals( Str2 );
      System.out.println("Returned Value = " + retVal );
      retVal = Str1.equals( Str3 );
      System.out.println("Returned Value = " + retVal );
   }
}
Returned Value = true
Returned Value = true
Node.js Buffer.from() Method

13 Oct, 2021
The Buffer.from() method is used to create a new buffer containing the specified string, array or buffer.
Syntax:
Buffer.from( object, encoding )
Parameters: This method accept two parameters as mentioned above and described below:
object: This parameter can hold either a string, buffer, array or an arrayBuffer.
encoding: If the object is a string then it is used to specify its encoding. It is optional parameter. Its default value is utf8.
Example 1:
// Node.js program to demonstrate the  // Buffer.from() Method  // Returns a new buffer with// copy of the given stringvar buf1 = Buffer.from("hello");   // Display the buffer object// of the given stringconsole.log(buf1);   // Convert the buffer to the // string and displays itconsole.log(buf1.toString());
Output:
<Buffer 68 65 6c 6c 6f>
hello

Example 2:
// Node.js program to demonstrate the  // Buffer.from() Method  // Creates an arrayBuffer with// length 10var arbuff = new ArrayBuffer(8);   // Returns a new buffer with a// specified memory range within// the arrayBuffervar buf = Buffer.from(arbuff, 0, 2);   // Displays the lengthconsole.log(buf.length);
Output:
2
Example 3:
// Node.js program to demonstrate the  // Buffer.from() Method  // Create a new buffer with// copy of the given stringvar buf1 = Buffer.from("John");   // Create another buffer with// copy of given buffervar buf2 = Buffer.from(buf1);   // Display the buffer objectconsole.log(buf2);   // Convert the buffer to// string and displays itconsole.log(buf2.toString());
Output:
<Buffer 4a 6f 68 6e>
John

Note: The above program will compile and run by using the node index.js command.
Reference: https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_string_encoding
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | List consisting of all the alternate elements

24 Dec, 2018
Some of the list operations are quite general and having shorthands without needing to formulate a multiline code is always required. Wanting to construct the list consisting of all the alternate elements of the original list is a problem that one developer faces in day-day applications.
Let’s discuss certain ways to print all the alternate elements of the given list.
Method #1 : Using list comprehension
Shorthand to the naive method, list comprehension provides a faster way to perform this particular task. In this method, all the indices which are not multiple of 2, hence odd are inserted in the new list.
# Python code to demonstrate # to construct alternate element list# using list comprehension   # initializing list test_list = [1, 4, 6, 7, 9, 3, 5]  # printing original list print ("The original list : " + str(test_list))  # using list comprehension# to construct alternate element listres = [test_list[i] for i in range(len(test_list)) if i % 2 != 0]  # printing result print ("The alternate element list is : " + str(res))
The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]

 Method #2 : Using enumerate()This is just a variation to the list comprehension method but does the similar internal working as list comprehension but uses different variables to keep track of index along with its value.
# Python code to demonstrate # to construct alternate element list# using enumerate()   # initializing list test_list = [1, 4, 6, 7, 9, 3, 5]  # printing original list print ("The original list : " + str(test_list))  # using enumerate()# to construct alternate element listres = [i for j, i in enumerate(test_list) if j % 2 != 0]  # printing result print ("The alternate element list is : " + str(res))
The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]

  Method #3 : Using Slice notationThis the most pythonic and elegant way to perform this particular task and enhances to the full power of python. We can use the skip utility provided by slice to get the alternate elements from start to end in the list.
# Python code to demonstrate # to construct alternate element list# using Slice notation  # initializing list test_list = [1, 4, 6, 7, 9, 3, 5]  # printing original list print ("The original list : " + str(test_list))  # using Slice notation# to construct alternate element listres = test_list[1::2]  # printing result print ("The alternate element list is : " + str(res))
The original list : [1, 4, 6, 7, 9, 3, 5]
The alternate element list is : [4, 7, 3]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Blocking and Non-Blocking in Node.js

21 May, 2021
Node.js is based on an event-driven non-blocking I/O model. This article discusses what does Blocking and Non-Blocking in Node.js means.
Blocking: It refers to the blocking of further operation until the current operation finishes. Blocking methods are executed synchronously. Synchronously means that the program is executed line by line. The program waits until the called function or the operation returns.
Example: Following example uses the readFileSync() function to read files and demonstrate Blocking in Node.js
index.js
const fs = require('fs');   const filepath = 'text.txt';  // Reads a file in a synchronous and blocking way const data = fs.readFileSync(filepath, {encoding: 'utf8'});  // Prints the content of fileconsole.log(data);  // This section calculates the sum of numbers from 1 to 10let sum = 0;for(let i=1; i<=10; i++){    sum = sum + i;}  // Prints the sumconsole.log('Sum: ', sum);
Run the index.js file using the following command:
node index.js
Output:
This is from text file.
Sum:  55
Non-Blocking: It refers to the program that does not block the execution of further operations. Non-Blocking methods are executed asynchronously. Asynchronously means that the program may not necessarily execute line by line. The program calls the function and move to the next operation and does not wait for it to return.
Example: Following example uses the readFile() function to read files and demonstrate Non-Blocking in Node.js
index.js
const fs = require('fs');   const filepath = 'text.txt';  // Reads a file in a asynchronous and non-blocking way fs.readFile(filepath, {encoding: 'utf8'}, (err, data) => {    // Prints the content of file    console.log(data);});    // This section calculates the sum of numbers from 1 to 10let sum = 0;for(let i=1; i<=10; i++){    sum = sum + i;}  // Prints the sumconsole.log('Sum: ', sum);
Run the index.js file using the following command:
node index.js
Output:
Sum:  55
This is from text file.
Note: In the non-blocking program the sum actually prints before the content of the file. This is because the program does not wait for the readFile() function to return and move to the next operation. And when the readFile() function returns it prints the content.
Node.js-Basics
NodeJS-function
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
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
Second largest value in a Python Dictionary

20 Dec, 2018
In this problem we will find the second largest value in the given Dictionary.Examples:
Input :  {'one':5, 'two':1, 'three':6, 'four':10}
Output :  Second largest value of the dictionary is 6

Input :   {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Output :  Second largest value of the dictionary is Geeks

dictionary = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}val = list(dictionary.values())val.sort()res = val[-2]print(res)
Geeks

Time Complexity : O(n Log n)
Please refer below post for more methods :
Python program to find second maximum value in Dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
numpy.random.exponential() in Python

15 Jul, 2020
With the help of numpy.random.exponential() method, we can get the random samples from exponential distribution and returns the numpy array of random samples by using this method.
exponential distribution
Syntax : numpy.random.exponential(scale=1.0, size=None)
Return : Return the random samples of numpy array.
Example #1 :
In this example we can see that by using numpy.random.exponential() method, we are able to get the random samples of exponential distribution and return the samples of numpy array.
Python3
# import exponentialimport numpy as npimport matplotlib.pyplot as plt  # Using exponential() methodgfg = np.random.exponential(3.45, 10000)  count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()
Output :
Example #2 :
Python3
# import exponentialimport numpy as npimport matplotlib.pyplot as plt  # Using exponential() methodgfg = np.random.exponential(101.123, 10000)gfg1 = np.random.exponential(gfg, 10000)  count, bins, ignored = plt.hist(gfg1, 14, density = True)plt.show()
Output :
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to calculate dot product of two vectors in Python?

25 May, 2021
In mathematics, the dot product or also known as the scalar product is an algebraic operation that takes two equal-length sequences of numbers and returns a single number. Let us given two vectors A and B, and we have to find the dot product of two vectors.
Given that, 
 
and,
Where,
i: the unit vector along the x directions
j: the unit vector along the y directions
k: the unit vector along the z directions
 
Then the dot product is calculated as:
 
Example:
 
Given two vectors A and B as,
 
Python provides a very efficient method to calculate the dot product of two vectors. By using numpy.dot() method which is available in the NumPy module one can do so.
 
Syntax:
numpy.dot(vector_a, vector_b, out = None)
Parameters:
vector_a: [array_like] if a is complex its complex conjugate is used for the calculation of the dot product.
vector_b: [array_like] if b is complex its complex conjugate is used for the calculation of the dot product.
out: [array, optional] output argument must be C-contiguous, and its dtype must be the dtype that would be returned for dot(a,b).
 
Return:
Dot Product of vectors a and b. if vector_a and vector_b are 1D, then scalar is returned
Example 1:
 
Python
# Python Program illustrating# dot product of two vectors # Importing numpy moduleimport numpy as np # Taking two scalar valuesa = 5b = 7 # Calculating dot product using dot()print(np.dot(a, b))
Output:
35
Example 2:
Python
# Python Program illustrating# dot product of two vectors # Importing numpy moduleimport numpy as np # Taking two 1D arraya = 3 + 1jb = 7 + 6j # Calculating dot product using dot()print(np.dot(a, b))
Output:
(15+25j)
Example 3:
Python
# Python Program illustrating# dot product of two vectors # Importing numpy moduleimport numpy as np # Taking two 2D array# For 2-D arrays it is the matrix producta = [[2, 1], [0, 3]]b = [[1, 1], [3, 2]] # Calculating dot product using dot()print(np.dot(a, b))
Output:
[[5 4]
 [9 6]]
Example 4:
Python
# Python Program illustrating# dot product of two vectors # Importing numpy moduleimport numpy as np # Taking two 2D array# For 2-D arrays it is the matrix producta = [[2, 1], [0, 3]]b = [[1, 1], [3, 2]] # Calculating dot product using dot()# Note that here I have taken dot(b, a)# Instead of dot(a, b) and we are going to# get a different output for the same vector valueprint(np.dot(b, a))
Output:
[[2 4]
 [6 9]]
Code_Mech
Python numpy-Matrix Function
Python-numpy
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Building frequency map of all the elements in an array JavaScript

We will be given an array of numbers / strings that contains some duplicate entries, all we have to do is to return the frequency of each element in the array.
Returning an object with an element as key and its value as frequency would be perfect for this situation.
We will iterate over the array with a forEach() loop and keep increasing the count of elements in the object if it already exists otherwise we will create a new property for that element in the object.
And lastly, we will return the object.
The full code for this problem will be −
const arr = [2,5,7,8,5,3,5,7,8,5,3,4,2,4,2,1,6,8,6];
const getFrequency = (array) => {
   const map = {};
   array.forEach(item => {
      if(map[item]){
         map[item]++;
      }else{
         map[item] = 1;
      }
   });
   return map;
};
console.log(getFrequency(arr));
The output in the console will be −
{ '1': 1, '2': 3, '3': 2, '4': 2, '5': 4, '6': 2, '7': 2, '8': 3 }
Lua - Overview

Lua is an extensible, lightweight programming language written in C. It started as an in-house project in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes.
It was designed from the beginning to be a software that can be integrated with the code written in C and other conventional languages. This integration brings many benefits. It does not try to do what C can already do but aims at offering what C is not good at: a good distance from the hardware, dynamic structures, no redundancies, ease of testing and debugging. For this, Lua has a safe environment, automatic memory management, and good facilities for handling strings and other kinds of data with dynamic size.
Lua provides a set of unique features that makes it distinct from other languages. These include −
Extensible
Simple
Efficient
Portable
Free and open
print("Hello World!")
Lua consists of two parts - the Lua interpreter part and the functioning software system. The functioning software system is an actual computer application that can interpret programs written in the Lua programming language. The Lua interpreter is written in ANSI C, hence it is highly portable and can run on a vast spectrum of devices from high-end network servers to small devices.
Both Lua's language and its interpreter are mature, small, and fast. It has evolved from other programming languages and top software standards. Being small in size makes it possible for it to run on small devices with low memory.
The most important point while learning Lua is to focus on the concepts without getting lost in its technical details.
The purpose of learning a programming language is to become a better programmer; that is, to become more effective in designing and implementing new systems and at maintaining old ones.
Game Programming
Game Programming
Scripting in Standalone Applications
Scripting in Standalone Applications
Scripting in Web
Scripting in Web
Extensions and add-ons for databases like MySQL Proxy and MySQL WorkBench
Extensions and add-ons for databases like MySQL Proxy and MySQL WorkBench
Security systems like Intrusion Detection System.
Security systems like Intrusion Detection System.

    12 Lectures 
     2 hours 

 Manish Gupta

    80 Lectures 
     3 hours 

 Sanjeev Mittal

    54 Lectures 
     3.5 hours 

 Mehmet GOKTEPE
 Print
 Add Notes
 Bookmark this page
What is the effect of extern “C” in C++?

The extern “C” keyword is used to make a function name in C++ have the C linkage. In this case the compiler does not mangle the function. Let us see what is the mangling in C++ first, then we can discuss about the extern “C” keyword.
In C++ we can use the function overloading feature. Using this feature, we can create functions with same name. The only difference is the type of the arguments, and the number of arguments. The return type is not considered here. Now the question comes how the C++ distinguishes overloaded functions in object code?
In the object code, it changes the name by adding information about the arguments. The technique which is applied here is called the Name Mangling. C++ has no standardized technique for name mangling. So different compiler uses different techniques.
Here is an example of Name Mangling. The overloaded functions are named as func(), and another function my_function() is there.
int func(int x) {
   return x*x;
}
double func(double x) {
   return x*x;
}
void my_function(void) {
   int x = func(2); //integer
   double y = func(2.58); //double
}
Some C++ compiler will change it like below −
int __func_i(int x){
   return x*x;
}
double __func_d(double x){
   return x*x;
}
void __my_function_v(void){
   int x = __func_i(2); //integer
   double y = __func_d(2.58); //double
}
The C does not support function overloading, So we have to make sure that name of a symbol is not changed, when we link a C code in C++. The following C++ code will generate an error.
int printf(const char *format,...);
main() {
   printf("Hello World");
}
undefined reference to `printf(char const*, ...)'
ld returned 1 exit status
This problem is generating because the name of the printf() is changed by the compiler. And it does not find the definition of the updated printf() function. To overcome this problem, we have to use the extern “C” in C++. When some code is used inside this block, then C++ compiler ensures that the function name is unmangled. So the name will not be changed. So the above code will be like this to solve this problem.
extern "C"{
   int printf(const char *format,...);
}
main() {
   printf("Hello World");
}
Hello World
Note: These block of codes may generate different results in different compilers.
So the extern “C” is basically one linkage specification. In every compiler, we have to use this keyword to specify the C linkage. And another thing we have to keep in mind that the linkage specifications must be in the namespace scope. The class members are ignored from the extern “C”
JavaScript Create Submit button for form submission and another button to clear input

Use input type=”submit” to submit the form and another input type=”button” to clear the input on
click as in the below code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
</style>
<body>
<label>StudentName:
<input type="text" id="txtName" />
</label>
<br>
<button type="submit">Submit</button>
<button type=" button" value="delete"
onclick="deleteSomething()">Delete</button>
<script>
   function deleteSomething(secondValue) {
      alert("I am going to clear text box data only...");
      document.getElementById("txtName").value = "";
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
Now, I am going to enter some value into the text box −
Now, I am going to click the button Delete. On clicking, you will get an alert message −
After clicking the OK button, you will get the following output −
How to merge two arrays in JavaScript?

To merge two arrays in JavaScript, use the Array.concat() method. JavaScript array concat() method returns a new array comprised of this array joined with two or more arrays.
You can try to run the following code to merge two arrays:
Live Demo
<html>    
   <head>      
      <title>JavaScript Array concat Method</title>    
   </head>      
   <body>          
      <script>          
         var alpha = ["a", "b", "c"];          
         var numeric = [1, 2, 3];  
         var alphaNumeric = alpha.concat(numeric);          
         document.write("alphaNumeric : " + alphaNumeric );        
      </script>          
   </body>
</html>
alphaNumeric : a,b,c,1,2,3
Tryit Editor v3.7

Tryit: Using box-shadow to create paper-like cards
Math floorMod() Method in Java - GeeksforGeeks

20 Jun, 2018
The java.lang.Math.floorMod() is a built-in math function in java which returns the floor modulus of the integer arguments passed to it. Therefore, floor modulus is (a – (floorDiv(a, b) * b)), has the same sign as the divisor b, and is in the range of -abs(b) < t < +abs(b).
Relationship between floorDiv and floorMod is:
floorDiv(a, b) * b + floorMod(a, b) == a
The difference in values between floorMod and the % operator is due to the difference between floorDiv that returns the integer less than or equal to the quotient and the / operator that returns the integer closest to zero.
Syntax :
public static int floorMod(data_type a, data_type b)
Parameters: The function accepts two parameters.
a: This refers to the dividend value.
b: This refers to the divisor value.The parameters can be of data-type int or long.
The parameters can be of data-type int or long.
Exception: It throws an ArithmeticException if the divisor is zero.
Return Value: This method returns the floor modulus x – (floorDiv(x, y) * y).
Below programs are used to illustrate the working of java.lang.Math.floorMod() method.Program 1:
// Java program to demonstrate working// of java.lang.Math.floorMod() methodimport java.lang.Math;  class Gfg1 {      public static void main(String args[])    {        int a = 25, b = 5;        System.out.println(Math.floorMod(a, b));          // Divisor and dividend is having same sign        int c = 123, d = 50;        System.out.println(Math.floorMod(c, d));          // Divisor is having negative sign        int e = 123, f = -50;        System.out.println(Math.floorMod(e, f));          // Dividend is having negative sign        int g = -123, h = 50;        System.out.println(Math.floorMod(g, h));    }}
0
23
-27
27

Program 2:
// Java program to demonstrate working// of java.lang.Math.floorMod() methodimport java.lang.Math;  class Gfg2 {      public static void main(String args[])    {        int x = 200;        int y = 0;          System.out.println(Math.floorMod(x, y));    }}
Output:
Runtime Error :
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at java.lang.Math.floorDiv(Math.java:1052)
    at java.lang.Math.floorMod(Math.java:1139)
    at Gfg2.main(File.java:13)

Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorMod-int-int-
Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Initialize an ArrayList in Java
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
Singleton Class in Java