code-rag-bench/online-tutorials huggingface dataset:
PHP | defined() function - GeeksforGeeks

23 Aug, 2019
The PHP defined() function is an inbuilt function in PHP which checks whether a constant is exists or not, in other words, defined or not.
Syntax:
bool defined($constant_name);
Parameter: This function accepts a single parameter as mentioned above and described below.
$constant_name: This is required parameter. It specifies the name of the constant.
Return Value: This function returns TRUE if constant exists and FALSE otherwise.
Note: This function is available for PHP 4.0.0 and newer version.
Below examples illustrate the function:
Example 1:
<?phpdefine("constant_key", "value for the constant key");echo defined("constant_key");?>
Output:
1

Example 2: checking with if condition after defining the constant.
<?phpdefine("constant_key", "value for the constant key");if(defined("constant_key")){    echo "constant_key is defined";}else{    echo "constant_key is not defined";}?>
Output:
constant_key is defined

Example 3: checking with if condition without defining the constant.
<?php//define("constant_key", "value for the constant key");if(defined("constant_key")){    echo "constant_key is defined";}else{    echo "constant_key is not defined";}?>
Output:
constant_key is not defined

PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
MATLAB - Vector Dot Product

Dot product of two vectors a = (a1, a2, ..., an) and b = (b1, b2, ..., bn) is given by −
a.b = ∑(ai.bi)
Dot product of two vectors a and b is calculated using the dot function.
dot(a, b);

Create a script file with the following code −
v1 = [2 3 4];
v2 = [1 2 3];
dp = dot(v1, v2);
disp('Dot Product:'); 
disp(dp);
When you run the file, it displays the following result −
Dot Product:
   20


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
How to Save a Plot to a File Using Matplotlib? - GeeksforGeeks

03 Jan, 2021
Matplotlib is a widely used python library to plot graphs, plots, charts, etc.  show() method is used to display graphs as output, but don’t save it in any file. To save generated graphs in a file on storage disk, savefig() method is used.
savefig() : Save the current figure.
Syntax: pyplot.savefig(fname, dpi=None, facecolor=’w’, edgecolor=’w’, orientation=’portrait’, papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None, metadata=None)
Parameters:
fname : path or name of output file with extension. If extension is not provided plot is saved as png file. Supported file formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff.
dpi : dots per inch resolution of figure
facecolor : facecolor of figure
edgecolor :  edgecolor of figure
orientation  : landscape or portrait
format : The file format, e.g. ‘png’, ‘pdf’, ‘svg’, etc.
transparent : If  it is True, the patches of axes will all be transparent
Steps:
Plot a graphUse pyplot.savefig() method to save generated plot in a file
Plot a graph
Use pyplot.savefig() method to save generated plot in a file
Example:
Python3
import matplotlib.pyplot as plt  # Creating datayear = ['2010', '2002', '2004', '2006', '2008']production = [25, 15, 35, 30, 10]  # Plotting barchartplt.bar(year, production)  # Saving the figure.plt.savefig("output.jpg")  # Saving figure by changing parameter valuesplt.savefig("output1", facecolor='y', bbox_inches="tight",            pad_inches=0.3, transparent=True)
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to use the GetValue() method of array class in C#?

The GetValue() method of array class in C# gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
We have set the array values first using the Array.CreateInstance method.
Array arr = Array.CreateInstance(typeof(String), 3, 6);
arr.SetValue("One", 0, 0);
arr.SetValue("Two", 0, 1);
arr.SetValue("Three", 0, 2);
arr.SetValue("Four", 0, 3);
arr.SetValue("Five", 1, 4);
arr.SetValue("Six", 1, 5);
arr.SetValue("Seven", 1, 2);
arr.SetValue("Eight", 1, 3);
Then loop throught the array length. This will display all the values using the GetValue() method.
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
Console.WriteLine( arr.GetValue(i, j));
 Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         Array arr = Array.CreateInstance(typeof(String), 3, 6);
         arr.SetValue("One", 0, 0);
         arr.SetValue("Two", 0, 1);
         arr.SetValue("Three", 0, 2);
         arr.SetValue("Four", 0, 3);
         arr.SetValue("Five", 1, 4);
         arr.SetValue("Six", 1, 5);
         arr.SetValue("Seven", 1, 2);
         arr.SetValue("Eight", 1, 3);
         int a = arr.GetLength(0);
         int b = arr.GetLength(1);
         // Getting values
         for (int i = 0; i <a; i++)
         for (int j = 0; j < b; j++)
         Console.WriteLine( arr.GetValue(i, j));
         Console.ReadLine();
      }
   }
}
One
Two
Three
Four

Seven
Eight
Five
Six
Sum of cubes of even and odd natural numbers - GeeksforGeeks

