Posted in JavaScript, Useful Script

Javascript useful script [Part 1]

javascript

In this topic, I will provide some useful scripts in Javascript, they can help us a lot for coding

  1. Array
  • .filter()

Create a new array base on an existed array with filter conditions.

const studentAge= [17,16,18,19,21,15]
const ableToDrink = studentsAge.filter( age => age > 18 );
// Result: ableToDrink= [19,21]
  • .map()

Create a new array by copying and editing data of an existed array

// Example: create new array from numbers array and add '&' for each element
const numbers = [2, 3, 4, 5];
const dollars = numbers.map( number => '$' + number);
// Result: dollars = ['$2', '$3', '$4', '$5']
  • .forEach()

Do a certain action on each element in an array

const emotions = ['happy', 'sad', 'angry'];
emotions.forEach( emotion => console.log(emotion) );
// Result will disply one by one
// 'happy'
// 'sad'
// 'angry'
  • .some()

Check if any element in array satisfy a certain condition. If yes, return true, otherwise, return false.

 
const userPrivileges = ['user', 'user', 'user', 'admin'];
const containsAdmin = userPrivileges.some( element => element === 'admin');
// Result: containsAdmin = true, because array has element that contain 'admin'
  • .every()

Like ‘.some()’ function but check all of elements with condition.

const ratings = [3, 5, 4, 3, 5];
const goodOverallRating = ratings.every( rating => rating >= 3 );
// Result: goodOverallRating = true, because every element in array >= 3

 

2) Others

 

Like & Share if this topic is helpful for you 🙂

Advertisements
Posted in Java

[Java Core] How to read/write file in Java ?

java_logo_100

In Java, we often face the requirement to read content from a file or write content to file. In Java, we have many ways to do that :).

A) How to READ file?

  • Using BufferedReader is the simplest and most common-used method. It helps us read file line by line:

public class ReadWriteFileHandler {

public void readFileByBufferedReader(String fileName) {
 BufferedReader br = null;
 FileReader fr = null;
 try {
   fr = new FileReader(fileName);
   br = new BufferedReader(fr);
   String currentLine = "";
   while ((currentLine = br.readLine()) != null) {
// Read line by line
      System.out.println(currentLine);
   }
 } catch (IOException e) {
   e.printStackTrace();
 } finally {
   try {
     if (br != null)
        br.close();
     if (fr != null)
        fr.close();
    } catch (IOException ex) {
     ex.printStackTrace();
    }
   }
 }

}

 

 

B) How to WRITE file?

Using BufferedWriter to write content to a file, create the file if doesn’t exist, the existing content will be overridden.

The BufferedWriter is a character stream class to handle the character data. Unlike byte stream (convert data into bytes), you can just write the strings, arrays or character data directly to a file.

Please find an example below:


public void writeFile(String fileName, String content) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
bw.write(content);
System.out.println("Write Done !");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();

}

}
}

 

Basically, you can refer above code from ReadWriteFileHandler.java

Hope this topic helpful for you :), please share if you like it 🙂

Posted in Java, QA, Tips

Useful scripts for Selenium in Java

selenium_icon

Selenium HQ is really useful for testing, you can find its info at Selenium Home Page . During working on it in Java projects, I found some scripts which help us save time for test cases implementation.

  • First is the necessary component in Selenium lib:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
  • Constructors:
WebDriverWait wait = new WebDriverWait(driver, 60);
WebDriver driver;
  • Collapse / Expand

This script is an action of Mouse when User clicks on an expand-icon for collapsing or expanding

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("$('.expand-icon')[0].dispatchEvent(new MouseEvent('click'))");
  • Click on a button:
String buttonId = "//button[@id='button_id_here']";
driver.findElement(By.xpath(buttonId)).click();
  • Check a webpage exist or not
String pageTitle = "//span[contains(.,'Page_Title')]";
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(pageTitle)));
  • Find a button
String buttonElement = "//button[@title='Button text here']";
WebElement buttonElement = driver.findElement(By.xpath(buttonElement ));
  • Find a content:
String contentId = "//span[@id='Content ID Here']";
WebElement contentElement = driver.findElement(By.xpath(contentId ));
  • Others (continues)

 

 

If this topic is helpful for you. Please share 🙂

 

Posted in IDEs

[IDE] VS Code Tips

vscodeide

Owner: Microsoft

Version: 1.19.3

Download Link: VS Code Homepage

 

  • Useful Hot short keyboard:

–  Open file: Ctrl + P

 

  • How to Reveal File at Sidebar like Sublime Text ?

This feature is not activated for short keyboard. So, we need active it:

In the command palette (F1), there is a Files: Reveal Active File in Side Bar command. You can assign a shortcut to it via the keyboard shortcuts editor:

