code-rag-bench/online-tutorials huggingface dataset:
Lodash _.reverse() Function - GeeksforGeeks

29 Jul, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.The _.reverse() is used to reverse the array. This function changes the original array and also returns a new array.
Syntax: 
_.reverse( array )
Parameters: This function accepts single parameter array that holds the array of elements.
Return Value: It returns the reversed array.
Note: Please install lodash module by using npm install lodash before using the below given code.
Example 1: This examples shows that this function effect the original array.
javascript
// Requiring the lodash libraryconst _ = require("lodash");  // Original arraylet array1 = [1, 2, 3, 4]  // Printing original Arrayconsole.log("original Array1: ", array1)  // Using _.reverse() methodlet reversedArray = _.reverse(array1);  // Printing the reversedArrayconsole.log("reversed Array: ", reversedArray)  // Printing original Arrayconsole.log("original Array1: ", array1)
Output: 
Example 2: In this example, we will take an array of objects and reverse them.
javascript
// Requiring the lodash libraryconst _ = require("lodash");  // Original arraylet array1 = [    { "a": 1 },     { "a": 2, "b": 3 },     { "c": 3 }]  // Printing original Arrayconsole.log("original Array1: ", array1)  // Using _.reverse() methodlet reversedArray = _.reverse(array1);  // Printing the reversedArrayconsole.log("reversed Array: ", reversedArray)  // Printing original Arrayconsole.log("original Array1: ", array1)
Output: 
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to Run Javascript from Python ? - GeeksforGeeks

28 Jul, 2021
In this article, we’ll discuss how to run a javascript file with Python. For this, we’ll use the JS2PY(Javascript Runtime in Pure Python) Python module. JS2PY works by translating JavaScript directly into Python. It indicates that you may run JS directly from Python code without installing large external engines like V8.
To use the module it first has to be installed into the system, since it is not built-in.
Syntax:
pip install js2py
To use the module it has to be imported.
Syntax:
import js2py
Now to covert javascript to python, the javascript command is stored as a string in some variable. We’ll now use the eval_js() function of the module js2py, and pass the javascript code to it.
eval_js() function is defined under the js2py module, which is used to evaluate javascript code, Pass the Javascript code as a parameter in the eval_js module.
Syntax:
js2py.eval_js(javascript code)
Example: Running a simple JS command in Python 
Python3
import js2py  code_2 = "function f(x) {return x+x;}"res_2 = js2py.eval_js(code_2)  print(res_2(5))
Output: 
10
Now let us look at how a JS file is interpreted in Python. For this first *.js file is translated to *.py file
The js2py module provides one way for converting JS code to Python code we must use the translate_file() function for this. After the translation, we will import the Python file and provide something to the function declared within the javascript file.
translate_file() function accepts two arguments: a Javascript file and a Python file, finally it converts the Javascript file to a Python file.
Syntax:
js2py.translate_file(Javascript File, Python File)
Example:  Running a JS file using Python
Javascript File:
Javascript
function wish(name) {    console.log("Hello, "+name+"!")}
Python File: 
Python3
import js2pyfrom temp import *  js2py.translate_file("hey.js", "temp.py")temp.wish("GeeksforGeeks")
Output: 
Hello GeeksforGeeks
We can also run JS without explicitly translating it. for this *.js is loaded into a variable through run_file() function.
run_file(): It is defined under the js2py module, which is used to run the Javascript file. It takes a Javascript file as an argument.
Syntax: 
js2py.run_file(Javascript File)
Example: Running JS in Python
Python3
import js2py  eval_res, tempfile = js2py.run_file("hey.js")tempfile.wish("GeeksforGeeks")
Output:
Hello GeeksforGeeks
python-modules
python-utility
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?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Node.js HTTP Module

08 Oct, 2021
To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client.
Syntax:
var http = require('http');
We can create a HTTP server with the help of http.createServer() method.
Example 1:Filename: max.js
var http = require('http');   // Create a serverhttp.createServer((request, response)=>{       // Sends a chunk of the response body    response.write('Hello World!');       // Signals the server that all of    // the response headers and body     // have been sent  response.end();}).listen(3000); // Server listening on port 3000
Step to run this program: Run this max.js file using the below command:
node max.js
Output:
To make requests via the HTTP module http.request() method is used.
Syntax:
http.request(options[, callback])
Example 2:Filename: max.js
var http = require('http');  var options = {    host: 'www.geeksforgeeks.org',    path: '/courses',    method: 'GET'};  // Making a get request to // 'www.geeksforgeeks.org'http.request(options, (response) => {      // Printing the statusCode    console.log(`STATUS: ${response.statusCode}`);}).end();
Step to run this program: Run this max.js file using the below command:
node max.js
Output:
Node.js-Basics
Picked
Node.js
Web Technologies
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 ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in 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
Output of the Program | Pointer to a Constant or Constant Pointer?