09 Oct, 2018
We know that sum of cubes of first n natural numbers is = (n(n+1)/2)2.
Sum of cube of first n even natural numbers23 + 43 + 63 + ......... + (2n)3
Even Sum = 23 + 43 + 63 + .... + (2n)3
        if we multiply by 23 then 
        = 23 x (13 + 23 + 32 + .... + (n)3)
        = 23 + 43 + 63 + ......... + (2n)3
        =  23 (n(n+1)/2)2
        =  8(n(n+1))2/4
        =  2(n(n+1))2

Example :
Sum of cube of first 4 even numbers = 23 + 43 + 63 + 83 
 put n = 4     = 2(n(n+1))2
               = 2*(4*(4+1))2
               = 2(4*5)2
               = 2(20)2
               = 800
 8 + 64 + 256 + 512 = 800

Program for Sum of cubes of first n even numbers
 Sum of cube of first n odd natural numbersWe need to compute 13 + 33 + 53 + .... + (2n-1)3
OddSum   = (Sum of cubes of all 2n numbers) - (Sum of cubes of first n even numbers)
         =  (2n(2n+1)/2)2 - 2(n(n+1))2 
         =  n2(2n+1)2 - 2* n2(n+1)2
         =  n2[(2n+1)2 - 2*(n+1)2]
         =  n2[4n2 + 1 + 4n - 2n2 - 2 - 4n]
         =  n2(2n2 - 1)

Example :
Sum of cube of first 4 odd numbers = 13 + 33 + 53 + 73 
 put n = 4     = n2(2n2 - 1)
               = 42(2*(4)2 - 1)
               = 16(32-1)
               =  496
 1 + 27 + 125 + 343 = 496

Program for Sum of cubes of first n odd numbers
maths-cube
series
series-sum
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Operators in C / C++
Sieve of Eratosthenes
Euclidean algorithms (Basic and Extended)
Algorithm to solve Rubik's Cube
How to use “OR” condition in MySQL CASE expression?


Set the same condition like “OR” in a MySQL CASE expression. Let us first create a sample table.
Following is the query
mysql> create table caseOrConditionDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100),
   -> Score int
   -> );
Query OK, 0 rows affected (0.49 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into caseOrConditionDemo(Name,Score) values('Larry',85);
Query OK, 1 row affected (0.18 sec)

mysql> insert into caseOrConditionDemo(Name,Score) values('Sam',74);
Query OK, 1 row affected (0.20 sec)

mysql> insert into caseOrConditionDemo(Name,Score) values('Mike',76);
Query OK, 1 row affected (0.16 sec)

mysql> insert into caseOrConditionDemo(Name,Score) values('Carol',65);
Query OK, 1 row affected (0.20 sec)
Following is the query to display records from the table using select command:
mysql> select *from caseOrConditionDemo;
This will produce the following output
+----+-------+-------+
| Id | Name  | Score |
+----+-------+-------+
| 1  | Larry | 85    |
| 2  | Sam   | 74    |
| 3  | Mike  | 76    |
| 4  | Carol | 65    |
+----+-------+-------+
4 rows in set (0.00 sec)
Following is the query to use a condition like “OR” in MySQL CASE expression:
mysql> select Id,Name,Score,
   -> case when Score > 75 then 'Better Score'
   -> when Score > 70 then 'Good Score'
   -> else 'Not Good Score'
   -> end as 'Performance'
   -> from caseOrConditionDemo;
This will produce the following output
+----+-------+-------+----------------+
| Id | Name  | Score | Performance    |
+----+-------+-------+----------------+
| 1  | Larry | 85    | Better Score   |
| 2  | Sam   | 74    | Good Score     |
| 3  | Mike  | 76    | Better Score   |
| 4  | Carol | 65    | Not Good Score |
+----+-------+-------+----------------+
4 rows in set (0.04 sec)
How to stop a function during its execution in JavaScript?

To stop a function during its execution, use the concept of −
document.getElementById().addEventListener().
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=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>
</head>
<body>
<button type="button" id="call">Call the function</button>
<button type="button" id="halt">Stop the function execution </button>
<script>
   document.getElementById("call").addEventListener("click", callFunction);
   document.getElementById("halt").addEventListener("click", haltFunction);
   var timeValue = null;
   function callFunction() {
      timeValue = setInterval(function() {
         console.log("The call() is being executed....");
      }, 1000);
   }
   function haltFunction() {
      clearInterval(timeValue);
   }
</script>
</body>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.
When you click Call the function button, it will execute the function. To stop the function, click Stop the function execution button.
The snapshot is as follows −
Tk - Label Widget

A label widget is a common widget used in almost all Tk applications that is used to display simple text. The syntax for label widget is shown below −
label labelName options

The options available for the label widget are listed below in table −
-background color
Used to set background color for widget.
-borderwidth width
Used to draw with border in 3D effects.
-font fontDescriptor
Used to set font for widget.
-foreground color
Used to set foreground color for widget.
-height number
Used to set height for widget.
-padx number
Sets the padx for the widget.
-pady number
Sets the pady for the widget.
-relief condition
Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or groove.
-text text
Sets the text for the widget.
-textvariable varName
Variable associated with the widget. When the text of widget changes, the variable is set to text of widget.
-width number
Sets the width for widget.
-justify alignment
Sets the alignment of text, which can be left, center, or right.
A simple example for label widget is shown below −
#!/usr/bin/wish

grid [label .myLabel -background red -foreground white -text "Hello World" -relief ridge
   -borderwidth 8 -padx 10 -pady 10 -font {Helvetica -18 bold} -height 10 -width 35 
   -textvariable myvariable -justify left -underline 1]
set myvariable "Test Hello"
When we run the above program, we will get the following output −
 Print
 Add Notes
 Bookmark this page
Java â String getBytes() Method

This method encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
Here is the syntax of this method −
public byte[] getBytes()

This method returns the resultant byte array.
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str1 = new String("Welcome to Tutorialspoint.com");
      
      try {
         String Str2 = new String( Str1.getBytes( "UTF-8" ));
         System.out.println("Returned Value " + Str2 );
         Str2 = new String (Str1.getBytes( "ISO-8859-1" ));
         System.out.println("Returned Value " + Str2 );
      } catch ( UnsupportedEncodingException e) {
         System.out.println("Unsupported character set");
      }
   }
}
This will produce the following result −
Returned Value Welcome to Tutorialspoint.com
Returned Value Welcome to Tutorialspoint.com


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to add/insert additional property to JSON string using Gson in Java?


