Snippets Collections
//Locators 

   > driver.findElement();
    - Return value of the above code is always 'WebElement'.

1. ID
  > findElement(By.id("idNameHere"));

2. Name
> driver.findElement(By.name('valueHere'));  
- it's the attribute 'name' in the element.

3. Xpath  ( Extended HTML path )

  > //div /* It will select the all the div elements */
  > //div[@attribute='value'] /* It will select the all the div elements with specific attribute and value */
  
  > //div[@type='submit' and @value='Login']
  > //div[@type='submit' and @value='Login' and @name='Login']
  
  > //a[text()='Gmail']
  > //a[text()='Text to Match']
              //OR use 'contains'                    -- Recommended. 
  > //a[contains(text(),'Gmail')]                      
  > //a[contains(text(),'Text to Match')]
  
 //div[@class='bd-example']//button[@type='button' and @class='btn btn-dark']
  /*  **We have to mention all the active classes element( if we are searching using the class attribute )           */
  
  > //div[@class='bd-example']//input[@value='Reset']
   div.bd-example > input 
  
4. CSS selector
 > driver.findElement(By.cssSelector("#idHere"));
 > driver.findElement(By.cssSelector(".classNameHere"));

5. LinkText : only for links text
 > driver.findElement(By.linkText("Trouble signing in?"));
//This will look for the link TEXT. Not the actual link. 

6. Partial Link Text
 > driver.findElement(By.partialLinkText("Trouble signi"));
//Only the partial string is passed. 
//Install MySql on Windows system.

> USE dataBaseName

                         // Clauses
 - SELECT | FROM | WHERE | ORDER BY
 
                     - SELECT
  : '*' Will return all the coloumns from the selected   table.
> SELECT fName,lName FROM customers //This will only look for the 2 specified columns.
 
> SELECT lname, points, points + 10 FROM customers
 // 'points + 10' Will add the given points to existing points coloumn.

> SELECT lname, points, points - 10 * 800 FROM customers
 // 'points - 10' Will Subtract the given points from existing points coloumn amnd then multiple by 800. We can use brackets if needed. 

> SELECT lname, points, points - 10 * 800 AS discount_factor FROM customers
// 'points - 10 * 800' column heading will not make sense to read, So we use 'AS' ( Alliance ), It will rename the heading from 'points - 10 * 800' to 'discount_factor'

> SELECT DISTINCT fname,lname from tableName;
//It will return the unique values for fname and lname, Duplicates will be removed. 

                           - WHERE
SELECT name FROM table1 WHERE name = 'tom';

SELECT name FROM table1 WHERE name != 'tom';
SELECT name FROM table1 WHERE name <> 'tom'; //"! and <>" are same.
//WHERE NOT  
SELECT * FROM table1 WHERE NOT score = 120;
SELECT * FROM table1 WHERE SCORE NOT IN ( 132, 20, 60); 
SELECT * FROM table1 WHERE score IN ( 132, 20, 60);    
SELECT score FROM table1 WHERE score = 100;
SELECT score FROM table1 WHERE score > 10;
SELECT score FROM table1 WHERE score < 200;
SELECT * FROM table1 WHERE date > '1991-10-10';

                  //'ORDER BY'
> SELECT * 
  FROM customers
  ORDER BY first_name;
  //It will sort the list using the 'first Name' in     ascending order.

> SELECT * 
  FROM customers
  ORDER BY first_name DESC;
  //It will sort the list using the 'first Name' in     decending order.
* WE can also add multiple 

             //AND
SELECT * FROM table1 WHERE date >= '1990-7-10' AND date <= '1990-10-10';

                                 //OR
SELECT * FROM table1 WHERE date >= '1990-7-10' OR date <= '1990-10-10';

                               //AND OR
SELECT * FROM table1 WHERE date >= '1990-7-10' AND points > 100  AND score = 120;

** AND : 'AND' Operator has higer precedence then the 'OR' operator**
  : I.E 'AND' Operator will be executed first, Even if the 'OR' is mentioned first. We can change the order using parenthesis.

 'IN' Operator:                 // 'NOT'  // IN
: We can use 'NOT' pretty much anywhere. 
SELECT * FROM table1 WHERE  score = 20 OR score = 60 OR score = 132;  
   OR
SELECT * FROM table1 WHERE score IN ( 132, 20, 60);    
SELECT * FROM table1 WHERE score NOT IN ( 132, 20, 60);    

                                  //Between
SELECT * FROM table1 WHERE SCORE BETWEEN 100 AND 150;           
//Both the points are inlusive.
SELECT * FROM table1 WHERE SCORE NOT BETWEEN 100 AND 150;
                                    
                              //Like
: It's used to find some pattern string/number/data.
> SELECT * FROM table2 WHERE fname LIKE "kara%";  //look for string starting with 'kar'
> LIKE "%ingh";  //look for string ending with 'ingh'
> LIKE "%IN%";  //look for string 'IN' ( can be anywhere )
> NOT LIKE "%IN%";  // NOT look for string 'IN' ( can be anywhere )
> LIKE "___karan%";  //look for string 'karan' starting after 3 characters ( 3 uderscores ).
> LIKE "b__y";  //look for string starting with 'b', ending with 'y' and have any two characters in between.


                             //Regexp ( Regular expression )