21 Jun, 2022
Predict the output of the below program. 
C++
C
#include <iostream>using namespace std; int main(){    int x = 5;    int * const ptr = &x;    ++(*ptr);       cout << x;    return 0;} // This code is contributed by sarajadhav12052009
#include <stdio.h> int main(){    int x = 5;    int * const ptr = &x;    ++(*ptr);    printf("%d", x);            getchar();    return 0;  }
6
Explanation: See following declarations to know the difference between constant pointer and a pointer to a constant. int * const ptr —> ptr is constant pointer. You can change the value at the location pointed by pointer p, but you can not change p to point to other location.int const * ptr —> ptr is a pointer to a constant. You can change ptr to point other variable. But you cannot change the value pointed by ptr.Therefore above program works well because we have a constant pointer and we are not changing ptr to point to any other location. We are only incrementing value pointed by ptr.Try below program, you will get compiler error.  
C++
C
#include <iostream>using namespace std; int main(){    int x = 5;       int const * ptr = &x;    ++(*ptr);       cout << x;     return 0;} // This code is contributed by sarajadhav12052009
int main(){    int x = 5;    int const * ptr = &x;    ++(*ptr);    printf("%d", x);           getchar();    return 0; }
varshagumber28
nikhatkhan11
sarajadhav12052009
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Runtime Errors
Output of C Programs | Set 2
Different ways to copy a string in C/C++
Output of C Programs | Set 3
Output of C++ Program | Set 1
Output of Python Program | Set 1
Output of Java Program | Set 2
Output of Java Program | Set 3
Output of C++ programs | Set 47 (Pointers)
Output of Java Programs | Set 12
How to generate random colors by using React hooks ?

29 Oct, 2021
We are going to make a react custom hook for generating random colors.
Pre-requisite:
React.js
React Hooks
Approach: Basically, if we are familiar with React , then we all have already used react custom hooks(like useState, useEffect , useContext etc.). We can also make our custom react hooks and can use it wherever we want. So there’s a small code for generating random colors. Here we will be making a random color generator custom hook (in our custom hook file), here we will make a function for changing color called (generateColor) , and we will be passing color and generate color as return. Then we will use this in our App.js by destructuring and will use that generate color as an onClick event function for a button through which we will change the color of our window.
Creating react application:
Step 1: Go to your command prompt and write the below command to create a react app.
npx create-react-app <YOUR_APP_NAME>
Step 2: Then go to your app folder by typing the below command
cd <YOUR_APP_NAME>
Project Structure: Our folder structure should be like this.
Folder structure
Step 3: Make a separate file useGenerateRandomColor.js in your src folder and use the below code :
useGenerateRandomColor.js
import {useState} from 'react';  const useGenerateRandomColor = () => {    const [color,setColor] = useState("")    const generateColor = () =>{        setColor(Math.random().toString(16).substr(-6));    };    return {color,generateColor};      };export default useGenerateRandomColor;
Step 4: Now go to src/App.js and paste the below code to use our random color generator custom hook.
App.js
import "./App.css";import useGenerateRandomColor     from "./useGenerateRandomColor";  function App() {  const { color, generateColor }             = useGenerateRandomColor();  return (    <div      style={{        height: "100vh",        width: "100vw",        backgroundColor: "#" + color,        display: "flex",        justifyContent: "center",        alignItems: "center",      }}    >      <button        style={{          padding: "40px",          borderRadius: "10px",          backgroundImage: "linear-gradient(to top, #a8edea 0%, #fed6e3 100%)",          fontSize: "larger",        }}        onClick={generateColor}      >        Generate random color      </button>    </div>  );}  export default App;
Now we are good to go with our react app .
Step to run the application: Run the following command to start your app in your localhost:3000.
npm start
Output:
React-Hooks
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design DFA in LEX Code that accepts the string having even binary number over input alphabet {0,1}

31 Jul, 2021
Problem Overview – Design a DFA in LEX Code that accepts the string having even binary number over input alphabet  {0,1}.
Example – 
Input : 1010
Output: Accepted

Input : 1001
Output: Not Accepted

Input: 23ab
Output:Invalid

Input:ab345
Output:Invalid

Input:010101
Output:Not Accepted
Approach :LEX provides us with an INITIAL state by default. So to make a DFA, use this as the initial state of the DFA. We define two more states: A, and DEAD, where the DEAD state would be used if encountering a wrong or invalid input. When the user inputs an invalid character, move to DEAD state, and then print “Invalid”. If the input string ends at A then display the message “Accepted”. Else if the input string ends at state INITIAL then displays the message “Not Accepted”.
Note –To compile the lex program we need to have a Unix system that has flex installed into it. Then we need to save the file with the .l extension.For example- filename.lThen after saving the program closes the lex file and then open the terminal and write the following commands as follows.
lex filename.l
cc lex.yy.c
./a.out
LEX CODE :
%{
%}
  
