Back-end separation calculator

Course for This Assignmenthttps://bbs.csdn.net/forums/ssynkqtd-04
Assignment Requirementshttps://bbs.csdn.net/topics/617378696
Objectives of This AssignmentLearn the development of front and back end and perfect the function of the first calculator.
Student ID832101201_王心怡_21124477
Github links about the front-end

GitHub - wxyyyyyyyyyy/ass1

Github links about the back-end

https://github.com/wxyyyyyyyyyy/ass2history

目录

I.Introduction

II.PSP table

III.Design and implementation process

i. Interface design

ii.Calculation logic

iii.Local storage

iv.Back-end implementation

1.Connection

2.Archive

3. Back-end function display

v.Back-end background knowledge

IV.  Summary

I.Introduction

In this blog post, I will introduce the upgraded front end separation calculator. Its basic functions include addition, subtraction, multiplication, division and remainder, and its extended functions include radical sign, trigonometric function, logarithm, scientific notation, bracket calculation, reciprocal and power operation. The front end uses HTML+JS+CSS, and the back end uses MySQL and node.js.

II.PSP table

**Personal Software Process Stages**Estimated Time(minutes)Actual Time(minutes)
Planning
• Estimate6045
Development
• Analysis2530
• Design Spec88
• Design Review58
• Coding Standard3040
• Design1520
• Coding250350
• Code Review6030
• Test2530
Reporting
• Test Repor6560
• Size Measurement1010
• Postmortem & Process Improvement Plan4060
**Sum**593691

III.Design and implementation process

i. Interface design

Based on the previous interface design, I added a new CSS style that uses the :hover pseudo-class selector to define the style of the button over the mouse. button:hover means to select the style of all buttons when hovering, turning brown when hovering over a number button and pink when hovering over other buttons. The background-color property sets the button's background color to blue. Use the button element with the "class" attribute to "digit" to set it separately so that the background color of the number button is orange and the rest of the keys are white.

 //Mouse hover: When you press the button, 
the position of the mouse will change to a different color

button {
    padding: 5px;
    background-color: #ffffff;
    border: none;
    cursor: pointer;
  }

  button:hover { 
    background-color: #ff00956c;
    color: #ffffff;
  }

  button.digit {
    background-color: #ff7b1d;
    color: #ffffff;
  }

  button.digit:hover {
    background-color: #c9500a;
  }
//Part of the button code display:
<button onclick="appendChar('*')">*</button>
      <button onclick="appendChar('1')" class="digit">1</button>
      <button onclick="appendChar('2')" class="digit">2</button>
      <button onclick="appendChar('3')" class="digit">3</button>
      <button onclick="appendChar('-')">-</button>
      <button onclick="appendChar('.')">.</button>

ii.Calculation logic

The following is JavaScript code, most of which comes with its own functions:
1. The 'calculateTan()', 'calculateLog10()', 'calculateLn()' functions are all function values that compute input values and display the result in a text box named 'result'. It evaluates the input value using the Math.() function and assigns the result to result.value.
2. ` calculateScientificNotation  ()' function is used for converting the input value science and counting method, and the results show that in a ` result ` text box. It computes the input value into a number using the 'eval()' function, then converts the result into scientific notation using the 'toExponential()' method, and assigns the result to 'result.value'.
3. The 'calculatePower()' function is used to calculate the exponential power of the input value and displays the result in a text box named 'result'. It first splits the input value according to the "^" symbol to get the base and exponent, then uses the 'Math.pow()' function to compute the exponential power of the base, and assigns the result to 'result.value'.
4. The 'calculateInverse()' function is used to calculate the inverse of the input value and displays the result in a text box named 'result'. It uses the 'eval()' function to evaluate the input value as a number, then calculates its reciprocal, and assigns the result to result.value.
5.'appendChar()' The function accepts an argument called "char" to indicate the character to append. It adds the character directly to a string variable named "expression". Parentheses and other simple operations are implemented through it.


function appendChar(char) {
    let result = document.getElementById("result").value;
    document.getElementById("result").value = result + char;
  }

function calculateTan() {
    try {
      result.value = Math.tan(eval(result.value));
    } catch (error) {
      result.value = 'ERROR';
    }
  }

  function calculateLog10() {
    let result = document.getElementById("result").value;
    let calculatedResult = Math.log10(eval(result));
    document.getElementById("result").value = calculatedResult;
  }

  function calculateLn() {
    let result = document.getElementById("result").value;
    let calculatedResult = Math.log(eval(result));
    document.getElementById("result").value = calculatedResult;
  }

  function calculateScientificNotation() {
    try {
      result.value = eval(result.value).toExponential();
    } catch (error) {
      result.value = 'ERROR';
    }
  }
  function calculatePower() {
    let result = document.getElementById("result").value;
    let parts = result.split('^');
    if (parts.length === 2) {
      let base = parseFloat(parts[0]);
      let exponent = parseFloat(parts[1]);
      let calculatedResult = Math.pow(base, exponent);
      document.getElementById("result").value = calculatedResult;
    }
  }
  function calculateInverse() {
    let result = document.getElementById("result").value;
    let calculatedResult = 1 / eval(result);
    document.getElementById("result").value = calculatedResult;
  }

 Computing function display:

计算器功能升级

iii.Local storage

If we're not thinking about using the back end, here's how local caching works:

1. Features: Data is stored in the browser and will not be lost with page refresh. Large amounts of data can be stored without taking up browser memory. Stored data can be persisted across sessions, even if the user closes the browser and opens it again. Data is stored in the form of key-value pairs, and only string type data can be stored, if you need to store other types of data, you need to serialize and deserialize operations.
2. Code idea: First, it retrieves the previously saved history from localStorage, parses it into an array if it exists, and creates an empty array if it does not exist.
Next, it assembles the current result of the evaluation and the expression into a string and adds it to the history array. It then saves the updated history array to localStorage again.
The function displayHistory() is used to display the history list. It first calls the getPreviousResults() function to asynchronously fetch the history array and then empties the contents of the history list. Next, it traverses the history array, creating a <li> element for each history, and adding the expression and result to that element.
Finally, it adds the element to the history list.
The clearHistory() function is used to clear the history. It calls the removeHistory() function to asynchronously delete the history, and then calls the displayHistory() function to redisplay the updated history list.

/ 将历史记录保存到localStorage中
let history = localStorage.getItem("history");
if (history) {
history = JSON.parse(history);
} else {
history = [];
}
history.push(result + " = " + calculatedResult);
localStorage.setItem("history", JSON.stringify(history));
}
async function displayHistory() {
let history = await getPreviousResults()
console.log(history, 'history');
let historyList = document.getElementById("history-list");
historyList.innerHTML = "";

for (let i = 0; i < history.length; i++) {
  let item = document.createElement("li");
  item.textContent = `${history[i].expression}=${history[i].result}`;
  historyList.appendChild(item);
}
}
function clearHistory() {
// localStorage.removeItem("history");
removeHistory().then(res => {
displayHistory();
})
}

本地储存历史记录

iv.Back-end implementation

There is a lot of code, you can click "ass2history" in github above to see.

1.Connection

Communicate with the server and process the saving and obtaining of the results, using jQuery's '$.ajax()' method to make HTTP requests and process responses. The url attribute specifies the URL of the server, the type attribute specifies the type of request (POST or GET), and the data attribute specifies the data to be sent. The successful callback function is defined with the 'success' attribute, and the wrong callback function is defined with the 'error' attribute. The XMLHttpRequest object is used to send the HTTP request and process the response, and the result of the asynchronous request is processed through an event listener.
(1) 'saveResult(expression, result)' : This function uses the '$.ajax()' method to send a POST request to the server, sending the expression and the result as data. After the result is saved successfully, the 'displayHistory()' function is called to display the history.
(2) 'getPreviousResults()' : This function returns a Promise object and sends a GET request to the server using the '$.ajax()' method to retrieve the previously saved result. When the result is successfully obtained, it is passed as an argument to the Promise object's 'resolve()' method.
(3) 'removeHistory()' : This function returns a Promise object and uses the '$.ajax()' method to send a POST request to the server to delete the previously saved result. When the result is successfully deleted, it is passed as an argument to the Promise object's 'resolve()' method.

(4) The calculate() function is used to send the expression entered by the user to the back end for calculation and display the calculation result on the page. The code takes the value of the input box, then creates an XMLHttpRequest object and sends the input string to the '/calculate' path on the back end using a POST request. Set the Content-Type of the request header to application/json. The onreadystatechange event listener is then used to listen for the status change of the request, and when the status of the request is 4 (completed) and the status code is 200 (successful), the result in the response is parsed and the result is displayed on the page.
(5) The'retrieveHistory()' function is used to retrieve the history from the back end and display the history on the page. The code also creates an XMLHttpRequest object that uses a GET request to retrieve the history from the '/history' path on the back end. Again, the onreadystatechange event listener listens for state changes in the request, and when the request status is 4 (completed) and the status code is 200 (successful), the history in the response is parsed, and each history is created as a div element, which is then added to the page.

2.Archive

The mysql module is used to connect to and manipulate the MySQL database, and the express module is used to create and run the server. The express.json() and express.urlencoded() middleware are used to parse the requested JSON and URL-encoded data.

(1) 'saveResult' : This endpoint is used to receive the user's expression, evaluate the result, and save the expression and result to the database. It defines a POST request handler using the app.post() method. Inside the handler, it takes the expression from the body of the request, evaluates the result using JavaScript's 'eval()' method, and inserts the expression and result into a database table called 'history'.
(2) 'getPreviousResults' : This endpoint is used to get the previously saved history. It defines a GET request handler using the app.get() method. Inside the handler, it queries the last 10 records from the 'history' table and sends the results to the client.
(3)  'removePreviousResults' : This endpoint is used to delete previously saved history. It defines a POST request handler using the app.post() method. Inside the handler, it executes a 'TRUNCATE TABLE' SQL statement to delete all records in the 'history' table.

3. Back-end function display

储存历史记录

 

v.Back-end background knowledge

1. Software introduction
Node.js is a JavaScript runtime environment based on the Chrome V8 engine that can be used to build high-performance web applications. Node.js processes requests in an event-driven and non-blocking I/O manner, making it ideal for handling highly concurrent network applications. MySQL is a popular open source relational database management system that is widely used to store and manage data. MySQL, as a relational database, can store and manage a large amount of data, and provides powerful query and transaction processing functions.
2. Combine the two
It's easy to build projects using Node.js and MySQL. We can use Node.js' module manager and package manager to handle dependencies and easily connect to MySQL database using MySQL module. Handle HTTP requests and responses by using the Express framework and writing a route. By combining these technologies, we can quickly build a complete project.

3. Flow chart

IV.  Summary

In this assignment, I learned how front end and back end combine. In order to make the interface of the calculator more beautiful, I set the mouse hover function. I learned other functions in order to implement other additional computing functions. Before starting the database setup process, you need to ensure that Node.js and MySQL are properly installed and configured. This includes installing the relevant software packages, setting up environment variables, and ensuring that they work properly. I spent a lot of time installing it, and it was a long and lonely process, solving bug after bug, exercising my patience and carefulness.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 油水分离的前沿技术包括: 1. 超声波技术:通过高频声波在油水混合物中产生微小空泡,使油和水分离。 2. 动力学分离技术:通过油水混合物的物理性质,如密度、流动性等差异,将油和水分离。 3. 光学分离技术:利用油和水在光学特性上的差异,如光吸收、折射率等,将油和水分离。 4. 膜技术:通过膜的选择性透过性,将油和水分离。 5. 化学吸附技术:通过合适的化学吸附剂,吸附油,使油和水分离。 这些技术具有不同的优缺点,根据实际应用情况,应选择合适的技术。 ### 回答2: 油水分离的前沿技术是指在处理含油废水时使用的最新科技和方法。由于油污水的治理一直是一个全球性的环境问题,因此研究人员一直在努力开发更有效的方法来分离油水,以减少对环境的污染。 一种前沿技术是利用纳米材料进行油水分离。纳米材料具有大比表面积和特殊的化学和物理性质,可以吸附或分解油污染物。这种技术通过将纳米材料应用于分离设备中,可以高效地分离油水混合物。纳米材料的使用还可以提高设备的储油容量和改善处理效率。 另一种前沿技术是利用膜分离技术进行油水分离。膜分离技术利用特殊的膜材料将油和水分离开来。这种技术相对传统的方法具有更高的分离效率和选择性。同时,膜分离技术还可以实现连续操作和减少处理成本。 此外,一种新兴的技术是利用电化学方法进行油水分离。该方法通过电场效应使油和水分离开来。这种技术具有高效、环保和可控性的优势,可以有效地处理不同种类的油污染物。 总之,油水分离的前沿技术为解决油污染问题提供了新的方法和可能性。这些技术在提高分离效率、降低处理成本和减少环境污染方面具有重要意义,对于推动可持续发展和保护环境具有重要作用。 ### 回答3: 油水分离的前沿技术是一种用于将油和水分离的先进技术。油水分离是一项重要的环境工程技术,用于处理由油污染引起的水体和废水。过去,常用的油水分离方法包括重力分离、漂浮、离心分离等,但这些方法存在一些局限性。 随着科技的进步,油水分离的前沿技术不断涌现。一个前沿技术是电化学油水分离法。该技术利用电解作用将水中的油脂离子化,然后利用电极的特殊性质将油脂吸附并分离出来。这种方法具有高效、节能、环保等优点,可以有效地从废水中分离出油脂。 另一个前沿技术是膜分离技术。膜分离技术利用特殊的薄膜材料,如聚合物膜、陶瓷膜等,通过渗透、过滤和离子交换等机制实现油水分离。这种技术具有高效、节能、可持续等特点,可以有效地去除水中的油污染物。 此外,纳米技术也被应用于油水分离的前沿技术中。纳米材料具有巨大的比表面积和特殊的物理化学性质,可以用于油水分离膜、吸附材料等的制备。通过纳米材料的使用,油水分离的效率和效果能够得到显著提高。 总之,油水分离的前沿技术不断涌现,为处理油污染带来了新的可能性。电化学油水分离、膜分离技术和纳米技术等都是重要的前沿技术,将为环境保护和资源开发提供有力支持。随着科学技术的发展,我们可以期待更多创新的油水分离技术的出现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值