Cursor编程初体验,搭载GPT-4大模型,你的AI助手,自然语言编程来了
创始人
2025-05-31 16:38:34
0

背景

这两天体验了下最新生产力工具Cursor,基于最新的 GPT-4 大模型,目前免费国内可访问不限次数跨平台,你确定不来体验一把?官方的 Slogan

Build Software. Fast. Write, edit, and chat about your code with GPT-4
In partnership with OpenAI

2023-03-20-Home.jpg

  • 在进行初步体验时,以下几点需要了解:
  1. Cursor编程的上下文是你所在的代码文件,即如果你的文件后缀名为.py,那么在具体沟通时,就无需再出现“使用Python实现……”这种多余的前提,可以用更具体的限制;
  2. 代码生成之后还会提示合并还是丢弃:Accept或者Reject
  3. 支持回滚:如果想撤销某次的PromptCtrl+Z, Reject
  4. 偶尔会出现生产的代码不完整的问题,只需问一句:没写完吧?
  5. Ctrl+K,生成代码或者对选定的代码段进行优化;
  6. Ctrl+L,对聊模式,对编程问题或者选定的代码段直接提问;
  • 支持的语言

2023-03-20-Language.jpg

  • 聊天模式

2023-03-20-Chat.jpg

  • 提示合并还是丢弃

2023-03-20-AcceptReject.jpg
以下通过12个简单的问题,从语言支持语法支持业务场景代码解释代码优化等方面来体验一把这个编程生产力利器。

理论上,对于复杂的任务,只要分解到GPT能够理解的那一步,都可以胜任。程序员的AI助手(它竟然可以帮我们找Bug~~),自然语言编程真的来了。至于下面生成的代码能不能用,还需要进行实际验证,但目测从语言支持、语义理解以及逻辑推理等方面来看,可用率至少80%吧。

语言支持

编程语言支持: 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 = bcrypt.compareSync('myPassword123', hash);
console.log(isMatch); // true

2023-03-20-1.gif

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 Algorithmimport numpy as np
import matplotlib.pyplot as pltclass KMeans:def __init__(self, k=2, max_iter=100):self.k = kself.max_iter = max_iterdef fit(self, X):self.centroids = {}# Initialize centroids randomlyfor i in range(self.k):self.centroids[i] = X[np.random.choice(len(X))]# Iterate until convergence or max iterations reachedfor i in range(self.max_iter):self.clusters = {}for j in range(self.k):self.clusters[j] = []# Assign each data point to the closest centroidfor 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 pointsfor 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()

2023-03-20-2.gif

Java

  • 第三问(源自于一道面试题或者日常工作中遇到的一个小需求):
    • 请简单封装一个函数,实现友好时间的功能,要求该函数可输入一个参数【时间戳】,输出一个字符串【三天前、昨天、今天、明天、刚刚(10分钟内)】。
public static String friendlyTime(long timestamp) {long current = System.currentTimeMillis();long diff = current - timestamp;if (diff < 10 * 60 * 1000) {return "刚刚";} else if (diff < 24 * 60 * 60 * 1000) {return "今天";} else if (diff < 2 * 24 * 60 * 60 * 1000) {return "昨天";} else if (diff < 3 * 24 * 60 * 60 * 1000) {return "前天";} else {return "更早之前";}
}

2023-03-20-3.gif

Java

  • 第四问(源自于一道面试题或者日常工作中遇到的一个小需求):
    • 请将一维数组的内容进行正向排序,并进行反向输出。[1,7,8,4,3,6,2,5,9]
public class Array {public static void main(String[] args) {int[] arr = {1, 7, 8, 4, 3, 6, 2, 5, 9};Arrays.sort(arr); // sort the array in ascending orderfor (int i = 0; i < arr.length; i++) {System.out.print(arr[i] + " ");}System.out.println();for (int i = arr.length - 1; i >= 0; i--) {System.out.print(arr[i] + " ");}}
}

2023-03-20-4.gif

Java

  • 第五问(源自于一道面试题或者日常工作中遇到的一个小需求):
    • 请将两个数组的交集与并集取出,存放于新的数组中。[q,w,e,r,t],[a,w,d,s,r,g]
public static void main(String[] args) {String[] arr1 = {"q", "w", "e", "r", "t"};String[] arr2 = {"a", "w", "d", "s", "r", "g"};Set set1 = new HashSet<>(Arrays.asList(arr1));Set set2 = new HashSet<>(Arrays.asList(arr2));// IntersectionSet intersection = new HashSet<>(set1);intersection.retainAll(set2);System.out.println("Intersection: " + intersection);// UnionSet union = new HashSet<>(set1);union.addAll(set2);System.out.println("Union: " + union);
}

2023-03-20-5.gif

SQL