%s A DEAD
  
%%
<INITIAL>0 BEGIN A;
<INITIAL>1 BEGIN INITIAL;
<INITIAL>[^01\n] BEGIN DEAD;
<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");}
  
<A>0 BEGIN A;
<A>1 BEGIN INITIAL;
<A>[^01\n] BEGIN DEAD;
<A>\n BEGIN INITIAL; {printf("Accepted\n");}
  
<DEAD>[^\n] BEGIN DEAD;
<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");} 
  
%%

int yywrap()
{
    return 1;
}  
int main()
{
    printf("Enter String\n");
    yylex();
return 0;
}
Output :
Enter String
1100
Accepted
1010
Accepted
0001
Not Accepted
abc
Invalid
0101
Not Accepted
DFA
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Decidable and Undecidable problems in Theory of Computation
Halting Problem in Theory of Computation
Post Correspondence Problem
NPDA for accepting the language L = {wwR | w ∈ (a,b)*}
Pushdown Automata Acceptance by Final State
Undecidability and Reducibility in TOC
Program to construct a DFA which accept the language L = {anbm | n mod 2=0, m≥1}
Arden's Theorem in Theory of Computation
How can I apply an offset on the current time in Python?

Whenever you want to add or subtract(apply an offset) to a date/time, use a datetime.datetime(), then add or subtract datetime.timedelta() instances. A timedelta object represents a duration, the difference between two dates or times. The timedelta constructor has the following function signature −
datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
Note − All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative. You can read more about it here − https://docs.python.org/2/library/datetime.html#timedelta-objects
An example of using the timedelta objects and dates −
import datetime
old_time = datetime.datetime.now()
print(old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print(new_time)
This will give the output −
2018-01-04 11:09:00.694602
2018-01-04 08:59:00.694602
timedelta() arithmetic is not supported for datetime.time() objects; if you need to use offsets from an existing datetime.time() object, just use datetime.datetime.combine() to form a datetime.datetime() instance, do your calculations, and 'extract' the time again with the .time() method.
Python | Program to convert a tuple to a string

30 Jun, 2021
Given a tuple of characters, Write a python program to convert the tuple into a string. 
Examples: 
Input : ('a', 'b', 'c', 'd', 'e')
Output : abcde

Input : ('g', 'e', 'e', 'k', 's')
Output : geeks
 There are various approaches to convert a tuple to a string. 
Create an empty string and using a for loop iterate through the elements of the tuple and keep on adding each element to the empty string. In this way, the tuple is converted to a string. It is one of the simplest and the easiest approaches to convert a tuple to a string in Python.
Python3
# Python3 code to convert a tuple# into a string using a for loop  def convertTuple(tup):        # initialize an empty string    str = ''    for item in tup:        str = str + item    return str  # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str)
Output:
geeks
The join() method is a string method and returns a string in which the elements of the sequence have been joined by a str separator. Using join() we add the characters of the tuple and convert it into a string.  
Python3
# Python3 code to convert a tuple# into a string using str.join() method  def convertTuple(tup):    str = ''.join(tup)    return str  # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str)
Output:
geeks
The str.join() function works well when we have only string objects as the tuple elements but if the tuple contains at least one non-string object then the str.join() function will fail and show a TypeError as a string object cannot be added to a non-string object. Hence to avoid this TypeError we will make use of map() function inside the join(). This map() function will take the iterator of the tuple and str() function as its parameters and convert each element of the tuple into a string.
Python3
# Python3 code to convert a tuple# into a string using str.join() & map() functions  def convertTuple(tup):    st = ''.join(map(str, tup))    return st  # Driver codetuple = ('g', 'e', 'e', 'k', 's', 101)str = convertTuple(tuple)print(str)
Output:
geeks101
The reduce(fun, seq) function is used to apply a particular function passed in its argument to all of the list elements mentioned in the sequence passed along. We pass the add operator in the function to concatenate the characters of a tuple.  
Python3
# Python3 code to convert a tuple# into a string using reduce() functionimport functoolsimport operator  def convertTuple(tup):    str = functools.reduce(operator.add, (tup))    return str  # Driver codetuple = ('g', 'e', 'e', 'k', 's')str = convertTuple(tuple)print(str)
Output:
geeks
sanju6890
Python string-programs
Python tuple-programs
python-string
python-tuple
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Difference between Relative Addressing Mode and Direct Addressing Mode

04 Jul, 2022
Prerequisite – Addressing Modes In an Instruction Fetch operation of the Instruction Cycle Process, addressing mode plays a crucial part. Addressing Mode is how the operand is addressed in an instruction word before being executed. 
1. Relative Address Mode: In this mode, the Effective Address (EA) of the operand is calculated by adding the content of the CPU register and the address part of the instruction word. The effective address is calculated by adding displacement (immediate value given in the instruction) and the register value. The address part of the instruction is usually a signed number, either positive or negative. The effective address thus calculated is relative to the address of the next instruction.
EA = CPU Register + Displacement
Figure – PC Relative Addressing Mode
Relative Addressing Mode can be further classified into three types –
PC (Program Counter) Relative Addressing Mode.
Index Register Relative Addressing Mode or Indexed Addressing Mode.
Base Register Addressing Mode.
2. Direct Address Mode: In Direct Address Mode, the effective address of the operand is equal to the address part of the instruction, i.e. the address part of the instruction indicates the memory location containing the operand. Example – ADD R1, 4000 where 4000 is the effective address of the location. 
Figure – Direct Address ModeIn this example, the memory location 4000 contains the operand 100 which gets added to the contents of R1 and gets stored in R1. Difference between Relative Addressing Mode and Direct Addressing Mode : 
The PC Relative or Base Relative Addressing mode is favored over the direct addressing mode because-i) Reduce the size of program storage.ii) Reduce the instruction fetch queue’s size.
iii) It will be simpler to relocate.
annieahujaweb2020
microprocessor
Computer Organization & Architecture
Difference Between
GATE CS
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to display the items in a JComboBox in Java