> SELECT * FROM table2 WHERE fname REGEXP 'tring'; //It is same as '%tring%'
> SELECT * FROM table2 WHERE fname REGEXP '^stri'; //It is same as '%tring' ( look for 'Starting' of starting )
> SELECT * FROM table2 WHERE fname REGEXP 'ing$'; //It is same as 'ing%' ( look for Ending Part)

> SELECT * FROM nameinfo WHERE Name REGEXP 'Tom|Allen'; //We add pipe in between 2 strings, This way it will search for the either of the provided strings.
> SELECT * FROM nameinfo WHERE Name REGEXP 'Tom|Allen|karan';
>  SELECT * FROM nameinfo WHERE Name REGEXP 'Tom|Allen|rose$';

>  SELECT * FROM nameinfo WHERE Name REGEX '[gim]e';
//It will look for 'ge' or 'ie' or 'me', 1 will be string from the brackets and which will be matched with 'e'.

>  SELECT * FROM nameinfo WHERE Name REGEX '[a-c]j';
 //It will look for the pattern 'aj'or 'bj' or 'cj'.


>  SELECT * FROM nameinfo WHERE Name REGEX 'e[gim]';
 //It will look for patter 'eg' or 'ei' or 'em'

>  SELECT * FROM nameinfo WHERE Name REGEX 'j[a-c]';
 //It will look for the pattern 'ja'or 'jb' or 'jc'.


> SELECT * FROM nameinfo WHERE Name REGEXP 'om$|en$';
  //Will look for 'om' or 'en' at the end of the string.

>  SELECT * FROM nameinfo WHERE Name REGEXP 's|ll';
 //Will look for 's' or 'll' anythere in the field ( can be starting,ending or middle.)
--------------------------------------------
                
                          //Comments
 : We use double Hyphen ( -- ) in the front of the code to make it as a comment.
> SELECT *
> --FROM customers        //This line will be commented. 
> WHERE customer_id = 100                         
            
                ---------------------------------------------
                         
                         
                         
                              //Table                         
> CREATE TABLE tableName (
                        columnName1 dataType(),
                        columnName2 dataType(),
                        columnName3 dataType(),
                        );
> INSERT INTO tableName VALUES("abv","ds","sda");

> ALTER TABLE tableName ADD newColumn1 dataType();
//Add new coloumn to the existing table

> DROP TABLE tableName1;
//'tableName1' will be deleted from the selected DB.

----------------------------------------
             //Null ( Empty Field )

> SELECT *
  FROM tableName 
  WHERE phoneNumer IS NULL;
 //It will return all the phoneNumber's which has        values NULL.
-----------------------------------------------


                         
//

Inspect a website and press CTRL + F ( curser should be selected on inspect side )to open xpath Search bar on chrome.

//Find Specific text with element H4
> //h4[text()='Cucumber - 1 Kg']
  
//Selecting parent of H4 element with text 'Cucumber....'  
> //h4[text()='Cucumber - 1 Kg']//parent

//Selecting parent of H4 element with text 'Cucumber....' with specific class   
> //h4[text()='Cucumber - 1 Kg']//parent::*[@class='production-action']
  
  
public static void main(String[] args) {
 //Basic set up.
}

//Print in the console.
System.out.println("Printing String...");

//Basics.
- Pink letters are keywords. ( public, static, class, void... )
- Compiler will always start with the 'main' mathod.      
- use ';' after each line of code.
- 'void' is the basically how we tell that we returning nothing. if we want to return a number? then mention 'int' instead of 'void'.                              
                              
                              
                              
int a = 10;
// 'int' is Integer.

String name = "Karan";
// 'String' is string.    
                              
 ----------------------------
             // Transfer data/methods within classes.
 
  public class Parent {
   // This is the parent Class.    
    public static void main(String[] args){
    
     Methods m = new Methods;
     //Methods is the class name.
     // 'm' is the oject.
    
     m.ValidateHeader(); 
     // 'm.' will provide 'built in' and custom methods             available in the 'Methods' class.
    
     m.ValidateFooter();
     // It will return 'Done Amigo' as programed in method. 
     }                           
  }                              
                              
  
 publick class Methods {
    //This is the 'Methods' class ( child class)
   // We won't be using 'main' method here as we are just            sending the data.
    
     public void ValidateHeader(){
      //Example of an Method.    
      // 'void' since we are not returning anything. 
    }
     public String ValidateFooter(){
      //Example of an Method.    
       // 'String' as we are returning string
        return "Done amigo"  
    }
     public int ValidateFooter2(){
      //Example of an Method.    
        return 200;  
    }
  }                             
                              
-----------------------------                          
                              
//

//Java Installation

// Eclipse Installation
> 'New Java Project' 
- src > 'New Java Class'
 - Download Selenium Jar file for Java.
 
 // Adding 'External Jar' ( Downloaded Selenium exe files ) to the Project Properties. ( As Class not Module )  ( ProjectName => Properties => Libraries ), Which will be used to import methods used in project.
 * Need to do for every project.
 
 // 'https://www.selenium.dev/selenium/docs/api/java/overview-summary.html'   ( Java API for Selenium )
 
 