The com.google.gson.JSonElement class represents an element of Json. We can use the toJsonTree() method of Gson class to serialize an object's representation as a tree of JsonElements. We can add/ insert an additional property to JSON string by using the getAsJsonObject() method of JSonElement. This method returns to get the element as JsonObject.
public JsonObject getAsJsonObject()
import com.google.gson.*;
public class AddPropertyGsonTest {
   public static void main(String[] args) {
      Gson gson = new GsonBuilder().setPrettyPrinting().create(); // pretty print JSON
      Student student = new Student("Adithya");
      String jsonStr = gson.toJson(student, Student.class);
      System.out.println("JSON String: \n" + jsonStr);
      JsonElement jsonElement = gson.toJsonTree(student);
      jsonElement.getAsJsonObject().addProperty("id", "115");
      jsonStr = gson.toJson(jsonElement);
      System.out.println("JSON String after inserting additional property: \n" + jsonStr);
   }
}
// Student class
class Student {
   private String name;
   public Student(String name) {
      this.name= name;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
JSON String:
{
   "name": "Adithya"
}
JSON String after inserting additional property:
{
   "name": "Adithya",
   "id": "115"
}
Perl | oct() Function - GeeksforGeeks

25 Jun, 2019
oct() function in Perl converts the octal value passed to its respective decimal value. For example, oct(‘1015’) will return ‘525’. This function returns the resultant decimal value in the form of a string which can be used as a number because Perl automatically converts a string to a number in numeric contexts. If the passed parameter is not an octal number then the result will be 0.
Syntax: oct(oct_value)
Parameter:oct_value: Octal number which is to be converted to decimal
Returns:the octal value converted to decimal value
Example 1:
#!/usr/bin/perl -w  # Converting and printing # the decimal valueprint("oct(31) ", oct('31'), "\n");print("oct(50) ", oct('50'), "\n");
oct(31) 25
oct(50) 40

Example 2:
#!/usr/bin/perl -w  # Converting and printing # the decimal valueprint("oct(106) ", oct('106'), "\n");print("oct(125) ", oct('125'), "\n");
oct(106) 70
oct(125) 85

Perl-function
Perl-Math-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl | Data Types
Perl Tutorial - Learn Perl With Examples
Perl | Multidimensional Hashes
Perl | Writing to a File
Perl | File Handling Introduction
Perl | Basic Syntax of a Perl Program
Perl | Appending to a File
Perl | Operators | Set - 1
Perl | index() Function
Perl | Scope of Variables
How to create a directory in project folder using Java?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
The mkdir() method of this class creates a directory with the path represented by the current object.
Therefore, to create a directory −
Instantiate the File class by passing the path of the directory you need to create, as a parameter (String).
Instantiate the File class by passing the path of the directory you need to create, as a parameter (String).
Invoke the mkdir() method using the above-created file object.
Invoke the mkdir() method using the above-created file object.
The following Java example reads the path and name of the directory to be created, from the user, and creates it.
 Live Demo
import java.io.File;
import java.util.Scanner;
public class CreateDirectory {
   public static void main(String args[]) {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String path = sc.next();
      System.out.println("Enter the name of the desired a directory: ");
      path = path+sc.next();
      //Creating a File object
      File file = new File(path);
      //Creating the directory
      boolean bool = file.mkdir();
      if(bool){
         System.out.println("Directory created successfully");
      } else {
         System.out.println("Sorry couldn’t create specified directory");
      }
   }
}
Enter the path to create a directory:
D:\
Enter the name of the desired a directory:
sample_directory
Directory created successfully
If you verify, you can observe see the created directory as −
But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory.
For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as −
D:\test\myDirectories\sample_directory
Where the test and myDirectories folders don’t exist, the mkdir() method will not create it.
Calculating the LCM of multiple numbers in JavaScript

We are required to write a JavaScript function that takes in an array of numbers of any length and returns their LCM.
We will approach this problem in parts −
Part 1 − We will create a helper function to calculate the Greatest Common Divisor (GCD) of two numbers
Part 2 − Then using Part 1 helper function we will create another helper function to calculate the Least Common Multiple (LCM) of two numbers.
Part 3 − Finally, using Part 2 helper function we will create a function that loops over the array and calculates the array LCM.
The code for this will be −
const calculateLCM = (...arr) => {
   const gcd2 = (a, b) => {
      // Greatest common divisor of 2 integers
      if(!b) return b===0 ? a : NaN;
         return gcd2(b, a%b);
   };
   const lcm2 = (a, b) => {
      // Least common multiple of 2 integers
      return a * b / gcd2(a, b);
   }
   // Least common multiple of a list of integers
   let n = 1;
   for(let i = 0; i < arr.length; ++i){
      n = lcm2(arr[i], n);
   }
   return n;
};
console.log(calculateLCM(12, 18, 7, 15, 20, 24, 28));
And the output in the console will be −
2520
Passing Multiple ids to single parameter in MySQL?

To pass multiple ids to single parameter, use FIND_IN_SET(). Let us first create a table −
mysql> create table  DemoTable1817
     (
     EmployeeName varchar(20),
     CountryName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1817 values('Chris','AUS');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1817 values('David','UK');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1817 values('Bob','US');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1817;
This will produce the following output −
+--------------+-------------+
| EmployeeName | CountryName |
+--------------+-------------+
| Chris        |          AUS|
| David        |          UK |
| Bob          |          US |
+--------------+-------------+
3 rows in set (0.00 sec)
Here is the query to pass multiple ids to single parameter in MySQL.
mysql> select * from DemoTable1817
     where find_in_set(CountryName,'US,UK');
This will produce the following output −
+--------------+-------------+
| EmployeeName | CountryName |
+--------------+-------------+
| David        |          UK |
| Bob          |          US |
+--------------+-------------+
2 rows in set (0.00 sec)
How to change JFrame background color in Java

At first, create a JFrame −
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(550, 300));
Now, change the background color of the JFrame −
frame.getContentPane().setBackground(Color.BLUE);
The following is an example to change JFrame background color −
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setPreferredSize(new Dimension(550, 300));
      frame.getContentPane().setBackground(Color.BLUE);
      frame.pack();
      frame.setVisible(true);
   }
}
Isolation Forest and Pyspark part 2 | by Maria Karanasou | Towards Data Science