The following is an example to display the first element in a JComboBox in Java:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      String[] strArr = new String[] { "Laptop", "Mobile", "Desktop", "Tablet" };
      JComboBox<String> comboBox = new JComboBox<>(strArr);
      panel.add(comboBox, BorderLayout.NORTH);
      JTextArea text = new JTextArea(5, 5);
      panel.add(text, BorderLayout.CENTER);
      JButton btn = new JButton("Click");
      btn.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            text.setText((String) comboBox.getSelectedItem());
            comboBox.setSelectedIndex(0);
         }
      });
      panel.add(btn, BorderLayout.SOUTH);
      JFrame frame = new JFrame();
      frame.add(panel);
      frame.pack();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
   }
}
The output is as follows displaying the first item:
Now, select the second item (Mobile) and press the “Click” button. The following will get displayed:
How to select between/before/after dates in MySQL conditionally?

Following is the syntax −
select *from yourTableName
where
yourColumnName1 < yourValue1 AND
(yourColumnName2 > yourValue2 OR yourColumnName2 is null);
Let us create a table −
mysql> create table demo35
−> (
−> id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
−> joining_date date,
−> relieving_date date
−> );
Query OK, 0 rows affected (3.88 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo35(joining_date,relieving_date) values('2020−01−10','2020−07−11');
Query OK, 1 row affected (0.15 sec)
mysql> insert into demo35(joining_date,relieving_date) values('2020−05−07','2020−12−08');
Query OK, 1 row affected (0.17 sec)
mysql> insert into demo35(joining_date,relieving_date) values('2020−04−11','2020−09−18');
Query OK, 1 row affected (0.14 sec)
mysql> insert into demo35(joining_date,relieving_date) values('2020−03−12','2020−10−01');
Query OK, 1 row affected (0.13 sec)
Display records from the table using select statement −
mysql> select *from demo35;
This will produce the following output −
+----+--------------+----------------+
| id | joining_date | relieving_date |
+----+--------------+----------------+
|  1 | 2020−01−10   | 2020−07−11     |
|  2 | 2020−05−07   | 2020−12−08     |
|  3 | 2020−04−11   | 2020−09−18     |
|  4 | 2020−03−12   | 2020−10−01     |
+----+--------------+----------------+
4 rows in set (0.00 sec)
Following is the query to select date conditionally in MySQL −
mysql> select *from demo35
−> where
−> joining_date < '2020−05−11' AND
−> (relieving_date > '2020−08−10' OR relieving_date is null);
This will produce the following output −
+----+--------------+----------------+
| id | joining_date | relieving_date |
+----+--------------+----------------+
|  2 | 2020−05−07   | 2020−12−08     |
|  3 | 2020−04−11   | 2020−09−18     |
|  4 | 2020−03−12   | 2020−10−01     |
+----+--------------+----------------+
3 rows in set (0.00 sec)
Python | Merge two lists into list of tuples

27 Dec, 2018
Given two lists, write a Python program to merge the two lists into list of tuples.
Examples:
Input : list1 = [1, 2, 3]
        list2 = ['a', 'b', 'c']
Output : [(1, 'a'), (2, 'b'), (3, 'c')]

Input : list1 = [1, 2, 3, 4]
        list2 = [ 1, 4, 9]
Output : [(1, 1), (2, 4), (3, 9), (4, '')]

Approach #1 : NaiveMerge both the list into a list of tuple using a for loop. But the drawback is given two lists need to be of the same length.
def merge(list1, list2):          merged_list = [(list1[i], list2[i]) for i in range(0, len(list1))]    return merged_list      # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))
[(1, 'a'), (2, 'b'), (3, 'c')]

 Approach #2 : Naive but more efficientThis method remove the above given drawback and work well with uneven lengths of the two lists. It also provide try catch error for Index error.
def merge(list1, list2):          merged_list = []    for i in range(max((len(list1), len(list2)))):          while True:            try:                tup = (list1[i], list2[i])            except IndexError:                if len(list1) > len(list2):                    list2.append('')                    tup = (list1[i], list2[i])                elif len(list1) < len(list2):                    list1.append('')                    tup = (list1[i], list2[i])                continue              merged_list.append(tup)            break    return merged_list  # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))
[(1, 'a'), (2, 'b'), (3, 'c')]

 Approach #3 : Using zip()using zip() method to merge the two list elements and then typecasting into tuple.
def merge(list1, list2):          merged_list = tuple(zip(list1, list2))     return merged_list      # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))
((1, 'a'), (2, 'b'), (3, 'c'))

 Approach #4 : Using enumerate(), alternative to zip().
This method uses two for loops to enumerate through lists and merge the two lists.
def merge(list1, list2):          merged_list = [(p1, p2) for idx1, p1 in enumerate(list1)     for idx2, p2 in enumerate(list2) if idx1 == idx2]    return merged_list      # Driver codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']print(merge(list1, list2))
[(1, 'a'), (2, 'b'), (3, 'c')]

 Approach #5: Using map() and lambda.
# Using map() and lambdadef listOfTuples(l1, l2):    return list(map(lambda x, y:(x,y), l1, l2))  # Driver Codelist1 = [1, 2, 3]list2 = ['a', 'b', 'c']  print(listOfTuples(list1, list2))
[(1, 'a'), (2, 'b'), (3, 'c')]

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Element methods in Selenium Python

11 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium in Python works with elements. An element can be a tag, property, or anything, it is an instance of class selenium.webdriver.remote.webelement.WebElement. After you find an element on screen using selenium, you might want to click it or find sub-elements, etc. Selenium provides methods around this WebElement of Selenium. In this article, we have discussed various methods that one can use to perform multiple tasks with Selenium and its WebElement.
To use a method on a WebElement, first of all we need to locate it into the webpage. There are various methods n how to locate an element in Selenium Python. Checkout – Locator Strategies – Selenium Python. After you have grabbed an element you can use a method according to following syntax –Syntax –
element.method_name
Example –
<input type="text" name="passwd" id="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")
element = driver.find_element_by_name("passwd")
element = driver.find_element_by_xpath("//input[@id='passwd-id']")
Also, to find multiple elements, we can use –
elements = driver.find_elements_by_name("passwd")
Now one can use any method as –
element.method_name
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reading and writing binary file in C/C++