//For Each browser we need different 'Invoke' file.
 System.setProperty(key, value );
  key = 'webdriver.chrome.driver' ( It's provided by the respective browser developers, Will be different for each browser  )             value = 'Address of invoked file on PC'    
 
 
// Create new object.
 className driver = new className();
/* driver: is object
 new : creates new memory for the class */

         -----------------------------------

//                       Basic set up;
{
  		//Invoking .exe file from Google Chrome 
		System.setProperty("webdriver.chrome.driver", "C:\\Users\\jpann\\Downloads\\Don't Delete\\chromedriver.exe");
		
		//Creating Object.
		WebDriver driver1 = new ChromeDriver();
}

               ----------------------------------
// Invoking for FireFox.
{
    System.setProperty("webdriver.gecko.driver","Location of           firefox invoke file.")
      //Creating Object.
		WebDriver driver1 = new FirefoxDriver();
}

          ----------------------------------
          
          /*   WebDriver Methods.  
          */
          
//Creating Object.
WebDriver driver1 = new ChromeDriver();          

//Pass the URL to open. 
driver1.get("http:/google.com")

//Return URL
driver1.getCurrentUrl();
          
//Return the Page Source.
driver1.getPageSource()

//This can be used to navigate the browser ( Go to next or previous link )
driver1.navigate().back();
driver1.navigate().forward();

//Once the execution is over, Close the test. (current window)
driver1.close();

//Once the execution is over, This will close all the Child Windows.
driver1.quit();

 
      -----------------------------------------
         
   /* Locator Techniques & Tools used to identify Objects.  
   */
        
 //Locators: ( the 'selector' is called 'Web Element in Selenium' )
 driver1.findElement(By.id("id_NameHere")); //Will locate using 'id'.
 driver1.findElement(By.className("class_NameHere")); // Will locate using 'class name',

 driver1.findElement(By.name("tag_NameHere"));
// Will locate the element using Tag Name.

 driver1.findElement(By.linkText("forget password?"));
//It will locate the element by the exact text present in the tag.

  //Methods
//Sending Data to an element ( To Input Field ),
 driver1.findElement(By.id("id_NameHere")).sendKeys("Text is added from Selenium.")

 driver1.findElement(By.id("text")).getText();
//It will get the text from #text

/* 
- ID's with Numerical values might be dynamic. It might change with clicks/time. So avoid selecting such tags using ID
- Classes with spaces won't work. ( Compound classes will not work )
- If there are two same ID's Selected. It will select the first one.
*/

driver1.findElement(By.className("buttonPlay")).click();
 //This will click the button with class 'buttonPlay'

---------------------
 // xpath
   driver1.findElement(By.xpath("path..['singleQuoteUsed'].."))

> Inspect (F12) on any selected element > Right click on HTML  code on right side ( on the element) > copy > XPath.
> This xpath can be used to select the element.
> This is not always 100% accurate.
> Double quotes inside the double quote won't work. ( use single quotes inside.)
> If the xpath starts with "html/body...", Then it is not relialble to use the path. 
> Might be different path for browsers.  
> Can be created in number of ways. ( using tag/class/attribute/id...)

> Before running the Scipts, We can validate the 'xpath' first, It will save time.
  - We can check/validate the xpath manually by running 
    > $x("xPathHere...") ( It should be written in browser's console, if it returns a array/object then it means the path is valid, if it show null then it's incorrect path)
  - Other way to check the path is to use a extension on the browser.                       
                   > Customized xpath 
 syntax:   //tagName[@attribute='value']
  /*for example */
 - //div[@id='box1'] ( double forward slash are part       of the code, Not comments)
 - //*[@id='username']  
   /*  Here it will  select any tags with id 'username' ( '//' is part of the code, not comments ) */
   
           > Creating xpath using Regular expression:
 - Sometimes in attributes the value string is fixed but the numerical values keep on changing, or if the value is too long but we know the format So in that case we can use syntax:

"//tagName[contains(@attribute,'value')]"

Example: <input id="username123"> </input>
> //input[contains(@id,'username')]
   
            ----------------------------------
 
 // CSS selector
- CSSselector is 10 times faster than xpath.
 driver1.findElement(By.cssSelector("#email"))
> Inspect on any selected element > Right click on HTML  code on right side ( on the element) > copy > CSS selector.
> We can check/validate the path manually using ( in the browser console)
     $("Path here...")

- Css Customized selector:
tagName[attribute='value']   ( @ and '//' are not used here like xpath )

- CSS regular expression selector:
tagName[Attribute*='value']

Example: <input id="name1233"> </input>
input[id*='name']

- Searching using Text
- Syntax : [class='class1 class2']

     --------------------------------- 

  // Traversing Through Elements

 // -parent-child
>  If there is no way to select the given element, We can select this tag using it's parent tag.
- define the xpath for parent and then direct to child using tagNames. 
Example: You want to select a 'input' tag and there is no unique/stable way to do it.
- Select it's parent tag first and then come to the child using tagNames, If on the way we have 2 same sibling tags then mention the number with it ( div[1] or divp[2] ).

  - parent : "//div[@class='1st-c']"

> Reach to Child using the parent now
- //div[@class='1st-c']/div/div[2]/div/input
-  parentTag/childTag/innerChildtag  

Child > Parent: ( only possible in xpath)

Example :
child: "//li[@id='item-1']"
- "//li[@id='item-1']/parent::ul"
    -----------------------------------

  //Relative and Absolute xpath.
  
- Relative : Does not depend upon the Parent or the child node. Even if the parent/child tag is removed, Still the locator (Selected element) should work just fine.  
 Example : "//div[@id='username']"

- Absolute : Here the selector is depended upon the parent/child tags. if any change in the order ,then selector will be affected.
Example:  //section/div/div/div/div/ul/li[2]

------------------------------------
          
      //Sibling Traversing ( "following-sibling::" )

- How to select/traverse through the siblings.

> "//li[@id='li-1']" ( This is the selected 'li' and we want to select it's 3rd sibling.) 
                       
> "//li[@id='li-1']/following-sibling::li[3]"
                
      --------------------------------------

    //Locating using 'text'  ( using xpath )  
                      
Syntax: "//*[text()=' specificWord ']"
// '*' It represents any tag can be selected.                      
Example: 
> driver1.findElement(By.xpath("//*[text()=' Singh ']")).getText();                      
                      
//The word should be exactly on the HTML, Include spaces both sides if there are spaces on the HTML code.                      
      ---------------------------------------
        
   /* Selenium Web Drivers
   */
//SELECT :                      
// >Static Dropdown: How to select  option from dropdown list.      
> Select sElement = new Select(elementLocation);
// 'Select' is the in-built class to manage 'select' element.
- We can choose 'option' in 3 ways.
 > sElement.selectByValue("JPY");
 > sElement.selectByIndex(3);
 > sElement.selectByVisibleTest("CANADIAN DOLLAR");

> sElement.deselectAll(); //Will de-Select all the options.


> Thread.sleep(time);
- We can use this to wait for the webpage/Program to laod, So as the next line codes can be executed after 2 seconds.


//Dynamic Dropdown.
- If there are two elements with exactly the same path, It will only select the first one.
- To select the second one, use ("(//a[@value='DEL'])[2]"));
- This will select using it's index.    

: It's not alway good idea to use index, So we use 'Parent-Child' locator,
- So Select the Parent Tag first and then it's child ( This way even if there are two elements with same name, But there Parent could be different.)

Example" ( 1 space after the Parent Element and then the child element Xpath. ):
( //input[@id='ctl00_mainContent_ddl_destinationStation1_CTXT'] //*[@value='DEL'] )
  
//AutoSuggestive Dropdown.  
: When user type something, The input field will provide some autoSuggestive results ( google, youtube...)

: To Clear the Pre-populated data OR sometimes we just select on the input field and it clears the data.
> .selector().clear();
or
> .selector().click();

: Use 'Down arrow' button and select using 'Enter'
> .selector()).sendKeys(Keys.DOWN);
> .selector()).sendKeys(Keys.ENTER);