So, after a few runs with the PySpark ml implementation of Isolation Forest presented here, I stumbled upon a couple of things and I thought I’d write about them so that you don’t waste the time I wasted troubleshooting.
In the previous article, I used VectorAssembler to gather the feature vectors. It so happened that the test data I had, created only DenseVectors, but when I tried the example on a different dataset, I realized that:
VectorAssembler can create both Dense and Sparse vectors in the same dataframe (which is smart and other spark ml argorithms can leverage it and work with it)
Isolation Forest (or at least the implementation found here ) does not support the above, so the input must be DenseVectors only.
To demonstrate the issue:
The current workaround is to transform all vectors to dense, using a udf unfortunately.
Set the approxQuantileRelativeError or the threshold parameter for large datasets
If you are planning on training on a big dataset, e.g. more than 10M rows, even if you set parameters like maxSamples and maxFeatures to decrease the dimensions, you need to set the approxQuantileRelativeError parameter to something reasonable, e.g. 0.2. The reason is that the approxQuantile function is a very expensive function to use, especially if we expect the approxQuantileRelativeError to be 0. (which is the default value). Doing this, drastically cut the training time and the OOM and executor communication issues, and, up to now, I haven’t seen any decline in prediction accuracy.
From the comments of the implementation:
* The proportion of outliers in the data set (0< contamination < 1).* It will be used in the prediction. In order to enhance performance,* Our method to get anomaly score threshold adopts DataFrameStsFunctions.approxQuantile,* which is designed for performance with some extent accuracy loss.* Set the param approxQuantileRelativeError (0 < e < 1) to calculate* an approximate quantile threshold of anomaly scores for large dataset.
Alternatively, set the threshold beforehand in fit and avoid the approxQuantile calculation like this:
model = iforest.fit(df, {'threshold': 0.5})print(model.getThreshold())> 0.49272560194039505
Hope this helps and saves you some time :) Let me know if you have any suggestions, corrections or ideas.
towardsdatascience.com
Understanding your model’s predictions:
Python | Split a sentence into list of words