To write a binary file in C++ use write method. It is used to write a given number of bytes on the given stream, starting at the position of the "put" pointer. The file is extended if the put pointer is currently at the end of the file. If this pointer points into the middle of the file, characters in the file are overwritten with the new data.
If any error has occurred during writing in the file, the stream is placed in an error state.
ostream& write(const char*, int);
To read a binary file in C++ use read method. It extracts a given number of bytes from the given stream and place them into the memory, pointed to by the first parameter. If any error is occurred during reading in the file, the stream is placed in an error state, all future read operation will be failed then.
gcount() can be used to count the number of characters has already read. Then clear() can be used to reset the stream to a usable state.
ifstream& write(const char*, int);
Begin
   Create a structure Student to declare variables.
   Open binary file to write.
   Check if any error occurs in file opening.
   Initialize the variables with data.
   If file open successfully, write the binary data using write method.
      Close the file for writing.
   Open the binary file to read.
   Check if any error occurs in file opening.
   If file open successfully, read the binary data file using read method.
      Close the file for reading.
   Check if any error occurs.
   Print the data.
End.
 Live Demo
#include<iostream>
#include<fstream>
using namespace std;
struct Student {
   int roll_no;
   string name;
};
int main() {
   ofstream wf("student.dat", ios::out | ios::binary);
   if(!wf) {
      cout << "Cannot open file!" << endl;
      return 1;
   }
   Student wstu[3];
   wstu[0].roll_no = 1;
   wstu[0].name = "Ram";
   wstu[1].roll_no = 2;
   wstu[1].name = "Shyam";
   wstu[2].roll_no = 3;
   wstu[2].name = "Madhu";
   for(int i = 0; i < 3; i++)
      wf.write((char *) &wstu[i], sizeof(Student));
   wf.close();
   if(!wf.good()) {
      cout << "Error occurred at writing time!" << endl;
      return 1;
   }
   ifstream rf("student.dat", ios::out | ios::binary);
   if(!rf) {
      cout << "Cannot open file!" << endl;
      return 1;
   }
   Student rstu[3];
   for(int i = 0; i < 3; i++)
      rf.read((char *) &rstu[i], sizeof(Student));
   rf.close();
   if(!rf.good()) {
      cout << "Error occurred at reading time!" << endl;
      return 1;
   }
   cout<<"Student's Details:"<<endl;
   for(int i=0; i < 3; i++) {
      cout << "Roll No: " << wstu[i].roll_no << endl;
      cout << "Name: " << wstu[i].name << endl;
      cout << endl;
   }
   return 0;
}
Student’s Details:
Roll No: 1
Name: Ram
Roll No: 2
Name: Shyam
Roll No: 3
Name: Madhu
Simplified Data Encryption Standard Key Generation