: We can use 'selector' into an variable and re-use it multiple times.
WebElement element = drivere.findElement(By.id("idName"));
element.clear();
element.sendKeys("New Text To Seach");
element.sendKeys(Keys.ENTER); //This will push 'Enter' button.


//Radio Buttons:
- We can select button using the usual 'WebElement' 
- we can use  '//input[@name='group1']' to check/compare/code/test the size of the Inputs with same group name.

- Here is the example to select inputs of same group using it's index.
> driver.findElement(By.xpath("//input[@name='group1'][1]")).click();
> Thread.sleep(1000);
> driver.findElement(By.xpath("//input[@name='group1'][3]")).click();
> Thread.sleep(1000);
> driver.findElement(By.xpath("//input[@name='group1'][2]")).click();


- It will return the Size of the input with same same group name.
> driver.findElements(By.xpath("//input[@name='group1']")).size()
> driver.findElements(By.xpath("//input[@type='radio']").get(0);
//It will select the first element.                     

                      
//Play with Attributes:
> selector.getAttribute("value");
> selector.getAttribute("name");
> selector.getAttribute("id");
> selector.getAttribute("class");
                      


//Check the size of the input radio button with same group name.
> int count = driver.findElements(By.xpath("//input[@name='group1']")).size();
				
> for (int i = 0 ; i < count ; i++ ) {
 //Print the 'attribute's Value of name = 'group1'. We are using loop and it's findElement(s).`
> String checkText = driver.findElements(By.xpath("//input[@name='group1']")).get(i).getAttribute("value");
						
> if(checkText.equals("Milk")) {
> System.out.println("Milk Found: "+ i);							 driver.findElements(By.xpath("//input[@name='group1']")).get(i).click();
			}						
		}

                   /*--------  */

/*  Java Alerts  */
: How can we manage the pop ups which are not web based element's. ( Which are not coded through HTML/Css/Js) are coded through 'Java'.

//We need to switch from 'web' to 'popup' View,So we can manage popups.
> driver.switchTo().alert().getText(); //This will return the whole 'text'on the PopUp.
> driver.switch().alert().sendKeys("Karan Singh"); //This can be used to Pass the value in the text field on PopUp.
> driver.switchTo().alert().accept(); // 'accept' will indicate as:'OK'|'agree'|'accept'
> driver.switch().alert().dismiss(); // 'dismiss' will indicated as 'cancel' | 'No' | 'Ignore'.

                   /*--------  */


//Check Boxes.
> ("//input[@type='checkbox']")
 or
 ("input[type='checkbox']")
 - It will return all the checkboxes on the given web page. ( use findElements )
> selector.isSelected(); //It will tell if checkbox is selected or not.
> selector.click();

                   /*--------  */

//Assertions: 
- It is a way to check if the Test case Passed or Failed. We are not to use console log's to check the results and see if the test is passed or failed, In work we are to be use "Assertions", Which will automatically tell if a test passes or failes. 
- Download 'testing Java' file and add it to your project Path.

- Boolean Check:
> Assert.assertTrue(data);
//This will expect a TRUE value to Pass the test.

> Assert.assertFalse(data);
//This will expect a FALSE value to Pass the test.

- Value Check: (String or value):
> Assert.assertEquals(selecter.getText(), "5 Adults");
: This will check the 'text' from selector and compare it to the '5 Adults'.

//Date:
: We can select the current date using classes/ or some other way.
> selector.click();

//Check if the element is enabled or disabled.
> select.isSelected(); //This does not work some times, Because of the website/app. As it might appear it's disabled but the selenium gets confused.
- We can Test/check the specific classed/attributes in the element, Which will tell us if the element is disabled/removed.
> select.getAttribute("style")
//This will return a complete STRING of all the CSS properties.
> select.getAttribute("style").contains("opacity:1"); //True
> select.getAttribute("style").contains("opa"); //True
> select.getAttribute("style").contains("1"); //True
> select.getAttribute("style").contains("opp"); //False
> select.getAttribute("style").contains("1");
//We can check the string by using 'contains' method.

  /* ------------XX--XX--XX---------*/

       /*-------Deep Dive Into Function-------------- */

: Format Code & debugging
 > CTRL + SHIFT + F
// This will format the code in the aligned format. 

: Naming Convection
- Class name should always start with capital letter ( Not camelCase )
- Variable should always be in lower case letters.
- Use CamelCase for Variable name.

- Debugging:
 > Right click on the line number and tap 'Toggle Breakpoint'
 > Debug As > Java Application.
 //This way the scipt will stop at toggled point and we need to manually push the 'next button' ( Step over or F6) to move to next line on script or push 'RESUME' it will resume the script in regular fashion.
 

//Adding Item Into the Carts 
//set up:


//Basics:

console.log(__dirname);
  //It will return the absolute path for current folder.
console.log(__filename);  //It will return the absolute path for current folder  with file name.
---------------------------------------------------

// Modeles | Require
let data = require("./script");
/* :> './' will look for relative to current path,
'require(".fileName") Will return the object.'
*/

module.exports = { var1, var2 }
// We can export multiple things/variables.

let { people } = require("./totalPeople");
// It will only return the 'people' variable in 'totalPeople'.

let { people, age } = require("./totalPeople");
// It will only return the 'people' and 'age' variables in 'totalPeople'.

// Also called Destructuring.
    ---------------------------------------------------
  
let os = require("os");
//Will provide built in Operating System module( object).

console.log(os.platform());
//Will return the type of OS ( windows/Linux...);

console.log(os.homedir());
//It will provide the HOME directory
      ---------------------------------------------------

const fs = require("fs");
 //Built in module, Used to read/write the files. ( FILE SYSTEM )
        
                       // Reading Files
fs.readFile(('./R/text.txt'), ( error, data ) => {
   console.log("Data: ", data); // It will return a package as a Buffer. 
   console.log(data.toString()); // It will provide the data (text.txt) in readable format.
});
//'readFile' is an async function and will not block the execution.

                      // Writing Files
fs.writeFile('./R/text.txt', " This is new replaced data,  ", ( ) => {
  //If the address is not valid, It will create the file.
  // It will replace the old data.
  //Since it's Async function, Call back function is required.
  console.log("Data updated");
});
//'writeField' is an asyn function and will not block the execution.


                      // Directories
//create
fs.mkdir('./assets',(err)=>{
    if(err) { console.log("Error: ",err) }
    console.log("Folder created");
})
//Remove
fs.rmdir('./assets',(err)=>{
    if(err) { console.log("Error: ",err) }
    console.log("Folder Removed");
})

//Check if specific 'folder' exist or not.
if(fs.existSync("./Resources")){
  //Check if 'Resources' folder is there or not.
  //'existSync' is a sync function and will block the code. 
  //code
}

**
  //Check for folder 'R' using '!'.
if(!fs.existsSync('./R')){
    console.log(" R Folder does not exists");

 //Create Folder.
 fs.mkdir('./R',(err)=>{
     if(err){ console.log("Issue with creatin Folder") };
     console.log("Folder R created")
 })
}else {
    //If already there, then deleting 'R' Folder
    fs.rmdir("./R",(err)=>{
        if(err){ console.log("issue with deleting Folder") }
        console.log("Folder R Deleted.")
    })
}

**  

                      // Deleting Files        
fs.unlink("./R/text.txt", (err)=>{
    console.log("Issue with deleting File");
    console.log("File has been deleted.")
})


//We should always check first if 'folder'/'files' exist or not.
if(fs.existsSync("./R")){
  console.log("Folder 'R' does exist");
  //Code
}

if(fs.existsSync("./R/file.txt")){
  console.log("File 'file.txt' does exist");
  //Code
}
** //Summary
  //Import Modules
const http = require("http");
const fs = require("fs");

//Creating Server
const server = http.createServer((req, res)=>{})

//Read File.
fs.readFile("./R/blogData.txt",(err,data)=>{ })

//Writing Files
fs.writeFile("./R/newFile4", "To a worm in horseradish, The world is horseradish.", (error)=>{
 // console.log("File Updated.")
})

//Create Directories.
fs.mkdir("./R/newFile5",(error)=>{})

//Check the Folder/File
console.log(fs.existsSync("./R/newFile2"));

//Remove Folder
fs.rmdir("./R/NewFolderCreated",(error)=>{ })

//Deleting File
fs.unlink("./R/newFile2",(error) =>{ })

//Server Configuration.
server.listen(8080 ,"localhost",()=>{});

**


      ---------------------------------------------------
      
 //Streams and Buffers.       
 Stream : Start using data, Before it has finished loading. Data will be transferred as 'Buffers'.
 
**
                //Create/Read new Stream
let createStream1 = fs.createReadStream("./R/sampleData.txt");
//Address should be mentioned.
/* We can pass the 2nd argument as '{ encoding: "utf8" }', and this we don't have to use 'toString()'.
let createStream1 = fs.createReadStream("./R/sampleData.txt",{encoding:"utf8"});
*/

createStream1.on("data",(bufferData)=>{
  //'on' is event listener, 
  //'data' is type of event. ( example 'click','scroll')
    console.log(bufferData.toString());
  //Every time we get new buffer, This 'bufferData' will be called ( call back function.)
})
**        
                          //Write Stream       
** 
let createStream = fs.createReadStream("./R/sampleData.txt", { encoding:'utf8'});
let writeStream = fs.createWriteStream('./R/blogData.txt');//if address does not exist, It will create new one.

writeStream.write('First Line Here...'); 
// It will write the provided text in './R/blogData.txt'

createStream.on("data",(buffer)=>{
  //For every 'buffer' generated, It will passed on to 'writeStream' 
    writeStream.write('\n'); 
    writeStream.write("Some Data");
    writeStream.write('\n');
    writeStream.write('\n');
    writeStream.write( buffer );
})    
 writeStream.write('Last Line Here....'); 
**
  //OR
**
  //Streams and buffers.
let createStream = fs.createReadStream("./R/sampleData.txt", { encoding:'utf8'});
let writeStream = fs.createWriteStream('./R/blogData.txt');

writeStream.write("First Line...");

//Using 'PIPE'
createStream.pipe(writeStream);
 //It will automatically pass all the data to './R/blogData.txt'. from "./R/sampleData.txt".
**  
        
      ---------------------------------------------------
                 //Client and Servers
const http = require("http");

const server = http.createServer((req, res)=>{
      console.log("Request Made")
});

server.listen( 3000 , 'localhost' ,()=>{
  // 'localhost' is by default.
    console.log("Server is Live on Port 3000")
})

      ---------------------------------------------------
            //Requests and Responses.
**  
  const server = http.createServer((req, res)=>{
      console.log("Request Made")
      
    console.log(req.url);
    //It will provide the 'url'. Root url is '/'.
    
    console.log(req.method);
    //It will return the method used. 
});
**    

 
**
const server = http.createServer((req, res)=>{

  //Set Header Content Type.
  res.setHeader("Content-type", "text/plain");
  //It will tell browser what kind of content to      expect. It can '"text/html"', If we want to pass     on HTML content/tags. 
  
  res.write(" Hello Karan");
  res.end(); //Manually end it. This will send the response to the browser. 
});
**
  
**
//Linking HTML file to the Code. 
 let fs = require("fs");

const server = http.createServer((req, res)=>{

  res.setHeader("Content-type", "text/html");
  //'text/html' is used, This time we will passing data as a HTML content ( with Tags nd all);
  
  fs.readFile('./home/Index.html',(err, data)=>{
    if(err){
      console.log("Koi Panga", err);
      res.end();
      //If err then we want to end the response, So that browser will move with next step ( other wise it will struck on loading )
    }else {
      res.write(data); //We are passing 'index.html' as the data.
      res.end();
      
      //We can also use 'res.end(data)'(for single file). ( res.write() will not be needed. )
    }
  })

  
  res.write(" Hello Karan");
  res.end(); //This will send the response to the browser. 
});
  
 **
   
                //Routes
   
**
 const server = http.createServer((req, res)=>{   
 console.log("URL: ", req.url)
   
 let path = "./"; // Root will always be './'
 switch( req.url ){
  
  case '/':
  path += 'index.html'
  break;

  case '/about':
  path += "about.html";
  break;
  default :
  path += "404.html";
     //This we can add specific page
}

 //Header Content.
 res.setHeader("Content-type", "text/html");
 fs.readFile(path,(err, data )=>{
   //Depending upon the URL, It will return the required HTML/plain page.
 res.write(data);
 res.end();
  })
});
**   
                  //Status Codes
   200 - OK
   301  Resource moved
   404  Not Found
   500  Internal serval error
  
  -------------------------------------------------
      ---------------------------------------------------
      ---------------------------------------------------
      ---------------------------------------------------
      -------------------------------------------------
      ---------------------------------------------------
      ---------------------------------------------------
      ---------------------------------------------------

  



  
  
# Do not forget the trailing dash in the source and target destinaton paths!

# Synchronize current directory to server
rsync -avPh --stats --delete ./ HOST:REMOTE_PATH/
  
# Synchronize a local directory to server
rsync -avPh --stats --delete LOCAL_PATH/ HOST:REMOTE_PATH/
  
# Sync remote server with local path
rsync -avPh --stats --delete HOST:REMOTE_PATH LOCAL_PATH
// Configurration for lanch.json

{
	"version": "0.2.0",
    "configurations": [
        {
          	"name": "Listen for XDebug",
          	"type": "php",
          	"request": "launch",
          	"port": 9000,
          	"pathMappings": {
            		"/var/www/project/": "${workspaceFolder}/site/project/"
            	}
    	}
    ]
}


    
// Content of xdebug.ini on server
    
zend_extension=xdebug.so

xdebug.remote_enable=1
xdebug.remote_autostart=1
xdebug.remote_host=10.0.2.2
xdebug.remote_port=9000
xdebug.remote_connect_back=1
xdebug.remote_cookie_expire_time=30
xdebug.idekey=vscode
xdebug.max_nesting_level=512

xdebug.profiler_enable=0
xdebug.profiler_output_name=xdebug.out.%t
xdebug.profiler_output_dir=/vargrant/profiler
xdebug.profiler_enable_trigger=1
  
  
// To install xdebug on server run
sudo apt-get install php-xdebug
// Edit xdebug.ini
sudo nano /etc/php/mods-available/xdebug.ini
...

/*  Creating Database  */
           
           /* Common Commands */

man //It is the 'manual' for all the commands in the linux system. 
> man ls //It will provide manual for 'ls'
> man touch //It will provide manual for 'touch'
> man man (All the manual will be displayed)
> man -k search //It will provide all the keywords related to 'search'.
> man -k jaskara //It will provide all the keywords related to 'jaskara'
  

which //It will provide the location from where shell is using the command.
> which touch //It will return the location of 'touch' cmd.
> which ls //It will return the location of 'ls' cmd.

 uname // This cmd will provide the system OS basic information.
uname -a | uname -i | uname -m


sudo parted // "Hard drive" details
parted -l //Provide partition of the HDD


sudo shutdown -h now //It will immediately shutdown the system
sudo shutdown -h +10 //It will shutdown the system in 10minutes.   
sudo shutdown -h +10 "System Will shutdown in 10minutes, Please Save your Work"//It will shutdown the system in 10minutes with the Prompted information.   
sudo shutdown -r now //It will Reboot the system.
sudo shutdown -c // To cancel the scheduled shutdown. 


pwd //Print Working Directory. ( It will provide the current directory)

cd //Change directory.
> cd /  //This will take to the parent directory.
> cd /childFolder/ChildsChildFolder/ // This will take the folder. But we should be in the current node to get to the child.   
> cd ~/desiredFolder //It will directly take to the desired folder. We don't have to worry about the current node.
> cd ..   //It will take to the previous directory
> cd ../..  /* Will take two directories back*/
> cd ../../..  /* Will take three directories back*/
> cd ~ //It will take to home directory


ls // It will Provide all the list items/files in the relative directory
> ls -l // It will provide detailed information.
> ls -alh  
  //or
> ll
// It will provide easier format to read.
> ls test* //It will only look for folders starting with string 'test'.
> ls *est //It will only look for folders ending with string 'est'.

> find / -name fileName* //it will find evrything starting          with 'fileName'.( might have to add sudo )
   
  
mkdir //It is used to create new folders. 
> mkdir folderName1
> mkdir test{1..5} //It will create 5 folders with pattern test1...test5.
> mkdir test{a..d}
  
touch // It will create new File(blank) in the directory.
> touch index.html
> touch script.js
> touch index.html style.css script.js //It will create all three files.

mrdir //It is usded to delete folders.

rm //It is used to remove files/Folders.
> rm index.html
> rm index.html style.css script.js //It will remove all three files.
rm -r folderName //Will delete all child data ( 'r' is recursive )
> rm -r test{1..5} //It will remove all the files with provided pattern


cat //Concatenate FILE(s) to standard output.
    //It can also be used to view files/data
    //It can only view text files.
> cat text.txt // It will print the 'text.txt'
> head text.txt //It will display the first 10 lines of the 'text.txt'
> head -2 text.txt //It will display first 2 lines.
> tail text.txt //It will display the last 10 lines of the 'text.txt'
> tail -2 text.txt //It will display last 2 lines.

> cat fileName (press double 'Tab') //It will return all the files starting with 'fileName'(s)

 grep //...
     //This can be used to filter data.
> sudo grep opened /var/log/auth.log //It will provide all the 'opened' in 'auth.log' file.

date //It will return date information.




      /*----------------------------------------*/

                 /*General Theory */
- Linux is case sentitive
- Relative : Present location ( Current directory)
- Absolute : Location from Root.
- Sudo group : A group of superusers that can access the root account and be receive unlimited privileges.

      /*----------------------------------------*/



              /* Ubuntu Server */

> sudo updateddb //It will update the database.

> locate fileName 
> locate test* //It will return all files starting with 'test'  
      /*----------------------------------------*/

  
              /*  Managing User */
//ONLY super user can add user on the system.
 //To Add User.  
> sudo useradd -d /home/dUserFolder -m dUserName
//It will add 'dUserName' as a new user name on the system
> sudo passwd dUserName
//It will create the password for 'dUserName'.
  

//2nd way to Add User. ( better way )
adduser //It is a script to 'add user',(not a command)  
> sudo adduser dUserName
//It will automatically create user and it's respestive folder and will ask to create password for it.

> cat /etc/group
 //It will return all the groups on the system. 
> cat /etc/group | grep dUserName
//It returns the 'group'(s) of user name 'dUserName'


 

              //Modify Users

//Add Group to user.
sudo usermod -aG groupName UserName
> sudo usermod -aG sudo dUserName
// We are adding 'sudo' group to user 'dUserName'.

> su UserName1
//It will change the terminal to 'UserName1'

//Lock User
> sudo usermod -L dUserName

//unlock User
> sudo usermode -U dUserName

//   /etc/passwd
> cat /etc/passwd
 //It will provide all the user's on the system ( including system groups ).

> sudo vipw
//It will display all the User's in a nano editabled list.
// Remove the need groups by using CTRL+K(To remove the line/group ) > CTRL+O (over write) > CTRL+X (exit).
//Removed groups will not show in the '> cat /etc/passwd'

//2nd way to remove group
groupdel
> groupdel [options] GROUPNAME


//  /etc/shadow
//It will return all the user's and there respective password and password data ( encryption used + Password expiration information ) . 


//Remove User
deluser
> deluser [--remove-all-files] [--backup] [--back-to DIR] dUserName
//It will remove the user and also the create the back for it.

  /*----------------------------------------*/


            /*   Managing Groups  */

addgroup
> sudo addgroup groupName1
//It will add 'groupName1' to the user.

> grep groupName1 /etc/group
//It will return the information about 'groupName1' 


groups
> groups
//It will return all the groups for the user.


Permissions:
> ll text.txt  
OR 
> ls -alh text.txt
 //It will provide the basic information about the file, inclduing permissions it has. 

-rwx-rwx-r--
-1 - 2- 3 -4
//Here Numbers are different groups. 
rw : read and write
r : Read.
x : executable file


To change Groups:
> sudo usermod -g newPrimaryGroup dUserName
//'newPrimaryGroup' Will be the primary group.


//Where can we keep the files to share data between different users. 
/var/share
/var/local/share
/share
/srv - for files that may be shared using a service externally.

//To modify the permission for user on the group.

//It will make new folder,
> sudo mkdir /home/newFolder

 //Adding new group
> sudo addgroup grpName1

// Group 'groupName1' will have access to 'newFolder' folder.
> sudo chgrp grpName1 /home/newFolder


  /*----------------------------------------*/



           /*  Managing Text Files  */

vim | nano
//Two popular linux terminal's IDE.


// VIM

> sudo app install vim
//In case if VIM is not installed by default.

> vim filesName.text



  /*----------------------------------------*/
 

     /* Linux Structure */

- man hier
//It will return the structure of the Linux system and basic idea about all the files.

 

  /*----------------------------------------*/
         /*  Remote Access    */


- SSH works on TCP.



/*----------------------------------------*/

  /*----------------------------------------*/

  
  
  
  
  
  
  
  
  
  
{
  "name": "frontend",
    // add proxy, so instead of looking at front end server, our api requests look at backend server
    // call it prox, then add the loopback address and the backend server port
  "proxy": "http://127.0.0.1:8080",
  "version": "0.1.0",
# ssh-copy-id takes care of adding your key in the right place

ssh-copy-id -i "user@hostname.example.com -p2222"

# If you don't use -i all of your public keys will be copied over.
# Also a alias for the host can be used if configured in your ssh config.

# You will be asked for the password and after that all should be taken care of.
# check the status of the web server i.e apache2
sudo systemctl status apache2

# restart the service
sudo systemctl restart apache2

# return network-related information using a combination of flags along with the netstat command to check which process is using a particular port
sudo netstat -nlp

# find python3 programs running
ps -ax | grep python3

# kill a process by its process ID (PID)
sudo kill [process-id]

# let's check for the availability of any service with the keywords "python" or "jimmy"
sudo systemctl --type=service | grep jimmy

# stop and disable a service using
sudo systemctl stop _servicename_ && sudo systemctl disable _servicename_

star

Sat Nov 13 2021 03:35:18 GMT+0000 (UTC) https://www.youtube.com/watch?v=X9eLWkZBKgQ

#linux #server
star

Mon Oct 18 2021 14:17:05 GMT+0000 (UTC) https://www.youtube.com/watch?v=7S_tz1z_5bA

#linux #server
star

Wed Sep 29 2021 04:22:23 GMT+0000 (UTC)

#linux #server
star

Mon Aug 30 2021 20:10:30 GMT+0000 (UTC)

#linux #server
star

Wed Aug 25 2021 04:44:09 GMT+0000 (UTC)

#linux #server
star

Mon Aug 23 2021 14:59:32 GMT+0000 (UTC)

#linux #server
star

Wed Aug 11 2021 03:54:23 GMT+0000 (UTC) https://www.youtube.com/watch?v=zb3Qk8SG5Ms

#linux #server
star

Wed Aug 04 2021 16:56:10 GMT+0000 (UTC)

#server #sync #copy
star

Tue Jul 27 2021 03:07:32 GMT+0000 (UTC) https://www.youtube.com/watch?v=7S_tz1z_5bA

#linux #server
star

Sat Jul 24 2021 13:41:12 GMT+0000 (UTC)

#linux #server
star

Mon Jun 21 2021 10:21:52 GMT+0000 (UTC) https://askubuntu.com/a/265646

#ssh #server #authentification #network

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension