编程语言支持: TypeScript , HTML , CSS , Python , C , Rust , Go , CSharp , Java , PHP , SQL 等数十种。
Node.js
第一问(源自于我的一篇文章:使用bcryptjs对密码加密时,其校验原理是怎样的?):
使用bcryptjs生成hash
校验密码
// Welcome to Cursor
// 1. Try generating with command K on a new line. Ask for a new react component of an error popup.
// 2. Then, select the outputted code and hit chat. Ask if there's a bug. Ask how to improve.
// 3. Try selecting some code and hitting edit. Ask the bot to add a button that updates a statefield.
// 4. To try out cursor on your own projects, go to file menu (top left) and open a folder.
const bcrypt = require('bcryptjs');
const password = 'myPassword123';
const salt = bcrypt.genSaltSync(10);
const hash = bcrypt.hashSync(password, salt);
console.log(hash);
const isMatch = bcryptpareSync('myPassword123', hash);
console.log(isMatch); // true
Python
第二问:
编写一个聚类算法,并提供实例
# Welcome to Cursor
# 1. Try generating with command K on a new line. Ask for a pytorch script of a feedforward neural network
# 2. Then, select the outputted code and hit chat. Ask if there's a bug. Ask how to improve.
# 3. Try selecting some code and hitting edit. Ask the bot to add residual layers.
# 4. To try out cursor on your own projects, go to the file menu (top left) and open a folder.
# K-Means Clustering Algorithm
import numpy as np
import matplotlib.pyplot as plt
class KMeans:
def __init__(self, k=2, max_iter=100):
self.k = k
self.max_iter = max_iter
def fit(self, X):
self.centroids = {}
# Initialize centroids randomly
for i in range(self.k):
self.centroids[i] = X[np.random.choice(len(X))]
# Iterate until convergence or max iterations reached
for i in range(self.max_iter):
self.clusters = {}
for j in range(self.k):
self.clusters[j] = []
# Assign each data point to the closest centroid
for x in X:
distances = [np.linalg.norm(x - self.centroids[c]) for c in self.centroids]
closest_centroid = distances.index(min(distances))
self.clusters[closest_centroid].append(x)
# Update centroids to be the mean of their assigned data points
for c in self.clusters:
self.centroids[c] = np.mean(self.clusters[c], axis=0)
def predict(self, X):
predictions = []
for x in X:
distances = [np.linalg.norm(x - self.centroids[c]) for c in self.centroids]
closest_centroid = distances.index(min(distances))
predictions.append(closest_centroid)
return predictions
# Example usage
X = np.array([[1, 2], [1.5, 1.8], [5, 8], [8, 8], [1, 0.6], [9, 11]])
kmeans = KMeans(k=2)
kmeans.fit(X)
predictions = kmeans.predict(X)
colors = ['r', 'g', 'b', 'c', 'm', 'y']
for i in range(len(X)):
plt.scatter(X[i][0], X[i][1], color=colors[predictions[i]])
plt.show()
Java
USE poetry;
SELECT poems.title, poems.content, poems_author.name
FROM poems
JOIN poems_author
ON poems.author_id = poems_author.id
LIMIT 10;
语法支持
第七问:
编码实现从数组中找出最小值:[8, 1, 4, 0, -3]
采用lambda方式实现
public class Min {
public static void main(String[] args) {
int[] arr = {8, 1, 4, 0, -3};
int min = Arrays.stream(arr).min().getAsInt();
System.out.println("The minimum value in the array is: " + min);
}
}
业务场景
第八问(源自于实际的物联网开发场景):
使用YoLoV5编码实现识别烟雾火焰
import torch
from PIL import Image
import requests
from io import BytesIO
# Load model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
# Define class names
class_names = ['smoke', 'fire']
# Define function to predict image
def predict_image(image_url):
# Load image from URL
response = requests.get(image_url)
img = Image.open(BytesIO(response.content))
# Predict image
results = model(img)
# Get class predictions
class_predictions = results.pred[0].softmax(-1)
# Get class indices
class_indices = class_predictions.argmax(-1).tolist()
# Get class names
class_names_predicted = [class_names[i] for i in class_indices]
return class_names_predicted
import java.sql.*;
public class Database {
public static void main(String[] args) {
try {
// Connect to local database
String url = "jdbc:mysql://localhost:3306/poetry";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
// Read first 5 rows from poems table
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM poems LIMIT 5");
// Print results
while (resultSet.next()) {
System.out.println(resultSet.getString("title") + " by " + resultSet.getString("author") + " " + resultSet.getString("content") + " " + resultSet.getString("style") + " " + resultSet.getString("dynasty") + " " + resultSet.getString("notes"));
}
// Export results to Excel
ResultSetToExcelConverter converter = new ResultSetToExcelConverter(resultSet);
converter.export("poems.xlsx");
DingTalkClient client = new DefaultDingTalkClient("oapi.dingtalk/robot/send?access_token=ACCESS_TOKEN");
OapiRobotSendRequest request = new OapiRobotSendRequest();
request.setMsgtype("text");
OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
text.setContent("Results from database query: " + resultSet.toString());
request.setText(text);
client.execute(request);
// Close connection
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("Error connecting to database: " + e.getMessage());
}
}
}
第十问(源自于实际的物联网开发场景):
编码实现一个OPC UA客户端
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.builtin.QualifiedName;
import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;
import org.eclipse.milo.opcua.stack.core.types.structured.ReadResponse;
import org.eclipse.milo.opcua.stack.core.types.structured.WriteValue;
import org.eclipse.milo.opcua.stack.core.types.structured.WriteResponse;
import java.util.concurrent.CompletableFuture;
public class OPCClient {
public static void main(String[] args) throws Exception {
// Create a new OPC UA client
OpcUaClient client = OpcUaClient.create("opc.tcp://localhost:12686/example");
// Connect to the server
client.connect().get();
// Read a value from the server
NodeId nodeId = new NodeId(2, "/HelloWorld/ScalarTypes/Int32");
ReadValueId readValueId = new ReadValueId(nodeId, QualifiedName.DEFAULT, null, null);
CompletableFuture<ReadResponse> readResponse = client.read(readValueId);
Variant value = readResponse.get().getResults()[0].getValue().getValue();
System.out.println("Value: " + value);
// Write a value to the server
WriteValue writeValue = new WriteValue(nodeId, QualifiedName.DEFAULT, new Variant(42));
CompletableFuture<WriteResponse> writeResponse = client.write(writeValue);
Boolean success = writeResponse.get().getResults()[0].isGood();
System.out.println("Write success: " + success);
// Disconnect from the server
client.disconnect().get();
}
}
代码解释
public static int test(int n) {
int cnt = 0;
while(0 != n) {
n = n & (n - 1);
++cnt;
}
return cnt;
}
public static void main(String[] args) {
System.out.println(test(15));
}
}
先将上述代码写入一个.java文件,然后 Ctrl+K 输入以下问题。
第十一问:
解释下这段代码(或者:这段代码是什么意思?)
// 这段代码是一个Java程序,其中定义了一个名为test的静态方法,该方法接受一个整数参数n并返回一个整数。该方法使用while循环计算n的二进制表示中1的个数,并将其存储在cnt变量中。最后,该方法返回cnt的值。在main方法中,该程序调用test方法并将15作为参数传递给它,然后将结果打印到控制台。
代码优化
public class Improve {
public static int test(int n) {
int cnt = 0;
while(0 != n) {
if((n & 1) != 0) {
++cnt;
n >>= 1;
} else {
n >>= 1;
}
}
return cnt; }
public static void main(String[] args) {
System.out.println(test(15));
}
}
public class Improve {
public static int test(int n) {
int cnt = 0;
cnt = Integer.bitCount(n);
return cnt;
}
public static void main(String[] args) {
System.out.println(test(15));
}
}