27 Sep, 2021
Simplified Data Encryption Standard (S-DES) is a simple version of the DES Algorithm. It is similar to the DES algorithm but is a smaller algorithm and has fewer parameters than DES. It was made for educational purposes so that understanding DES would become simpler.  It is a block cipher that takes a block of plain text and converts it into ciphertext.  It takes a block of 8 bit.
It is a symmetric key cipher i.e. they use the same key for both encryption and decryption. In this article, we are going to demonstrate key generation for s-des encryption and decryption algorithm. We take a random 10-bit key and produce two 8-bit keys which will be used for encryption and decryption.
Key Generation Concept: In the key generation algorithm, we accept the 10-bit key and convert it into two 8 bit keys. This key is shared between both sender and receiver. 
In the key generation, we use three functions:
1. Permutation P10
2. Permutation P8
3. Left Shift
Step 1: We accepted a 10-bit key and permuted the bits by putting them in the P10 table.
Key = 1 0 1 0 0 0 0 0 1 0
(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (1, 0, 1, 0, 0, 0, 0, 0, 1, 0)

P10 Permutation is: P10(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k3, k5, k2, k7, k4, k10, k1, k9, k8, k6) 
After P10, we get 1 0 0 0 0 0 1 1 0 0
Step 2: We divide the key into 2 halves of 5-bit each.
l=1 0 0 0 0, r=0 1 1 0 0
Step 3: Now we apply one bit left-shift on each key.
l = 0 0 0 0 1, r = 1 1 0 0 0 
Step 4: Combine both keys after step 3 and permute the bits by putting them in the P8 table. The output of the given table is the first key K1.
After LS-1 combined, we get 0 0 0 0 1 1 1 0 0 0
P8 permutation is: P8(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k6, k3, k7, k4, k8, k5, k10, k9)
After P8, we get Key-1 : 1 0 1 0 0 1 0 0
Step 5: The output obtained from step 3 i.e. 2 halves after one bit left shift should again undergo the process of two-bit left shift.
Step 3 output - l = 0 0 0 0 1, r = 1 1 0 0 0 
After two bit shift - l = 0 0 1 0 0, r = 0 0 0 1 1
Step 6: Combine the 2 halves obtained from step 5 and permute them by putting them in the P8 table. The output of the given table is the second key K2.
After LS-2 combined = 0 0 1 0 0 0 0 0 1 1
P8 permutation is: P8(k1, k2, k3, k4, k5, k6, k7, k8, k9, k10) = (k6, k3, k7, k4, k8, k5, k10, k9)
After P8, we get Key-2 : 0 1 0 0 0 0 1 1
Final Output:
Key-1 is: 1 0 1 0 0 1 0 0
Key-2 is: 0 1 0 0 0 0 1 1
guptaaman9981
cryptography
Computer Networks
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to get the enter key in ReactJS ?

11 Nov, 2021
Let us create a React project and then we will create a UI that takes input from users. Users can interact with the UI and press Enter Key to trigger an event through this. 
We will be creating an input field that takes the message as input. In the input, we have added an on Keypress function which will get activated whenever the user clicks and types something in the input. It will not do anything since a condition is added. The condition is that for every keystroke it will check if the key is entered or not. If the user presses enter then the code inside the condition will run. On the press of entering, the input text will be saved inside the state. After that, a call back function is called which will trigger an alert function greeting the user with the message. An alert function is added. So, input is created that sends a Welcome message whenever Enter is pressed by the user.
Creating React Project:
Step 1: To create a react app you need to install react modules through npx command. “Npx” is used instead of “npm” because you will be needing this command in your app’s lifecycle only once.
npx create-react-app project_name
Step 2: After creating your react project move into the folder to perform different operations.
cd project_name
Project Structure: After running the commands mentioned in the above steps, if you open the project in an editor you can see a similar project structure as shown below. The new components user makes or the code changes we will be performing will be done in the source folder.
Project_Structure
Example:
App.js
import React, { Component } from "react";  class App extends Component {    state = {        message: ""    };      render() {        return (            <div>                <p>Enter Your Message and Press Enter:</p>                  <input                    onKeyPress={(e) => {                        if (e.key === "Enter") {                            this.setState({ message: e.target.value },                            () => {                                alert(this.state.message);                            });                        }                    }}                    type="text"                />            </div>        );    }}export default App;
Step to run the application: Open the terminal and type the following command.
npm start
Output: Open your browser. It will by default open a tab with localhost running (http://localhost:3000/) and you can see the output shown in the image. Enter your message and press ENTER to see the welcome message.
Detecting Enter Key
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How To Check MySQL Version

Let us understand how to check the version of MySQL that the user is currently running −
Before entering queries on the console, it is important to ensure that the user is connected to the server.
The below query would give the version number of the server being used, and the current date.
mysql> SELECT VERSION(), CURRENT_DATE;
Note: The function ‘VERSION()’ and ‘CURRENT_DATE’ are case −insensitive. This means ‘version()’, ‘Version()’, ‘vERsion()’, all mean the same. Same goes with ‘CURRENT_DATE’
Learn about MySQL Queries
An SQL query is followed by a semi−colon.
An SQL query is followed by a semi−colon.
When a query is issued to mysql, it sends the query to the server for execution. The results are computed and displayed. Another ‘mysql>’ also gets printed, indicating that the server is ready for one more query.
When a query is issued to mysql, it sends the query to the server for execution. The results are computed and displayed. Another ‘mysql>’ also gets printed, indicating that the server is ready for one more query.
The output after executing the mysql query is in tabular form, i.e rows and columns. The first row contains the name of the columns. The remaining rows are the query results.
The output after executing the mysql query is in tabular form, i.e rows and columns. The first row contains the name of the columns. The remaining rows are the query results.
Once the query is executed, ‘mysql’ also gives the number of rows that were returned, the amount of time taken to execute the query. This gives the user a rough idea about the performance of the server.
Once the query is executed, ‘mysql’ also gives the number of rows that were returned, the amount of time taken to execute the query. This gives the user a rough idea about the performance of the server.
MySQL server can also be used to execute multiple statement in a single line. It has been shown below −
mysql > SELECT VERSION(); SELECT NOW();
Solidity - Basic Syntax

A Solidity source files can contain an any number of contract definitions, import directives and pragma directives.
Let's start with a simple source file of Solidity. Following is an example of a Solidity file −
pragma solidity >=0.4.0 <0.6.0;
contract SimpleStorage {
   uint storedData;
   function set(uint x) public {
      storedData = x;
   }
   function get() public view returns (uint) {
      return storedData;
   }
}
The first line is a pragma directive which tells that the source code is written for Solidity version 0.4.0 or anything newer that does not break functionality up to, but not including, version 0.6.0.
A pragma directive is always local to a source file and if you import another file, the pragma from that file will not automatically apply to the importing file.
So a pragma for a file which will not compile earlier than version 0.4.0 and it will also not work on a compiler starting from version 0.5.0 will be written as follows −
pragma solidity ^0.4.0;
Here the second condition is added by using ^.
A Solidity contract is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereumblockchain.
The line uintstoredData declares a state variable called storedData of type uint and the functions set and get can be used to modify or retrieve the value of the variable.
Though above example does not have an import statement but Solidity supports import statements that are very similar to those available in JavaScript.
The following statement imports all global symbols from "filename".
import "filename";

The following example creates a new global symbol symbolName whose members are all the global symbols from "filename".
import * as symbolName from "filename";

To import a file x from the same directory as the current file, use import "./x" as x;. If you use import "x" as x; instead, a different file could be referenced in a global "include directory".
Following are the reserved keywords in Solidity −
JavaScript Date getFullYear() Method

12 Oct, 2021
Below is the example of Date getFullYear() method.  
Example:  
javascript
<script>  // Here a date has been assigned  // while creating Date object  var dateobj = new Date('October 15, 1996 05:35:32');   // year from above date object is  // being fetched using getFullYear().  var B = dateobj.getFullYear();   // Printing year  document.write(B);</script>
Output:  
1996
The date.getFullYear() method is used to fetch the year from a given Date object.Syntax:  
DateObj.getFullYear()
Parameter: This function does not accept any parameters.Return Values: It returns the year for the given date.More codes for the above method are as follows: Program 1: If nothing as parameter is given to the Date() constructor, then the getFullYear() function returns current year.  
javascript
<script>  // Creating Date Object  var dateobj = new Date();   // year from above object  // is being fetched using getFullYear().  var B = dateobj.getFullYear();     // Printing current year  document.write(B);</script>
Output:  
2018
Program 2: The date of the month must lie between 1 to 31 because a month cannot have more than 31 days. That is why it returns NaN i.e, not a number because the date for the month does not exist. Hence, Year will not exist when the date of the month is set as 45 or any number which does not lie between 1 to 31. 
javascript
<script>  // Here a date has been assigned  // while creating Date object  var dateobj = new Date('October 45, 1996 05:35:32');   // year from above date object is  // being fetched using getFullYear().  var B = dateobj.getFullYear();   // Printing year  document.write(B);</script>
Output:  
NaN
Program 3: It has applications such as getting current year.It is used in websites to validate the age of the user.  
javascript
<script>  // Creating Date Object  var dateobj = new Date();   // Year from above object  // is being fetched using getFullYear()  var B = dateobj.getFullYear();   // Printing current year  document.write(B);</script>
Output:  
2018
Supported Browsers: The browsers supported by JavaScript Date getFullYear() method are listed below:  
Google Chrome 1 and above
Edge 12 and above
Firefox 1 and above
Internet Explorer 4 and above
Opera 4 and above
Safari 1 and above
 
RahulRanjan4
ysachin2314
javascript-date
JavaScript-Methods
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to empty an array in JavaScript?

There are a couple of ways to empty an array in javascript.
Let's suppose take an array
var array1 = [1,2,3,4,5,6,7];
var array1 = [1,2,3,4,5,6,7];
var array1 = [];
var array1 = [];
The code above will set the number array to a new empty array. This is recommended when you don't have any references to the original array 'array1'. You should be careful with this way of empty the array, because if you have referenced this array from another variable, then the original reference array will remain unchanged.
<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7];  // Created array
   var anotherArray = array1;     // Referenced array1 by another variable
   array1 = [];                   // Empty the array
   document.write(anotherArray);  // Output [1,2,3,4,5,6,7]
</script>
</body>
</html>
var array1.length = 0;
var array1.length = 0;
The line of code above will make the length of original array to 0 there by emptying the array.
<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7]; // Created array
   var anotherArray = array1; // Referenced array1 by another variable
   array1.length = 0; // Empty the array by setting length to 0
   console.log(anotherArray); // Output []