  • 数据表结构

2023-03-20-DB.png

  • 第六问:
    • 连接本地数据库:localhost:3306,用户名:root,密码:root,从数据库poetry中的poems读取前10条数据并打引,通过author_id关联poems_author表。
USE poetry;
SELECT poems.title, poems.content, poems_author.name 
FROM poems 
JOIN poems_author 
ON poems.author_id = poems_author.id 
LIMIT 10;

2023-03-20-12.gif

语法支持

  • 第七问:
    • 编码实现从数组中找出最小值:[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);}
}

2023-03-20-6.gif

业务场景

  • 第八问(源自于实际的物联网开发场景):
    • 使用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 URLresponse = requests.get(image_url)img = Image.open(BytesIO(response.content))# Predict imageresults = model(img)# Get class predictionsclass_predictions = results.pred[0].softmax(-1)# Get class indicesclass_indices = class_predictions.argmax(-1).tolist()# Get class namesclass_names_predicted = [class_names[i] for i in class_indices]return class_names_predicted

2023-03-20-7.gif

  • 第九问:
    • 连接本地数据库:localhost:3306,用户名:root,密码:root,从数据库poetry中的poems读取前5条数据并打印。
    • 把这5条数据导出到Excel
    • 发送到钉钉
import java.sql.*;public class Database {public static void main(String[] args) {try {// Connect to local databaseString 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 tableStatement statement = connection.createStatement();ResultSet resultSet = statement.executeQuery("SELECT * FROM poems LIMIT 5");// Print resultswhile (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 ExcelResultSetToExcelConverter converter = new ResultSetToExcelConverter(resultSet);converter.export("poems.xlsx");DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/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 connectionresultSet.close();statement.close();connection.close();} catch (SQLException e) {System.out.println("Error connecting to database: " + e.getMessage());}}
}

2023-03-20-8.gif

  • 第十问(源自于实际的物联网开发场景):
    • 编码实现一个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 clientOpcUaClient client = OpcUaClient.create("opc.tcp://localhost:12686/example");// Connect to the serverclient.connect().get();// Read a value from the serverNodeId nodeId = new NodeId(2, "/HelloWorld/ScalarTypes/Int32");ReadValueId readValueId = new ReadValueId(nodeId, QualifiedName.DEFAULT, null, null);CompletableFuture readResponse = client.read(readValueId);Variant value = readResponse.get().getResults()[0].getValue().getValue();System.out.println("Value: " + value);// Write a value to the serverWriteValue writeValue = new WriteValue(nodeId, QualifiedName.DEFAULT, new Variant(42));CompletableFuture writeResponse = client.write(writeValue);Boolean success = writeResponse.get().getResults()[0].isGood();System.out.println("Write success: " + success);// Disconnect from the serverclient.disconnect().get();}
}

2023-03-20-9.gif

代码解释

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作为参数传递给它,然后将结果打印到控制台。

2023-03-20-10.gif

代码优化

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));}
}

先将上述代码写入一个.java文件,然后选择需要优化的代码段或者全选, Ctrl+K 输入以下问题。

  • 第十一问:
    • 优化下
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));}
}

从结果看, Cursor 将我们自己编写的通过位运算右移计算二进制表示中1的个数,改成了一个内置方法调用。

2023-03-20-11.gif

小总结

其实,除了上述的入门体验,还有其他很多事情可以做,eg: 编写测试用例,解决力扣编程问题,网络爬虫,制作网页,小游戏编程,you name it,这一切仅受限于我们的想象力。

以下引用池建强的一句话:

人们需要警惕的是,当年因为汽车的诞生而失业的马车夫,他们并不是转行去干司机了,而是真失业了,或者去干别的苦力活。
当上时代司机的,是另一群人。


If you have any questions or any bugs are found, please feel free to contact me.

Your comments and suggestions are welcome!

相关内容

热门资讯

【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
牛客计算器的改良(Python... 文章目录1.题目描述2.输入描述:3.输出描述:4.示例15.分析6.代码7.结语 链接࿱...
【前端】‘??‘与‘||‘有什... 0 问题 经常写const data = res.data.a ?? ''或者const d...
正大杯|市调大赛|2023备赛... 关键信息 同时随着精细化养宠趋势的深入,宠物消费类目日渐丰富。 本报告通过 Niuco...
文本生成视频Make-A-Vi... Meta公司(原Facebook)在今年9月29日首次推出一款人工智能系...