01 Sep, 2021
Given a Sentence, write a Python program to convert the given sentence into list of words. 
Examples: 
Input : ['Hello World']
Output : ['Hello', 'world']

Input : ['Geeks For geeks']
Output : ['Geeks', 'for', 'geeks']
The simplest approach provided by Python to convert the given list of Sentence into words with separate indices is to use split() method. This method split a string into a list where each word is a list item. We have alternative ways to use this function in order to achieve the required output.
Method #1 : Splitting the first index element 
Python3
# Python3 program to Convert single# indexed list into multiple indexed list def convert(lst):    return (lst[0].split()) # Driver codelst =  ["Geeks For geeks"]print( convert(lst))
['Geeks', 'For', 'geeks']
 
Method #2 : Using for loop We can also use a for loop to split the first element. This method is also beneficial if we have more than one element.  
Python3
# Python3 program to Convert single# indexed list into multiple indexed list def convert(lst):    return ([i for item in lst for i in item.split()])     # Driver codelst =  ['Geeksforgeeks is a portal for geeks']print( convert(lst))
['Geeksforgeeks', 'is', 'a', 'portal', 'for', 'geeks']
 
Method #3 : Using join() We can split the given list and than join using join() function. We can also use this when you have a list of string or single string inside a list.  
Python3
# Python3 program to Convert single# indexed list into multiple indexed list def convert(lst):    return ' '.join(lst).split()      # Driver codelst =  ['Hello Geeks for geeks']print( convert(lst))
['Hello', 'Geeks', 'for', 'geeks']
 
varshagumber28
akshaysingh98088
Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python – Append Similar Values as Key

08 May, 2020
Sometimes, while working with data, we can have problems in which we need to categorize a particular list and values to similar keys. This can be problem in counting data. Like counting votes or counting coins. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute way in which this task can be performed. In this, we run a loop to add values to dictionary value list, if not present we dynamically create key and perform append.
# Python3 code to demonstrate working of # Append Similar Values as Key# Using loop  # initializing listtest_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',             'Manjeet', 'Akash', 'Akshat', 'Manjeet']  # printing original listprint("The original list is : " + str(test_list))  # Append Similar Values as Key# Using loopres = dict()for ele in test_list:    try:        res[ele].append(ele)    except KeyError:        res[ele] = [ele]  # printing result print("The similar values dictionary is : " + str(res)) 
The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]}
 
Method #2 : Using defaultdict() + loopThe combination of above functions can be used to solve this problem. In this, we pre initialize the dictionary using defaultdict().
# Python3 code to demonstrate working of # Append Similar Values as Key# Using defaultdict() + loopfrom collections import defaultdict  # initializing listtest_list = ['Manjeet', 'Nikhil', 'Akshat', 'Akash',          'Manjeet', 'Akash', 'Akshat', 'Manjeet']  # printing original listprint("The original list is : " + str(test_list))  # Append Similar Values as Key# Using defaultdict() + loopres = defaultdict(list)for sub in test_list:    res[sub].append(sub)  # printing result print("The similar values dictionary is : " + str(dict(res))) 
The original list is : [‘Manjeet’, ‘Nikhil’, ‘Akshat’, ‘Akash’, ‘Manjeet’, ‘Akash’, ‘Akshat’, ‘Manjeet’]The similar values dictionary is : {‘Nikhil’: [‘Nikhil’], ‘Manjeet’: [‘Manjeet’, ‘Manjeet’, ‘Manjeet’], ‘Akash’: [‘Akash’, ‘Akash’], ‘Akshat’: [‘Akshat’, ‘Akshat’]}
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
JavaScript | exec() Method