</script>
</body>
</html>
array1.splice(0, array1.length);
array1.splice(0, array1.length);
The above line of code also works perfectly. This way of code will update all the references of the original array.
<html>
<body>
<script>
   var array1 = [1,2,3,4,5,6,7]; // Created array
   var anotherArray = array1; // Referenced array1 by another variable
   array1.splice(0, array1.length); // Empty the array by setting length to 0
   console.log(anotherArray); // Output []
</script>
</body>
</html>
MomentJS - Unix Timestamp

Using this, you can pass the integer value in milliseconds and seconds to moment.
moment(Number);

var day = moment(1315681876406);
To use seconds inside moment will have to use it as moment.unix(timestamp)
moment.unix(Number)

var day = moment.unix(1968781876);
 Print
 Add Notes
 Bookmark this page
Darken or lighten a color in Matplotlib

To darken and lighten the color, we can chage the alpha value in the argument of plot() method.Greater the aplha value, darker will be the color.
Create data points for xs and ys using numpy.
Plot two lines with different value of alpha, to replicate darker and lighter color of the lines
Place legend of the plot using legend() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
xs = np.linspace(-2, 2, 100)
ys = np.sin(xs)
plt.plot(xs, ys, c='red', lw=10, label="Darken")
plt.plot(xs+.75, ys+.75, c='red', lw=10, alpha=0.3, label="Lighten")
plt.legend(loc='upper left')
plt.show()
How to display output data in tabular form in Node.js ?