vscode_howtorevealfileatsidebar

Then set your own short keyboard for it, then press ENTER. Done :), Let’s enjoy it 🙂

  • Others

 

Share if this tip is useful 🙂

Posted in JavaScript

QUnit introduce

QUnit

  • What is QUnit?

QUnit is a powerful, easy-to-use JavaScript unit testing framework. It’s used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code.

Refer: QUnit site

  • Install QUnit using NPM:

npm install -g qunit

  • Hello World Demo:

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>QUnit Example</title>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.5.0.css">
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<script src="https://code.jquery.com/qunit/qunit-2.5.0.js"></script>
<script src="tests.js"></script>
</body>
</html>

helloworld.js

QUnit.test( "hello test", function( assert ) {
assert.ok( 1 == "1", "Passed!" );
});

 

Simply run Demo by open index.html file in Brower. Refer:

qunit_result

You also file the demo at HelloWorld at Github

Thank you. Hope it is useful 🙂

Posted in JavaScript

[AWS] How to do Scan / Query in AWS DynamoDb for JS

aws_logo

For query items from DymanoDb, AWS supports some ways: Scan, Query, BatchGetItem

Below are some examples:

If I have a table ‘GtfsStopTime’ with 2 primaries (tripId & index)

  • Scan items from a list of id:
async getGtfsStopTimeListByTripIds (tripIds) {
    try {
      var list = []
      const attributeValueList = []
      for (let tripId of tripIds) {
        attributeValueList.push({
          S: tripId
        })
      }

      const param = {
        TableName: this._getTableName(),
        ScanFilter: {
          'tripId': {
            'AttributeValueList': attributeValueList,
            'ComparisonOperator': 'IN'
          }
        }
      }

      const data = await this.dynamoDB.scan(param).promise()
      list = data.Items
      return list
    } catch (err) {
      console.error('Error happen')
    }
  }

Note: We cannot apply BatchGetItem in this case because the BatchGetItem require all primary keys of table (in this case, we only query by one primary key – tripId )

  • Query items in DynamoDb using BatchGetItem

Below is example code to fetch items in ‘GtfsStop’ table by list of stopId as input which has stopId is primary key

async getGtfsStopListByIds (stopIdList) {
    const keys = stopIdList.map(function (stopId) {
      return {
        'stopId': {
          S: stopId
        }
      }
    })

    try {
      const params = {
        RequestItems: {
          'GtfsStop': { Keys: keys }
        }
      }
      const fetchedResponse = await this.dynamoDB.batchGetItem(params).promise()
      const gtfsStopItems = fetchedResponse.Responses.GtfsStop
      return gtfsStopItems
    } catch (err) {
      throw new Error(err)
    }
  }
  • Others

 

Hope this topic is useful for you 🙂

Posted in Tips

[Tips] Helpful commands for OS

  • MAC
  1. Find IP: ifconfig | grep ‘inet
  2. Go to /usr/local folder:

Method 1: From the Terminal, type “open -a Finder /usr/local/bin”.

Method 2: From Finder’s “Go” menu, select “Go to folder…”. That’ll bring up a window in which you can type “/usr/local/bin”.

 

  • Window
  1. Find IP: ipconfig
  2. OS info: dxdiag

 

 

Posted in Frameworks, Java

FFmpeg – A complete, cross-platform solution to record, convert and stream audio and video.

java_logo_100ffmpeg

Nowaday, the Audio and Video are so popular. As a developer, you have many works to process them such as record, convert, stream, etc.

Actually, if you are an Java-er, C#-er, etc, it is really difficult to find the way to do that with pure language programming.

Today, I want to introduce one powerful ‘tool’ which can do these tasks quickly. It is FFMPEG.

FFMPEG is a complete, cross-platform solution to record, convert and stream audio and video. After using it, I found that converting video and audio has never been so easy ! You only use commands and option which are supported, only one line command ! Wow

Please find detail at below website:

http://www.ffmpeg.org/

Look at below commant to converting a .mp4 file to .avi file:

ffmpeg -i input.mp4 output.avi

Run it and Done ! You have a AVI file. How it is easy !

Because the FFMPEG is a cross-platform, so you can use it in any popular OS today such as Window, Linux, MAC OS, etc.

Beside running pure FFMPEG command directly, you can use it in your project using Java, C#, etc.

For Java, you only define a certain FFMPEG command and run it using Process object like below code:

String exeCommand = “ffmpeg -i your_input_file your_output_file”

// Run FFMPEG command
Process process = Runtime.getRuntime().exec(exeCommand);

Done. You can find the demo JAVA code using FFMPEG at Github here.

Share this topic if it is helpful 🙂

Thank you