12 Apr, 2021
The exec() Method in JavaScript is used to test for match in a string. If there is a match this method returns the first match else it returns NULL.Syntax:  
RegExpObject.exec(str)
Where str is the string to be searched. This is required field. Example-1: This example searches for the string “computer” in the original string.  
html
<!DOCTYPE html><html> <body style="text-align:center">    <h1 style="color:green">      GeeksforGeeks  </h1>    <h2>exec() Method</h2>     <p>      String: GeeksforGeeks is the      computer science portal for geeks.  </p>     <button onclick="geek()">      Click it!  </button>    <p id="app"></p>     <script>        function geek() {            var str =                "GeeksforGeeks is the "+                "computer science portal for geeks.";                       var regex = new RegExp("computer", );            // match "computer" in string.                                  var rex = regex.exec(str);            document.getElementById("app").innerHTML =                " Found " + rex.length + " match: " + rex;        }    </script></body> </html>
Output: Before clicking the button:  
After clicking the button:  
Example-2: This example searches for the string “rep” in the original string.  
html
<!DOCTYPE html><html> <body style="text-align:center">    <h1 style="color:green">      GeeksforGeeks  </h1>    <h2>      exec() Method  </h2>     <p>      String: GeeksforGeeks      is the computer science      portal for geeks.  </p>     <button onclick="geek()">      Click it!  </button>    <p id="app"></p>     <script>        function geek() {            var str =                "GeeksforGeeks is the"+                " computer science "+                "portal for geeks.";            var regex = new RegExp("rep");                       // Match "rep" in string.            var rex = regex.exec(str);            alert(rex);        }    </script></body> </html>
Output: Before clicking the button:  
After clicking the button:  
Supported Browsers: The browsers supported by JavaScript exec() Method are listed below:  
Google Chrome
Apple Safari
Mozilla Firefox
Opera
Internet Explorer
 
simranarora5sos
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Filter Tuple Dictionary Keys

30 Jan, 2020
Sometimes, while working with Python dictionaries, we can have it’s keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functionalities to achieve this. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionIn this method, we just iterate through the each dictionary item and get it’s filtered key’s elements into a list.
# Python3 code to demonstrate working of# Filter Tuple Dictionary Keys# Using list comprehension  # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}  # printing original dictprint("The original dict is : " + str(test_dict))  # Initializing K K = 5  # Filter Tuple Dictionary Keys# Using list comprehensionres = [ele for key in test_dict for ele in key if ele > K]  # printing resultprint("The filtered dictionary tuple key elements are : " + str(res))
The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The filtered dictionary tuple key elements are : [6, 9, 10, 8]

 
Method #2 : Using chain.from_iterable()This task can be performed in more compact form, using one word instead of one-line by using from_iterable(), which internally accesses the tuple elements and stores in list and then perform the filter operation.
# Python3 code to demonstrate working of# Filter Tuple Dictionary Keys# Using chain.from_iterable()from itertools import chain  # Initializing dicttest_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}  # printing original dictprint("The original dict is : " + str(test_dict))  # Initializing K K = 5  # Filter Tuple Dictionary Keys# Using chain.from_iterable()temp = list(chain.from_iterable(test_dict))res = [ele for ele in temp if ele > K]   # printing resultprint("The filtered dictionary tuple key elements are : " + str(res))
The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The filtered dictionary tuple key elements are : [6, 9, 10, 8]

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 | Convert string dictionary to dictionary
Find out when a download has completed using Python & Selenium

We can find when a download has completed with Selenium webdriver in Python. We shall use the ChromeOptions class for this purpose. First, we shall create an object of the ChromeOptions class.
Then apply the add_experimental_option method on the object created. We shall pass browser preferences and download.default_directory:<location of
downloaded file> as parameters to that method. Finally, this information shall be passed to the driver object.
Once the download is completed, we can verify it with the help of the os.path.isfile method. The path of the downloaded file is passed as a parameter to that method. The method os.path.exists shall also be used to verify if the downloaded file path exists.
op = webdriver.ChromeOptions()
p = {'download.default_directory':'C:\\Users\\Downloads\\Test'}
op.add_experimental_option('prefs', p)
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import os.path
#object of ChromeOptions class
op = webdriver.ChromeOptions()
#browser preferences
p = {'download.default_directory': 'C:\\Users\\Downloads\\Test'}
#add options to browser
op.add_experimental_option('prefs', p)
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe",
options=op)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.seleniumhq.org/download/");
#click download link
l = driver.find_element_by_link_text("32 bit Windows IE")
l.click()
#check if file downloaded file path exists
while not os.path.exists('C:\\Users\\Downloads\\Test'):
time.sleep(2)
#check file
if os.path.isfile('C:\\Users\\Downloads\\Test\\IEDriverServer_Win32.zip):
   print("File download is completed")
else:
   print("File download is not completed")
#close browser
driver.quit()
Python | Split given string into equal halves

03 Jul, 2019
Sometimes, we need to simply divide the string into two equal halves. This type of application can occur in various domain ranging from simple programming to web development. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + String slicingThis is the naive method to perform this particular task. In this we just use brute divisions and slicing to separate first and last part of string.
# Python3 code to demonstrate working of# Splitting string into equal halves# Using list comprehension + string slicing  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + test_str)  # Using list comprehension + string slicing# Splitting string into equal halvesres_first = test_str[0:len(test_str)//2]res_second = test_str[len(test_str)//2 if len(test_str)%2 == 0                                 else ((len(test_str)//2)+1):]  # printing result print("The first part of string : " + res_first)print("The second part of string : " + res_second)
The original string is : GeeksforGeeks
The first part of string : Geeksf
The second part of string : rGeeks

 
Method #2 : Using string slicingTo overcome the shortcomings of above method and find a more elegant solution, we use string slicing to perform this particular task.
# Python3 code to demonstrate working of# Splitting string into equal halves# Using string slicing  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + test_str)  # Using string slicing# Splitting string into equal halvesres_first, res_second = test_str[:len(test_str)//2],                         test_str[len(test_str)//2:]  # printing result print("The first part of string : " + res_first)print("The second part of string : " + res_second)
The original string is : GeeksforGeeks
The first part of string : Geeksf
The second part of string : orGeeks

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Tutorial

JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
This tutorial will teach you JavaScript from basic to advanced.
With our "Try it Yourself" editor, you can edit the source code and view 
the result.

Try it Yourself »

We recommend reading this tutorial, in the sequence listed in the menu.
If you have a large screen, the menu will always be present on the left.
If you have a small screen, open the menu by clicking the top menu sign ☰.
Examples are better than 1000 words. Examples are often easier to understand 
than text explanations.
This tutorial supplements all explanations with clarifying "Try it Yourself" examples.
If you try all the examples, you will learn a lot about JavaScript, in a very short time!
JavaScript is one of the 3 languages all web developers 
must 
learn:
   1. HTML to define the content of web pages
   2. CSS to specify the layout of web pages
   3. JavaScript to program the behavior of web pages 
This tutorial covers every version of JavaScript:
The Original JavaScript ES1 ES2 ES3 (1997-1999)
The First Main Revision ES5 (2009)
The Second Revision ES6 (2015)
The Yearly Additions (2016, 2017, 2018)
In this tutorial, the learning speed is your choice.
Everything is up to you.
If you are struggling, take a break, or re-read the material.
Always make sure you understand all the "Try-it-Yourself" 
examples.
The only way to become a clever programmer is to:
Practice. Practice. Practice. Code. Code. Code !
Create a variable called carName and assign the value Volvo to it.
var  = "";

Start the Exercise
How do I get JavaScript?
Where can I download JavaScript?
Is JavaScript Free?
You don't have to get or download JavaScript.
JavaScript is already running in your browser on your computer,
on your tablet, and on your smart-phone.
JavaScript is free to use for everyone.
W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.
The reference contains examples for all properties, methods and events, and 
is continuously updated according to the latest web standards.
Test your JavaScript skills at W3Schools!
Start JavaScript Quiz!
Get certified by completing the JavaScript course
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 extract data frame columns stored in a list in R?

Suppose we have two frames each having 5 columns that are stored in a list in R and the data that belongs to same columns has some kind of inherent relationship or we want to check whether there exists a relationship between them then we might want to extract those columns. Therefore, we can use lapply function for this extraction. For example, if we have a list called LIST that store two data frames then column 3 of each data frame can be extracted by using the command lapply(LIST,"[",3).
Consider the below data frames and list of these data frames −
 Live Demo
df1<-data.frame(x1=rnorm(20),x2=rnorm(20))
df2<-data.frame(y1=rnorm(20),y2=rnorm(20))
List<-list(df1,df2)
List
[[1]]
    x1            x2
1  -0.2616691   0.4838822161
2  -0.4962192  -0.2029131423
3  -0.6289051   0.6067368122
4  -1.8650979  -0.2673970799
5  -0.1144585   1.2794435497
6  -0.7950920   0.3237400683
7  -0.7473936   0.5272240477
8  -1.1275262   0.8650962534
9  -0.2354747   1.0057184299
10  1.3755067   0.0961681148
11 -0.1747653   1.2535584458
12 -1.5245065   1.0977974301
13 -1.9052953  -0.6178104611
14  0.6634748   0.3078744775
15 -0.3464213  -0.9288219551
16 -1.7638077  -1.3873331806
17 -0.6839449  -0.0006287789
18 -0.1494119   0.1155562131
19 -0.3583126   0.2606700288
20 -0.6148202  -0.5952164804
[[2]]
      y1            y2
1   -0.211831075   0.80770142
2   0.275355837  -0.37532157
3   0.026130608   0.07003241
4  -0.214784788   0.36447807
5  -0.706518246  -2.35280957
6  -0.786380214  -0.83800239
7   0.599793658   1.00900869
8  -0.952037717   0.31360048
9  -0.820999108   1.37718684
10 -1.912105297  -0.48305776
11  0.436298130   0.56800539
12  1.126854489   0.26761877
13 -2.148552234  -1.54496557
14  1.832004140  -0.93939487
15 -0.587988585   0.74063570
16  0.945827064  -0.30905531
17 -1.571678758  -0.44346002
18 -0.704557448  -0.78744069
19 -0.009306419   0.71375917
20  0.734797879  -1.88248741
Extracting column 2 from each data frame stored in List −
lapply(List,"[",2)
[[1]]
       x2
1   0.4838822161
2  -0.2029131423
3   0.6067368122
4  -0.2673970799
5   1.2794435497
6   0.3237400683
7   0.5272240477
8   0.8650962534
9   1.0057184299
10  0.0961681148
11  1.2535584458
12  1.0977974301
13 -0.6178104611
14  0.3078744775
15 -0.9288219551
16 -1.3873331806
17 -0.0006287789
18  0.1155562131
19  0.2606700288
20 -0.5952164804
[[2]]
     y2
1   0.80770142
2  -0.37532157
3   0.07003241
4   0.36447807
5  -2.35280957
6  -0.83800239
7   1.00900869
8   0.31360048
9   1.37718684
10 -0.48305776
11  0.56800539
12  0.26761877
13 -1.54496557
14 -0.93939487
15  0.74063570
16 -0.30905531
17 -0.44346002
18 -0.78744069
19  0.71375917
20 -1.88248741
How to add a margin to a tkinter window?

The margin of a tkinter window can be controlled by specifying the value of fill, expand and padding. Another way to set the margin of a tkinter window is to use grid(**options) Geometry Manager. Grid pack manager allows us to add the margin by specifying the value of row and column property.
# Import the required library
from tkinter import *
from tkinter import ttk

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

# Set the size of the Tkinter window
win.geometry("700x350")

# Add a frame to set the size of the window
frame= Frame(win, relief= 'sunken', bg= "black")
frame.pack(fill= BOTH, expand= True, padx= 10, pady=20)

# Add a label widget
label= Label(frame, text= "Welcome to Tutorialspoint",
font=('Helvetica 15 bold'), bg= "white")
label.pack(pady= 30)

win.mainloop()
Executing the above code will display a Label Text lying inside a frame. The margin of the frame is expandable and resizable.
Ethical Hacking - Enumeration

Enumeration belongs to the first phase of Ethical Hacking, i.e., “Information Gathering”. This is a process where the attacker establishes an active connection with the victim and try to discover as much attack vectors as possible, which can be used to exploit the systems further.
Enumeration can be used to gain information on −
Network shares
SNMP data, if they are not secured properly
IP tables
Usernames of different systems
Passwords policies lists
Enumerations depend on the services that the systems offer. They can be −
DNS enumeration
NTP enumeration
SNMP enumeration
Linux/Windows enumeration
SMB enumeration
Let us now discuss some of the tools that are widely used for Enumeration.
NTP Suite is used for NTP enumeration. This is important because in a network environment, you can find other primary servers that help the hosts to update their times and you can do it without authenticating the system.
Take a look at the following example.
ntpdate 192.168.1.100 01 Sept 12:50:49 ntpdate[627]: 
adjust time server 192.168.1.100 offset 0.005030 sec 

or 
ntpdc [-ilnps] [-c command] [hostname/IP_address] 
  
root@test]# ntpdc -c sysinfo 192.168.1.100 
***Warning changing to older implementation 
***Warning changing the request packet size from 160 to 48 
system peer: 192.168.1.101 

system peer mode: client
leap indicator: 00 
stratum: 5  

precision: -15 
root distance: 0.00107 s 
root dispersion: 0.02306 s 
reference ID: [192.168.1.101] 
reference time: f66s4f45.f633e130, Sept 01 2016 22:06:23.458 
system flags: monitor ntp stats calibrate 
jitter: 0.000000 s 
stability: 4.256 ppm 
broadcastdelay: 0.003875 s 
authdelay: 0.000107 s

enum4linux is used to enumerate Linux systems. Take a look at the following screenshot and observe how we have found the usernames present in a target host.
smtp-user-enum tries to guess usernames by using SMTP service. Take a look at the following screenshot to understand how it does so.
It is recommended to disable all services that you don’t use. It reduces the possibilities of OS enumeration of the services that your systems are running.

    36 Lectures 
     5 hours 

 Sharad Kumar

    31 Lectures 
     3.5 hours 

 Abhilash Nelson

    22 Lectures 
     3 hours 

 Blair Cook

    74 Lectures 
     4.5 hours 

 199courses

    75 Lectures 
     4.5 hours 

 199courses

    148 Lectures 
     28.5 hours 

 Joseph Delgadillo
 Print
 Add Notes
 Bookmark this page