01 Jul, 2020
Tables are a combination of rows and columns. Node.js has its own module named as a table that helps in making tables with a wide variety of styles that can be applied to the table such as border styles, colors body style, etc.
Installation of module:
npm install table
Syntax:
table(data, config)
Parameters:
data: Data is an Array of array i.e. data to be saved in the table.
config: Different predefined configuration.
Return Value: A string is returned by the function.
Example 1: Filename: script.js
let table = require("table");let data, config;  // Data to be saved in the tablesdata = [  ["A", "B", "C"],            ["D", "E", "F"],  ["G", "H", "I"],]  config = {    // Predefined styles of table  border: table.getBorderCharacters("ramac"),}  let x = table.table(data, config);console.log(x)
Step to run this program: Run script.js using the following command:
node script.js
Output:
Example 2: Filename: script.js
let table = require("table");let data, config;  data = [  ["A", "B", "C"],  ["D", "E", "F"],  ["G", "H", "I"],]  // Creating column width configurationconfig = {   columns: {    0: {      width: 1   // Column 0 of width 1    },    1: {      width: 20  // Column 1 of width 20    },    2: {      width: 5   // Column 2 of width 5    }  }};let x = table.table(data, config);console.log(x)
Step to run this program: Run script.js using the following command:
node script.js
Output:
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Node.js forEach() function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React