🔍 搜尋結果:Node

🔍 搜尋結果:Node

99% 的時間都會用到的 22 個 JavaScript 函數 💯🔥

下面的函數對於 Web 開發和 JavaScript 程式設計來說是基礎,它們簡化了任務,例如*使用新舊 console.log()***進行偵錯**、**操作 DOM 以及處理 JSON 資料。** 了解和使用這些函數就像*建立該語言的基礎支柱*一樣。 掌握這些工具也肯定會簡化編碼流程,進而帶來良好的開發人員體驗。 --- 長話短說 ---- **控制台和除錯** -> 控制台.log(...args) **定時** -> setTimeout(回呼, 延遲) -> setInterval(回呼, 間隔) **DOM 操作和事件處理** -> 查詢選擇器全部(選擇器) -> addEventListener(事件,回呼) **JSON 處理** -> JSON.parse(jsonString) -> JSON.stringify(物件) **陣列運算(高階函數)** -> forEach(回呼) -> 地圖(回呼) -> 過濾器(回調) -> 減少(回調,初始值) **陣列運算** -> 切片(開始,結束) -> 拼接(開始,刪除計數,...專案) ->indexOf(元素) -> 包含(元素) -> 排序(比較函數) -> 反向() -> isArray(值) **字串操作** -> 分割(分隔符號) -> 連接(分隔符號) -> toLowerCase(), toUpperCase() -> 修剪() --- 控制台和除錯: ------- ### 0️⃣1️⃣ console.log(...args) ⇒ 將訊息或物件輸出到控制台以進行偵錯。 ``` // console.log(...args) console.log("Hello World!"); ``` --- 定時: --- ### 0️⃣2️⃣ setTimeout(回呼、延遲) ⇒ 在指定的延遲(以毫秒為單位)後執行函數。 ### 0️⃣3️⃣ setInterval(回調,間隔) ⇒ 以指定的時間間隔重複執行某個功能。 ``` // setTimeout(callback, delay) setTimeout(function() { console.log("This message will appear after 3 seconds."); }, 3000); // Runs the anonymous function after 3000 milliseconds (3 seconds) // setInterval(callback, interval) function printCounter() { let count = 0; setInterval(function() { console.log("Count:", count++); }, 1000); } printCounter(); // Prints count every second ``` --- DOM 操作與事件處理: ------------ ### 0️⃣4️⃣ querySelectorAll(選擇器) ⇒ 傳回一個 NodeList,其中包含與指定選擇器相符的所有元素。 ### 0️⃣5️⃣ addEventListener(事件,回呼) ⇒ 將事件處理函數附加到 HTML 元素。 ``` // querySelectorAll(selector) console.log("querySelectorAll(selector)"); const container = document.getElementById('container'); const links = container.querySelectorAll('a'); // Accessing the href attribute of each link // Iterate over the NodeList links.forEach(link => { console.log(link.href); }); // addEventListener(event, callback) console.log("addEventListener(event, callback)"); const button = document.getElementById('myButton'); button.addEventListener('click', function() { console.log('Button clicked!'); }); ``` --- JSON 處理: -------- ### 0️⃣6️⃣ JSON.parse(jsonString) ⇒ 解析 JSON 字串並傳回 JavaScript 物件。 ### 0️⃣7️⃣ JSON.stringify(物件) ⇒ 將 JavaScript 物件轉換為 JSON 字串。 ``` // JSON.parse(jsonString) console.log("JSON.parse(jsonString)"); const jsonString = '{"name": "John", "age": 30, "city": "New York"}'; const jsonObject = JSON.parse(jsonString); console.log(jsonObject.name); // Output: John console.log(jsonObject.age); // Output: 30 console.log(jsonObject.city); // Output: New York // JSON.stringify(object) console.log("JSON.stringify(object)"); const person = { name: 'John', age: 30, city: 'New York' }; const jsonString2 = JSON.stringify(person); console.log(jsonString2); // Output: {"name":"John","age":30,"city":"New York"} ``` --- 陣列運算(高階函數): ----------- ### 0️⃣8️⃣ forEach(回呼) ⇒ 對每個陣列元素執行一次提供的函數。 ### 0️⃣9️⃣地圖(回調) ⇒ 使用對每個元素呼叫提供的函數的結果來建立一個新陣列。 ### 1️⃣0️⃣過濾器(回呼) ⇒ 建立一個新陣列,其中的元素滿足給定的條件。 ### 1️⃣1️⃣減少(回調,初始值) ⇒ 透過對每個元素應用函數將陣列縮減為單一值。 ``` const numbers = [1, 2, 3, 4, 5]; // forEach(callback) console.log("forEach:"); numbers.forEach(num => { console.log(num); }); // Output: // 1 // 2 // 3 // 4 // 5 // map(callback) const doubledNumbers = numbers.map(num => num * 2); // Output: [2, 4, 6, 8, 10] // filter(callback) const evenNumbers = numbers.filter(num => num % 2 === 0); // [2, 4] // reduce(callback, initialValue) const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // 15 ``` --- 陣列操作: ----- ### 1️⃣2️⃣片(開始,結束) ⇒ 傳回指定起始索引和結束索引之間的陣列部分的淺表副本。 ### 1️⃣3️⃣ 拼接(開始,刪除計數,...專案) ⇒ 透過刪除/取代元素和/或新增元素來變更陣列內容。 ### 1️⃣4️⃣indexOf(元素) ⇒ 傳回在陣列中可以找到給定元素的第一個索引,如果不存在則傳回 -1。 ### 1️⃣5️⃣包含(元素) ⇒ 判斷陣列是否包含某個元素,傳回 true 或 false。 ### 1️⃣6️⃣排序(比較函數) ⇒ 根據提供的函數或預設排序順序對陣列元素進行排序。 ### 1️⃣7️⃣反向() ⇒ 反轉陣列中元素的順序。 ### 1️⃣8️⃣ isArray(值) ⇒ 檢查給定值是否為陣列,傳回 true 或 false。 ``` // slice(start, end) const array = [1, 2, 3, 4, 5]; const slicedArray = array.slice(1, 4); console.log("slice:", slicedArray); // Output: [2, 3, 4] // splice(start, deleteCount, ...items) const spliceArray = [1, 2, 3, 4, 5]; spliceArray.splice(2, 2, 'a', 'b'); console.log("splice:", spliceArray); // Output: [1, 2, "a", "b", 5] // indexOf(element) const indexOfArray = ['apple', 'banana', 'cherry']; const indexOfCherry = indexOfArray.indexOf('cherry'); console.log("indexOf:", indexOfCherry); // Output: 2 // includes(element) const includesArray = [1, 2, 3, 4, 5]; const includesValue = includesArray.includes(3); console.log("includes:", includesValue); // Output: true // sort(compareFunction) const sortArray = [3, 1, 4, 1, 5]; sortArray.sort((a, b) => a - b); console.log("sort:", sortArray); // Output: [1, 1, 3, 4, 5] // reverse() const reverseArray = ['a', 'b', 'c', 'd']; reverseArray.reverse(); console.log("reverse:", reverseArray); // Output: ['d', 'c', 'b', 'a'] // isArray(value) const isArrayValue = [1, 2, 3]; const isArray = Array.isArray(isArrayValue); console.log("isArray:", isArray); // Output: true ``` --- 字串操作: ----- ### 1️⃣9️⃣分割(分隔符號) ⇒ 根據指定的分隔符號將字串分割為子字串陣列。 ### 2️⃣0️⃣加入(分隔符號) ⇒ 將陣列的所有元素連接成一個字串,並以指定的分隔符號分隔。 ### 2️⃣1️⃣ toLowerCase(), toUpperCase() ⇒ 將字串轉換為小寫或大寫。 ### 2️⃣2️⃣修剪() ⇒ 刪除字串兩端的空格。 ``` // split(separator) const sentence = "Hello, world! How are you?"; const words = sentence.split(' '); console.log("split:", words); // Output: ["Hello,", "world!", "How", "are", "you?"] // join(separator) const fruits = ['Apple', 'Banana', 'Orange']; const fruitString = fruits.join(', '); console.log("join:", fruitString); // Output: "Apple, Banana, Orange" // toLowerCase(), toUpperCase() const mixedCase = "Hello WoRLd"; const lowerCase = mixedCase.toLowerCase(); const upperCase = mixedCase.toUpperCase(); console.log("toLowerCase:", lowerCase); // Output: "hello world" console.log("toUpperCase:", upperCase); // Output: "HELLO WORLD" // trim() const stringWithWhitespace = " Hello, world! "; const trimmedString = stringWithWhitespace.trim(); console.log("trim:", trimmedString); // Output: "Hello, world!" ``` 🙌 最後的想法 ------- 當我們結束對上述功能的討論時,我請您分享您的見解。 **您認為在 Web 開發或主要是 JavaScript 專案中還需要哪些其他功能?** 請隨時在下面的評論中分享您的想法和有用的功能! 我希望你喜歡這篇文章! ❤️ 與我聯絡: [Linktree。](https://linktr.ee/arjuncodess/) 快樂編碼! 🚀 感謝22097! 🤗 --- 原文出處:https://dev.to/arjuncodess/18-javascript-functions-youll-use-99-of-the-time-2bl4

使用 React 開發時應該了解的 17 個函式庫

長話短說 ==== 我收集了您應該了解的 React 庫,以建立許多不同類型的專案並成為 React 奇才🧙‍♂️。 其中每一項都是獨一無二的,並且都有自己的用例。 別忘了給他們加星號🌟 讓我們開始吧! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16rwdtymlmp6y17ocz59.gif) --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 建立應用內人工智慧聊天機器人、代理程式和文字區域 ------------------------------------------------------------------------------------ ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 將 AI 功能整合到 React 中是很困難的,這就是 Copilot 的用武之地。一個簡單快速的解決方案,可將可投入生產的 Copilot 整合到任何產品中! 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui ``` Copilot Portal 是 CopilotKit 提供的元件之一,CopilotKit 是一個應用程式內人工智慧聊天機器人,可查看目前應用狀態並在應用程式內採取操作。它透過插件與應用程式前端和後端以及第三方服務進行通訊。 這就是整合聊天機器人的方法。 `CopilotKit`必須包裝與 CopilotKit 互動的所有元件。建議您也開始使用`CopilotSidebar` (您可以稍後切換到不同的 UI 提供者)。 ``` "use client"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; export default function RootLayout({children}) { return ( <CopilotKit url="/path_to_copilotkit_endpoint/see_below"> <CopilotSidebar> {children} </CopilotSidebar> </CopilotKit> ); } ``` 您可以使用此[快速入門指南](https://docs.copilotkit.ai/getting-started/quickstart-backend)設定 Copilot 後端端點。 之後,您可以讓 Copilot 採取行動。您可以閱讀如何提供[外部上下文](https://docs.copilotkit.ai/getting-started/quickstart-chatbot#provide-context)。您可以使用`useMakeCopilotReadable`和`useMakeCopilotDocumentReadable`反應掛鉤來執行此操作。 ``` "use client"; import { useMakeCopilotActionable } from '@copilotkit/react-core'; // Let the copilot take action on behalf of the user. useMakeCopilotActionable( { name: "setEmployeesAsSelected", // no spaces allowed in the function name description: "Set the given employees as 'selected'", argumentAnnotations: [ { name: "employeeIds", type: "array", items: { type: "string" } description: "The IDs of employees to set as selected", required: true } ], implementation: async (employeeIds) => setEmployeesAsSelected(employeeIds), }, [] ); ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)並查看[演示影片](https://github.com/CopilotKit/CopilotKit?tab=readme-ov-file#demo)。 您可以輕鬆整合 Vercel AI SDK、OpenAI API、Langchain 和其他 LLM 供應商。您可以按照本[指南](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)將聊天機器人整合到您的應用程式中。 基本概念是在幾分鐘內建立可用於基於 LLM 的應用程式的 AI 聊天機器人。 用例是巨大的,作為開發人員,我們絕對應該在下一個專案中嘗試使用 CopilotKit。 https://github.com/CopilotKit/CopilotKit Star CopilotKit ⭐️ --- 2. [xyflow](https://github.com/xyflow/xyflow) - 使用 React 建立基於節點的 UI。 -------------------------------------------------------------------- ![XY流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yevpzvqpt3u6ahkqdrsl.png) XYFlow 是一個功能強大的開源程式庫,用於使用 React 或 Svelte 建立基於節點的 UI。它是一個 monorepo,提供[React Flow](https://reactflow.dev)和[Svelte Flow](https://svelteflow.dev) 。讓我們更多地了解可以使用 React flow 做什麼。 ![反應流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mzezlna4v4bx75z3omr.png) 您可以觀看此影片,在 60 秒內了解 React Flow。 https://www.youtube.com/watch?v=aUBWE41a900 有些功能在專業模式下可用,但免費層中的功能足以形成一個非常互動的流程。 React 流程以 TypeScript 編寫並使用 Cypress 進行測試。 開始使用以下 npm 指令。 ``` npm install reactflow ``` 以下介紹如何建立兩個節點( `Hello`和`World` ,並透過邊連接。節點具有預先定義的初始位置以防止重疊,並且我們還應用樣式來確保有足夠的空間來渲染圖形。 ``` import ReactFlow, { Controls, Background } from 'reactflow'; import 'reactflow/dist/style.css'; const edges = [{ id: '1-2', source: '1', target: '2' }]; const nodes = [ { id: '1', data: { label: 'Hello' }, position: { x: 0, y: 0 }, type: 'input', }, { id: '2', data: { label: 'World' }, position: { x: 100, y: 100 }, }, ]; function Flow() { return ( <div style={{ height: '100%' }}> <ReactFlow nodes={nodes} edges={edges}> <Background /> <Controls /> </ReactFlow> </div> ); } export default Flow; ``` 這就是它的樣子。您還可以新增標籤、更改類型並使其具有互動性。 ![你好世界](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xzerdd3ng0vtnz5rbgau.png) 您可以在 React Flow 的 API 參考中查看[完整的選項清單](https://reactflow.dev/api-reference/react-flow)以及元件、鉤子和實用程式。 最好的部分是您還可以加入[自訂節點](https://reactflow.dev/learn/customization/custom-nodes)。在您的自訂節點中,您可以渲染您想要的一切。您可以定義多個來源和目標句柄並呈現表單輸入或圖表。您可以查看此[codesandbox](https://codesandbox.io/p/sandbox/pensive-field-z4kv3w?file=%2FApp.js&utm_medium=sandpack)作為範例。 您可以閱讀[文件](https://reactflow.dev/learn)並查看 Create React App、Next.js 和 Remix 的[範例 React Flow 應用程式](https://github.com/xyflow/react-flow-example-apps)。 React Flow 附帶了幾個額外的[插件](https://reactflow.dev/learn/concepts/plugin-components)元件,可以幫助您使用 Background、Minimap、Controls、Panel、NodeToolbar 和 NodeResizer 元件製作更高級的應用程式。 例如,您可能已經注意到許多網站的背景中有圓點,增強了美觀性。要實現此模式,您可以簡單地使用 React Flow 中的後台元件。 ``` import { Background } from 'reactflow'; <Background color="#ccc" variant={'dots'} /> // this will be under React Flow component. Just an example. ``` ![背景元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en2tl17ef31nydaycw18.png) 如果您正在尋找一篇快速文章,我建議您查看 Webkid 的[React Flow - A Library for Rendering Interactive Graphs](https://webkid.io/blog/react-flow-node-based-graph-library/) 。 React Flow 由 Webkid 開發和維護。 它在 GitHub 上有超過 19k 顆星,並且在`v11.10.4`上顯示它們正在不斷改進,npm 套件每週下載量超過 40 萬次。您可以輕鬆使用的最佳專案之一。 ![統計資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o99csz9epqmai3ixt859.png) https://github.com/xyflow/xyflow 星 xyflow ⭐️ --- 3. [Zod](https://github.com/colinhacks/zod) + [React Hook Form](https://github.com/react-hook-form) - 致命的驗證組合。 -------------------------------------------------------------------------------------------------------------- ![佐德](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s6zvmqr0lv93vsrhofs.png) 第一個問題是:為什麼我在同一個選項中包含 Zod 和 React Hook 表單?好吧,請閱讀它來找出答案。 Zod 的目標是透過最大限度地減少重複的類型聲明來對開發人員友好。使用 Zod,您聲明一次驗證器,Zod 將自動推斷靜態 TypeScript 類型。將更簡單的類型組合成複雜的資料結構很容易。 開始使用以下 npm 指令。 ``` npm install zod ``` 這是您在建立字串架構時自訂一些常見錯誤訊息的方法。 ``` const name = z.string({ required_error: "Name is required", invalid_type_error: "Name must be a string", }); ``` ``` // It does provide lots of options // validations z.string().min(5, { message: "Must be 5 or more characters long" }); z.string().max(5, { message: "Must be 5 or fewer characters long" }); z.string().length(5, { message: "Must be exactly 5 characters long" }); z.string().email({ message: "Invalid email address" }); z.string().url({ message: "Invalid url" }); z.string().emoji({ message: "Contains non-emoji characters" }); z.string().uuid({ message: "Invalid UUID" }); z.string().includes("tuna", { message: "Must include tuna" }); z.string().startsWith("https://", { message: "Must provide secure URL" }); z.string().endsWith(".com", { message: "Only .com domains allowed" }); z.string().datetime({ message: "Invalid datetime string! Must be UTC." }); z.string().ip({ message: "Invalid IP address" }); ``` 請閱讀[文件](https://zod.dev/)以了解有關 Zod 的更多資訊。 它適用於 Node.js 和所有現代瀏覽器。 現在,第二部分來了。 有很多可用的表單整合。 ![形式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zz290xe2bpdsjvj6pzao.png) 雖然 Zod 可以驗證物件,但如果沒有自訂邏輯,它不會影響您的用戶端和後端。 React-hook-form 是用於客戶端驗證的優秀專案。例如,它可以顯示輸入錯誤。 ![反應鉤子形式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vy3m7inekd685t4nt59m.png) 開始使用以下 npm 指令。 ``` npm install react-hook-form ``` 這就是如何使用`React Hook Form` 。 ``` import { useForm, SubmitHandler } from "react-hook-form" type Inputs = { example: string exampleRequired: string } export default function App() { const { register, handleSubmit, watch, formState: { errors }, } = useForm<Inputs>() const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data) console.log(watch("example")) // watch input value by passing the name of it return ( /* "handleSubmit" will validate your inputs before invoking "onSubmit" */ <form onSubmit={handleSubmit(onSubmit)}> {/* register your input into the hook by invoking the "register" function */} <input defaultValue="test" {...register("example")} /> {/* include validation with required or other standard HTML validation rules */} <input {...register("exampleRequired", { required: true })} /> {/* errors will return when field validation fails */} {errors.exampleRequired && <span>This field is required</span>} <input type="submit" /> </form> ) } ``` 您甚至可以隔離重新渲染,從而提高整體效能。 您可以閱讀[文件](https://react-hook-form.com/get-started)。 兩者結合起來就是一個很好的組合。嘗試一下! 我透過 Shadcn 發現了它,它使用它作為表單元件的預設值。我自己在幾個專案中使用過它,效果非常好。它提供了很大的靈活性,這確實很有幫助。 https://github.com/colinhacks/zod Star Zod ⭐️ https://github.com/react-hook-form Star React Hook Form ⭐️ --- 4. [React DND](https://github.com/react-dnd/react-dnd) - 用於 React 的拖放。 ---------------------------------------------------------------------- ![反應 dnd](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0ywjp9hk8l4ocq145yr.png) 我還沒有完全實現拖放功能,而且我經常發現自己對選擇哪個選項感到困惑。我遇到的另一個選擇是[interactjs.io](https://interactjs.io/) ,根據我讀過的文件,它似乎非常有用。由於他們提供了詳細的範例,這非常容易。 ![拖放](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2h85gcto3r3kwuj0nix.png) 但我現在只介紹 React DND。 開始使用以下 npm 指令。 ``` npm install react-dnd react-dnd-html5-backend ``` 除非您正在編寫自訂後端,否則您可能想要使用 React DnD 隨附的 HTML5 後端。 這是安裝`react-dnd-html5-backend`方法。閱讀[文件](https://react-dnd.github.io/react-dnd/docs/backends/html5)。 這是起點。 ``` import { HTML5Backend } from 'react-dnd-html5-backend' import { DndProvider } from 'react-dnd' export default class YourApp { render() { return ( <DndProvider backend={HTML5Backend}> /* Your Drag-and-Drop Application */ </DndProvider> ) } } ``` 透過這種方式,您可以非常輕鬆地實現卡片的拖放操作。 ``` // Let's make <Card text='Write the docs' /> draggable! import React from 'react' import { useDrag } from 'react-dnd' import { ItemTypes } from './Constants' export default function Card({ isDragging, text }) { const [{ opacity }, dragRef] = useDrag( () => ({ type: ItemTypes.CARD, item: { text }, collect: (monitor) => ({ opacity: monitor.isDragging() ? 0.5 : 1 }) }), [] ) return ( <div ref={dragRef} style={{ opacity }}> {text} </div> ) } ``` 請注意,HTML5 後端不支援觸控事件。因此它不適用於平板電腦和行動裝置。您可以將`react-dnd-touch-backend`用於觸控裝置。閱讀[文件](https://react-dnd.github.io/react-dnd/docs/backends/touch)。 ``` import { TouchBackend } from 'react-dnd-touch-backend' import { DndProvider } from 'react-dnd' class YourApp { <DndProvider backend={TouchBackend} options={opts}> {/* Your application */} </DndProvider> } ``` 這個codesandbox規定了我們如何正確使用React DND。 https://codesandbox.io/embed/3y5nkyw381?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx&hidenavigation=1 你可以看看React DND的[例子](https://react-dnd.github.io/react-dnd/examples)。 它們甚至有一個乾淨的功能,您可以使用 Redux 檢查內部發生的情況。 您可以透過為提供者新增 debugModeprop 來啟用[Redux DevTools](https://github.com/reduxjs/redux-devtools) ,其值為 true。 ``` <DndProvider debugMode={true} backend={HTML5Backend}> ``` 它提供了多種元件選項,我需要親自測試一下。總的來說,這看起來相當不錯,特別是如果你剛開始的話。 React DND 已獲得`MIT`許可,並在 GitHub 上擁有超過 20k Stars,這使其具有令人難以置信的可信度。 https://github.com/react-dnd/react-dnd Star React DND ⭐️ --- 5. [Cypress](https://github.com/cypress-io/cypress) - 快速測試瀏覽器中執行的內容。 -------------------------------------------------------------------- ![柏](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybhbgvetu8tky7xiepdz.png) 近年來已經證明了測試的重要性,而 Jest 和 Cypress 等選項使其變得異常簡單。 但我們只會介紹 Cypress,因為它本身就很方便。 只需一張圖片就能證明 Cypress 值得付出努力。 ![柏](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ey0v3unpnblie1o610iv.png) 開始使用以下 npm 指令。 ``` npm install cypress -D ``` 如果您在專案中沒有使用 Node 或套件管理器,或者您想快速試用 Cypress,您始終可以[直接從 CDN 下載 Cypress](https://download.cypress.io/desktop) 。 一旦安裝並打開它。您必須使用`.cy.js`建立一個規範檔案。 ![規格文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/077r7oilgyuf5j0chryv.png) 現在,您可以編寫並測試您的應用程式(範例程式碼)。 ``` describe('My First Test', () => { it('Does not do much!', () => { expect(true).to.equal(true) }) }) ``` Cypress 提供了多種選項,例如`cy.visit()`或`cy.contains()` 。由於我沒有廣泛使用 Cypress,因此您需要在其[文件](https://docs.cypress.io/guides/end-to-end-testing/writing-your-first-end-to-end-test)中進一步探索它。 如果它看起來很可怕,那麼請前往這個[為初學者解釋 Cypress 的](https://www.youtube.com/watch?v=u8vMu7viCm8&pp=ygUQY3lwcmVzcyB0dXRvcmlhbA%3D%3D)freeCodeCamp 教程。 Freecodecamp 影片確實是金礦 :D Cypress 在 GitHub 上擁有超過 45,000 顆星,並且在目前的 v13 版本中,它正在不斷改進。 https://github.com/cypress-io/cypress 星柏 ⭐️ --- [6.Refine](https://github.com/refinedev/refine) - 面向企業的開源 Retool。 ----------------------------------------------------------------- ![精煉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wsti2yfikrhc9nggov5.png) Refine 是一個元 React 框架,可以快速開發各種 Web 應用程式。 從內部工具到管理面板、B2B 應用程式和儀表板,它可作為建立任何類型的 CRUD 應用程式(例如 DevOps 儀表板、電子商務平台或 CRM 解決方案)的全面解決方案。 ![電子商務](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xry9381y4s36emgb9psr.png) 您可以在一分鐘內使用單一 CLI 命令進行設定。 它具有適用於 15 多個後端服務的連接器,包括 Hasura、Appwrite 等。 您可以查看可用的[整合清單](https://refine.dev/integrations/)。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7h9tbp4u3llh8ywgb8m8.png) 但最好的部分是,Refine `headless by design` ,從而提供無限的樣式和自訂選項。 由於該架構,您可以使用流行的 CSS 框架(如 TailwindCSS)或從頭開始建立樣式。 這是最好的部分,因為我們不希望最終受到與特定庫的兼容性的樣式限制,因為每個人都有自己的風格並使用不同的 UI。 開始使用以下 npm 指令。 ``` npm create refine-app@latest ``` 這就是使用 Refine 新增登入資訊的簡單方法。 ``` import { useLogin } from "@refinedev/core"; const { login } = useLogin(); ``` 使用 Refine 概述程式碼庫的結構。 ``` const App = () => ( <Refine dataProvider={dataProvider} resources={[ { name: "blog_posts", list: "/blog-posts", show: "/blog-posts/show/:id", create: "/blog-posts/create", edit: "/blog-posts/edit/:id", }, ]} > /* ... */ </Refine> ); ``` 您可以閱讀[文件](https://refine.dev/docs/)。 您可以看到一些使用 Refine 建立的範例應用程式: - [全功能管理面板](https://example.admin.refine.dev/) - [優化不同的用例場景](https://github.com/refinedev/refine/tree/master/examples)。 他們甚至提供模板,這就是為什麼這麼多用戶喜歡Refine。 你可以看到[模板](https://refine.dev/templates/)。 ![範本](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/87vbx5tqyicb9gmgirka.png) 他們在 GitHub 上擁有大約 22k+ 顆星。 https://github.com/refinedev/refine 星際精煉 ⭐️ --- 7. [Tremor](https://github.com/tremorlabs/tremor) - React 元件來建立圖表和儀表板。 ---------------------------------------------------------------------- ![樣品元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hq6ehdstz94ya5kfvwl4.png) Tremor 提供了 20 多個開源 React 元件,用於建立基於 Tailwind CSS 的圖表和儀表板,使資料視覺化再次變得簡單。 ![社群](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkwu1t43p0zfsmeehqxl.png) 開始使用以下 npm 指令。 ``` npm i @tremor/react ``` 這就是您如何使用 Tremor 快速建立東西。 ``` import { Card, ProgressBar } from '@tremor/react'; export default function Example() { return ( <Card className="mx-auto max-w-md"> <h4 className="text-tremor-default text-tremor-content dark:text-dark-tremor-content"> Sales </h4> <p className="text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong"> $71,465 </p> <p className="mt-4 flex items-center justify-between text-tremor-default text-tremor-content dark:text-dark-tremor-content"> <span>32% of annual target</span> <span>$225,000</span> </p> <ProgressBar value={32} className="mt-2" /> </Card> ); } ``` 這就是基於此生成的內容。 ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tvpu7r0rig522zeqae8.png) 您可以閱讀[文件](https://www.tremor.so/docs/getting-started/installation)。其間,他們在引擎蓋下使用混音圖標。 從我見過的各種元件來看,這是一個很好的起點。相信我! Tremor 還提供了一個[乾淨的 UI 工具包](https://www.figma.com/community/file/1233953507961010067)。多麼酷啊! ![使用者介面套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jf4cwk5ybsc89dhz696.png) Tremor 在 GitHub 上擁有超過 14k 顆星,並有超過 280 個版本,這意味著它正在不斷改進。 https://github.com/tremorlabs/tremor 星震 ⭐️ --- 8. [Watermelon DB](https://github.com/Nozbe/WatermelonDB) - 用於 React 和 React Native 的反應式和非同步資料庫。 ------------------------------------------------------------------------------------------------ ![西瓜資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sbofucs4kcaix7igjfch.png) 我不知道為什麼資料庫有這麼多選項;甚至很難全部數清。但如果我們使用 React,Watermelon DB 是一個不錯的選擇。即使在 4k+ 提交之後,它們仍然處於`v0.28`版本,這是一個相當大的問題。 Rocket.chat 使用 Watermelon DB,這給了他們巨大的可信度。 開始使用以下 npm 指令。 ``` npm install @nozbe/watermelondb ``` 您需要做的第一件事是建立模型和後續遷移(閱讀文件)。 ``` import { appSchema, tableSchema } from '@nozbe/watermelondb' export default appSchema({ version: 1, tables: [ // We'll add to tableSchemas here ] }) ``` 根據文件,使用 WatermelonDB 時,您正在處理模型和集合。然而,在 Watermelon 之下有一個底層資料庫(SQLite 或 LokiJS),它使用不同的語言:表格和欄位。這些一起稱為資料庫模式。 您可以閱讀有關[CRUD 操作的](https://watermelondb.dev/docs/CRUD)[文件](https://watermelondb.dev/docs/Installation)和更多內容。 https://github.com/Nozbe/WatermelonDB 明星 WatermelonDB ⭐️ --- 9. [Evergreen UI](https://github.com/segmentio/evergreen) - 按 Segment 劃分的 React UI 框架。 -------------------------------------------------------------------------------------- ![常青用戶介面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkfdl3thy6cdukhxg92j.png) 沒有 UI 框架的清單幾乎是不可能的。有許多受歡迎的選項,例如 Material、Ant Design、Next UI 等等。 但我們正在報道 Evergreen,它本身就非常好。 開始使用以下 npm 指令。 ``` $ npm install evergreen-ui ``` [Evergreen Segment 網站](https://evergreen.segment.com/foundations)上顯示了任何使用者介面的基礎以及詳細的選項。 ![基礎](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/imir9z0siqqwh99p6lno.png) 它提供了很多元件,其中一些非常好,例如`Tag Input`或`File uploader` 。 ![標籤輸入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yrsxzhzdemj49aeauc8j.png) ![文件上傳器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fckysg2iz6iz7c4st3as.png) 您可以看到 Evergreen UI 提供的所有[元件](https://evergreen.segment.com/components)。 https://github.com/segmentio/evergreen Star Evergreen UI ⭐️ --- 10. [React Spring](https://www.react-spring.dev/) - 流暢的動畫來提升 UI 和互動。 -------------------------------------------------------------------- ![反應彈簧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ouigl2pr2rwbyj2whzli.png) ![流體動畫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eosf22k1notx3wa1pfpd.png) 如果您喜歡 React-Motion 但感覺過渡不流暢,那是因為它專門使用 React 渲染。 如果你喜歡 Popmotion,但感覺自己的能力受到限制,那是因為它完全跳過了 React 渲染。 `react-spring`提供了兩種選擇,試試看! 開始使用以下 npm 指令。 ``` npm i @react-spring/web ``` 這就是導入高階元件來包裝動畫的方法。 ``` import { animated } from '@react-spring/web' // use it. export default function MyComponent() { return ( <animated.div style={{ width: 80, height: 80, background: '#ff6d6d', borderRadius: 8, }} /> ) } ``` 由於以下程式碼和框,我決定嘗試 React Spring。令人驚訝的是,我們可以使用 React Spring 做很多事情。 https://codesandbox.io/embed/mdovb?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx&hidenavigation=1 您可以閱讀[文件](https://www.react-spring.dev/docs/getting-started)。 他們還提供了很多您可以學習的[範例](https://www.react-spring.dev/examples)。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/muzldxpw58tun2yyn18t.png) 它提供了大量的選項,例如`useScroll` ,它允許您建立滾動連結動畫。 例如,這個codesandbox告訴了`useScroll`的用法。 https://codesandbox.io/embed/b07dmz?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx&hidenavigation=1 React Spring 在 GitHub 上有大約 27k+ Stars。 https://github.com/pmndrs/react-spring Star React Spring ⭐️ --- 11. [React Tweet](https://github.com/vercel/react-tweet) - 將推文嵌入到你的 React 應用程式中。 -------------------------------------------------------------------------------- ![反應推文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9t2ktcvb8p6eitul8y9b.png) `React Tweet`可讓您在使用 Next.js、Create React App、Vite 等時將推文嵌入到 React 應用程式中。 該函式庫不需要使用 Twitter API。推文可以靜態呈現,從而無需包含 iframe 和額外的客戶端 JavaScript。 它是 Vercel 的開源專案。 開始使用以下 npm 指令。 ``` npm i react-tweet ``` 為了顯示推文,我們需要從 Twitter 的 API 請求資料。透過此 API 進行速率限制具有挑戰性,但如果您僅依賴我們提供的 SWR 端點 ( `react-tweet.vercel.app/api/tweet/:id` ),這是可能的,因為伺服器的IP 位址向Twitter 發出了許多請求API。這也適用於 RSC,其中 API 端點不是必需的,但伺服器仍然從相同 IP 位址發送請求。 為了避免 API 限制,您可以使用 Redis 或 Vercel KV 等資料庫快取推文。例如,您可以使用 Vercel KV。 ``` import { Suspense } from 'react' import { TweetSkeleton, EmbeddedTweet, TweetNotFound } from 'react-tweet' import { fetchTweet, Tweet } from 'react-tweet/api' import { kv } from '@vercel/kv' async function getTweet( id: string, fetchOptions?: RequestInit ): Promise<Tweet | undefined> { try { const { data, tombstone, notFound } = await fetchTweet(id, fetchOptions) if (data) { await kv.set(`tweet:${id}`, data) return data } else if (tombstone || notFound) { // remove the tweet from the cache if it has been made private by the author (tombstone) // or if it no longer exists. await kv.del(`tweet:${id}`) } } catch (error) { console.error('fetching the tweet failed with:', error) } const cachedTweet = await kv.get<Tweet>(`tweet:${id}`) return cachedTweet ?? undefined } const TweetPage = async ({ id }: { id: string }) => { try { const tweet = await getTweet(id) return tweet ? <EmbeddedTweet tweet={tweet} /> : <TweetNotFound /> } catch (error) { console.error(error) return <TweetNotFound error={error} /> } } const Page = ({ params }: { params: { tweet: string } }) => ( <Suspense fallback={<TweetSkeleton />}> <TweetPage id={params.tweet} /> </Suspense> ) export default Page ``` 您可以直接使用它,方法非常簡單。 ``` <div className="dark"> <Tweet id="1629307668568633344" /> </div> ``` 如果您不喜歡使用 Twitter 主題,您也可以使用多個選項建立自己的[自訂主題](https://react-tweet.vercel.app/custom-theme)。 例如,您可以建立自己的推文元件,但沒有回覆按鈕,如下所示: ``` import type { Tweet } from 'react-tweet/api' import { type TwitterComponents, TweetContainer, TweetHeader, TweetInReplyTo, TweetBody, TweetMedia, TweetInfo, TweetActions, QuotedTweet, enrichTweet, } from 'react-tweet' type Props = { tweet: Tweet components?: TwitterComponents } export const MyTweet = ({ tweet: t, components }: Props) => { const tweet = enrichTweet(t) return ( <TweetContainer> <TweetHeader tweet={tweet} components={components} /> {tweet.in_reply_to_status_id_str && <TweetInReplyTo tweet={tweet} />} <TweetBody tweet={tweet} /> {tweet.mediaDetails?.length ? ( <TweetMedia tweet={tweet} components={components} /> ) : null} {tweet.quoted_tweet && <QuotedTweet tweet={tweet.quoted_tweet} />} <TweetInfo tweet={tweet} /> <TweetActions tweet={tweet} /> {/* We're not including the `TweetReplies` component that adds the reply button */} </TweetContainer> ) } ``` 您可以閱讀[文件](https://react-tweet.vercel.app/#installation)。 您可以查看[React Tweet 的演示,](https://react-tweet-next.vercel.app/light/1761133168772489698)以了解它如何在頁面上呈現。 它們已發布`v3.2`版本,這表明它們正在不斷改進,並且[每週下載量超過 46k+](https://www.npmjs.com/package/react-tweet) 。 https://github.com/vercel/react-tweet Star React 推文 ⭐️ --- 12. [React 360](https://github.com/facebookarchive/react-360) - 使用 React 建立令人驚嘆的 360 度和 VR 內容。 ---------------------------------------------------------------------------------------------- ![反應 360](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92546vucm4rnnseew2fi.png) 儘管 Facebook 已將其存檔,但許多開發人員仍然發現它足夠有用,因此繼續使用。 React 360 是一個函式庫,它利用大量 React Native 功能來建立在 Web 瀏覽器中執行的虛擬實境應用程式。 它使用 Three.js 進行渲染,並作為 npm 套件提供。透過將 WebGL 和 WebVR 等現代 API 與 React 的聲明性功能結合,React 360 有助於簡化建立跨平台 VR 體驗的過程。 開始使用以下 npm 指令。 ``` npm install -g react-360-cli ``` 涉及的事情有很多,但您可以使用 VrButton 加入重要的互動功能到您的 React VR 應用程式。 ``` import { AppRegistry, StyleSheet, Text, View, VrButton } from 'react-360'; state = { count: 0 }; _incrementCount = () => { this.setState({ count: this.state.count + 1 }) } <View style={styles.panel}> <VrButton onClick={this._incrementCount} style={styles.greetingBox}> <Text style={styles.greeting}> {`You have visited Simmes ${this.state.count} times`} </Text> </VrButton> </View> ``` 除了許多令人驚奇的東西之外,您還可以加入聲音。請參閱[使用 React 360 的 React Resources](https://reactresources.com/topics/react-360)範例。 您也可以閱讀 Log Rocket 撰寫的關於[使用 React 360 建立 VR 應用](https://blog.logrocket.com/building-a-vr-app-with-react-360/)程式的部落格。 這個codesandbox代表了我們可以使用React 360做什麼的一個常見範例。 https://codesandbox.io/embed/2bye27?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.js&hidenavigation=1 https://github.com/facebookarchive/react-360 Star React 360 ⭐️ --- 13. [React Advanced Cropper](https://github.com/advanced-cropper/react-advanced-cropper) - 建立適合您網站的裁剪器。 ------------------------------------------------------------------------------------------------------- ![反應先進的作物](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9b7o2lchxua4urkot79.png) ![反應先進的作物](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tc5328gj9v9yjbptu3nn.png) React Advanced Cropper 是一個高級庫,可讓您建立適合任何網站設計的裁剪器。這意味著您不僅可以更改裁剪器的外觀,還可以自訂其行為。 它們仍處於測試版本,這意味著 API 可能會在未來版本中發生變化。 簡單的用例是設計軟體和裁剪圖像表面以獲得進一步的見解。 他們有很多選擇,因此值得。 ![選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nt5br00qyymlllmjlowk.png) ![選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atvlbxjowv1isjoi3p6m.png) 開始使用以下 npm 指令。 ``` npm install --save react-advanced-cropper ``` 您可以這樣使用它。 ``` import React, { useState } from 'react'; import { CropperRef, Cropper } from 'react-advanced-cropper'; import 'react-advanced-cropper/dist/style.css' export const GettingStartedExample = () => { const [image, setImage] = useState( 'https://images.unsplash.com/photo-1599140849279-1014532882fe?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1300&q=80', ); const onChange = (cropper: CropperRef) => { console.log(cropper.getCoordinates(), cropper.getCanvas()); }; return ( <Cropper src={image} onChange={onChange} className={'cropper'} /> ) }; ``` 您可以閱讀[文件](https://advanced-cropper.github.io/react-advanced-cropper/docs/intro),它們提供了[20 多個自訂選項](https://github.com/advanced-cropper/react-advanced-cropper?tab=readme-ov-file#cropper)。 他們主要提供三種類型的[裁剪器選項](https://advanced-cropper.github.io/react-advanced-cropper/docs/guides/cropper-types/):固定、經典和混合以及範例和程式碼。 您可以使用 React Advanced Cropper 製作一些令人興奮的東西來向世界展示:) https://github.com/advanced-cropper/react-advanced-cropper Star React 進階裁剪器 ⭐️ --- 14. [Mobx](https://github.com/mobxjs/mobx) - 簡單、可擴展的狀態管理。 --------------------------------------------------------- ![行動裝置](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/od2isnsvbr1y349cpcnb.png) MobX 是一個經過驗證的基於訊號的函式庫,可透過函數反應式程式設計簡化和擴展狀態管理。它提供了靈活性,使您能夠獨立於任何 UI 框架來管理應用程式狀態。 這種方法會產生解耦、可移植且易於測試的程式碼。 以下是使用 MobX 的任何應用程式中處理事件的方式。 ![事件架構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3k0uxde1tnj8y8xizo8c.png) 圖片來自文件 開始使用以下 npm 指令。 ``` npm install mobx-react --save // CDN is also available ``` 這就是它的樣子。 ``` import { observer } from "mobx-react" // ---- ES6 syntax ---- const TodoView = observer( class TodoView extends React.Component { render() { return <div>{this.props.todo.title}</div> } } ) // ---- ESNext syntax with decorator syntax enabled ---- @observer class TodoView extends React.Component { render() { return <div>{this.props.todo.title}</div> } } // ---- or just use function components: ---- const TodoView = observer(({ todo }) => <div>{todo.title}</div>) ``` 您可以使用 props、全域變數或使用 React Context 在觀察者中使用外部狀態。 您可以閱讀[有關 React Integration](https://mobx.js.org/react-integration.html)和[npm docs](https://www.npmjs.com/package/mobx-react#api-documentation)的文件。 您也可以閱讀[MobX 和 React 的 10 分鐘互動介紹](https://mobx.js.org/getting-started)。 MobX 在 GitHub 上擁有超過 27k 顆星,並在 GitHub 上被超過 140K 開發者使用。 https://github.com/mobxjs/mobx 明星 Mobx ⭐️ --- 15. [React Virtualized](https://github.com/bvaughn/react-virtualized) - 渲染大型清單和表格資料。 ------------------------------------------------------------------------------------ ![反應虛擬化](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znt47ig09aebglto0915.png) 開始使用以下 npm 指令。 ``` npm install react-virtualized --save ``` 以下是如何在網格中使用 ColumnSizer 元件。探索演示(文件)以詳細了解可用選項。 ``` import React from 'react'; import ReactDOM from 'react-dom'; import {ColumnSizer, Grid} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // numColumns, numRows, someCalculatedHeight, and someCalculatedWidth determined here... // Render your list ReactDOM.render( <ColumnSizer columnMaxWidth={100} columnMinWidth={50} columnCount={numColumns} width={someCalculatedWidth}> {({adjustedWidth, getColumnWidth, registerChild}) => ( <Grid ref={registerChild} columnWidth={getColumnWidth} columnCount={numColumns} height={someCalculatedHeight} cellRenderer={someCellRenderer} rowHeight={50} rowCount={numRows} width={adjustedWidth} /> )} </ColumnSizer>, document.getElementById('example'), ); ``` 您可以閱讀[文件](https://github.com/bvaughn/react-virtualized/tree/master/docs#documentation)和[演示](https://bvaughn.github.io/react-virtualized/#/components/List)。 他們提供了 React-window 作為輕量級的替代方案,但這個在發布和明星方面更受歡迎,所以我介紹了這個選項。您可以閱讀哪個選項更適合您: [React-Window 與 React-Virtualized 有何不同?](https://github.com/bvaughn/react-window?tab=readme-ov-file#how-is-react-window-different-from-react-virtualized) 。 它被超過 85,000 名開發人員使用,並在 GitHub 上擁有超過 25,000 顆星。它還擁有令人印象深刻的[170 萬+ 每週下載量](https://www.npmjs.com/package/react-virtualized)。 https://github.com/bvaughn/react-virtualized Star React 虛擬化 ⭐️ --- 16.React [Google Analytics](https://github.com/react-ga/react-ga) - React Google Analytics 模組。 ---------------------------------------------------------------------------------------------- ![反應Google分析](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6lh8m8zussnyn32togy.png) 這是一個 JavaScript 模組,可用於在使用 React 作為前端程式碼庫的網站或應用程式中包含 Google Analytics 追蹤程式碼。 該模組對我們如何在前端程式碼中進行追蹤有一定的看法。我們的 API 比核心 Google Analytics 庫稍微詳細一些,以使程式碼更易於閱讀。 開始使用以下 npm 指令。 ``` npm install react-ga --save ``` 您可以這樣使用它。 ``` import ReactGA from 'react-ga'; ReactGA.initialize('UA-000000-01'); ReactGA.pageview(window.location.pathname + window.location.search); <!-- The core React library --> <script src="https://unpkg.com/[email protected]/dist/react.min.js"></script> <!-- The ReactDOM Library --> <script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script> <!-- ReactGA library --> <script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script> <script> ReactGA.initialize('UA-000000-01', { debug: true }); </script> ``` 執行`npm install` `npm start`並前往`port 8000 on localhost`後,您可以閱讀[文件](https://github.com/react-ga/react-ga?tab=readme-ov-file#installation)並查看[演示](https://github.com/react-ga/react-ga/tree/master/demo)。 它每週的下載量超過 35 萬次,在 GitHub 上擁有超過 5,000 顆星(已存檔)。 https://github.com/react-ga/react-ga Star React Google Analytics ⭐️ --- 17.react [-i18next](https://github.com/i18next/react-i18next) - React 的國際化做得很好。 ------------------------------------------------------------------------------- ![反應-i18next](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xrxn9omsv79bzy9j9mr4.png) 無需更改 webpack 配置或加入額外的 babel 轉譯器。 開始使用以下 npm 指令。 ``` npm i react-i18next ``` 我們來比較一下程式碼結構。 > 在使用react-i18next之前。 ``` ... <div>Just simple content</div> <div> Hello <strong title="this is your name">{name}</strong>, you have {count} unread message(s). <Link to="/msgs">Go to messages</Link>. </div> ... ``` > 使用react-i18next後。 ``` ... <div>{t('simpleContent')}</div> <Trans i18nKey="userMessagesUnread" count={count}> Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>. </Trans> ... ``` 您可以閱讀[文件](https://react.i18next.com/)並前往[Codesandbox 的互動式遊樂場](https://codesandbox.io/s/1zxox032q)。 該工具已被超過 182,000 名開發人員使用,在 GitHub 上擁有超過 8,000 顆星。軟體包中令人印象深刻的 3400k+ 下載量進一步鞏固了它的可信度,使其成為您下一個 React 專案的絕佳選擇。 您也可以閱讀 Locize 關於[React Localization - Internationalize with i18next](https://locize.com/blog/react-i18next/)的部落格。 https://github.com/i18next/react-i18next 明星react-i18next ⭐️ --- 哇!如此長的有用專案清單。 我知道您有更多想法,分享它們,讓我們一起建造:D 現在就這些了! 在開展新專案時,開發人員經驗至關重要,這就是為什麼有些專案擁有龐大的社區,而有些則沒有。 React 社群非常龐大,所以成為這些社群的一部分,並使用這些開源專案將您的專案提升到一個新的水平。 祝你有美好的一天!直到下一次。 在 GitHub 上關注我。 https://github.com/Anmol-Baranwal 請關注 CopilotKit 以了解更多此類內容。 https://dev.to/copilotkit --- 原文出處:https://dev.to/copilotkit/libraries-you-should-know-if-you-build-with-react-1807

100% AI 驅動的 Web 開發工作流程,與 Devin 一樣出色:MAGE x Aider

長話短說 ---- [Devin](https://www.youtube.com/watch?v=fjHtjT7GO1c) ,這位自稱「第一個」完全自主的軟體工程師剛剛出現,並引起了很多關注。 它尚未公開,但透過幾個開源工具,您現在可以獲得類似的 Web 開發體驗,而且成本可能只是一小部分。 {% 嵌入 https://www.youtube.com/watch?v=DXunbNBpgZg %} 在其 CLI 中使用[Wasp 的 AI 功能](https://wasp.sh),您可以透過簡單的提示產生全端 Web 應用程式程式碼庫。然後,在[Aider](https://aider.chat)的幫助下透過加入功能和除錯來迭代它。 在這兩個人工智慧代理的幫助下,您可以增強全端應用程式的開發,而無需編寫一行程式碼(如果您不想)。 請繼續閱讀有關如何開始的詳細說明! --- ![星星](https://res.cloudinary.com/practicaldev/image/fetch/s--2jk6M804--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j3a8gkl9fcs0a8rl4zsq.gif) 順便說一句,Wasp 是建立全端 Web 應用程式的最快方法,而且它也恰好內建了 AI 生成 - 而且它是免費和開源的! 您可以透過[在 GitHub 上為我們的儲存庫加註星標](https://www.github.com/wasp-lang/wasp)來支持我們。它幫助我們建立更多東西並創造更多像這樣很酷的內容🙏 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hk4emh8rr8q4j35sxud.gif) {% cta https://www.github.com/wasp-lang/wasp %} 連 Ron 也會在 GitHub 上為 Wasp 加註星標 🤩 {% endcta %} --- 德文到底是誰? ------- 您可能已經看到和聽過圍繞 Devin 的炒作,他自稱是「第一個」完全自主的軟體工程師。 如果沒有,請觀看下面的宣傳影片: {% 嵌入 https://www.youtube.com/watch?v=fjHtjT7GO1c %} 儘管 Devin 絕對不是同類中的第一個人工智慧編碼助手,但它的推出仍然引起了許多人的注意。簡而言之,這就是 Devin 所做的: - 接受提示 - 制定逐步計劃 - 在具有程式碼編輯器、終端、瀏覽器和聊天介面的時尚 UI 中展示其工作 - 能夠迭代現有的程式碼庫 儘管有其他類似的人工智慧編碼代理,其中一些像 GPT-Pilot 是開源的,但 Devin 使用內建所有必要工具的流暢 UI 使其脫穎而出。此外,它能夠迭代現有程式碼庫,這使其與大多數類似工具(Aider 除外)區分開來。 那麼,德文真的那麼令人印象深刻嗎? 是和不是。正如著名 AI YouTuber [Matthew Berman](https://www.youtube.com/@matthew_berman)在他關於 Devin 的影片中指出的那樣,Devin 最令人印象深刻的事情可能是他們的發布的成功。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5mrfmizjkew07qrd8qw.png) 但伯曼也指出了一些與他們的行銷主張不一致的地方: 1. Devin 絕對不是同類中的第一個。 [Mage](https://useMage.ai) 、 [Aider](https://aider.chat)和[GPT-Pilot](https://github.com/Pythagora-io/gpt-pilot)等類似工具已經存在。 2. 他們對效能基準的比較(如上圖所示)並不能真正被認真對待,因為Devin 是一個可以迭代和執行多個任務的代理,而它所比較的 LLM,如GPT-4,只是「零樣本」 (即他們嘗試一次才能得到正確的答案)。為了公平比較,Devin 應該與其他代理人進行比較,例如 GPT-Pilot、MetaGPT、Mage 等。 另外,Devin 實際上是建立在 OpenAI 的 GPT-4 API 之上的。所以,是的,他們在其之上建置的一些工具非常令人印象深刻,並且將加快編碼工作流程,但底層模型與像您和我這樣的開發人員可以存取的東西完全相同。 這意味著,透過結合幾個可用的開源工具,您現在可以獲得與 Devin 非常相似的結果,而無需等待早期預覽存取,並且成本可能只是其一小部分。 現在就讓我們來看看吧! Wasp AI x Aider — 全端 Web 應用程式的開源「Devin」替代品 ------------------------------------------ 幾個月前,我們發布了[Mage](https://usemage.ai) ( **Magic** **App** **Generator** ),這是一個實驗平台,用於透過簡單的提示生成全端 Web 應用程式。自發布以來,Mage 已被用來產生超過 40k 個應用程式! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxzoa3be0u5qghqmvpd8.png) Mage 使用[Wasp(一個全端 React、Node 和 Prisma 框架)](https://wasp.sh)來產生比大多數編碼助理更好的全端應用程式。到底是為什麼呢?這是因為 Wasp 使用聲明性設定檔來定義應用程式的功能。 這個設定檔為Wasp 的編譯器提供了將客戶端和伺服器程式碼「黏合」在一起所需的指令,並處理一堆樣板程式碼,因此您和AI 都不必處理諸如身份驗證、路由、端點、伺服器之類的編碼配置等 ``` // wasp config file app TodoApp { wasp: { version: "^0.13.0" }, auth: { userEntity: User, methods: { usernameAndPassword: {} }, } } entity User {=psl id Int @id @default(autoincrement()) tasks Task[] psl=} // rest of the config file... ``` 查看上面的範例,了解如何使用 Wasp 編寫全端 Auth。很容易,對吧?現在想像一下,對於 Mage 或任何其他人工智慧編碼助理來說,編寫 Wasp 程式碼是多麼容易。 另外,由於 Wasp 設定檔的結構已經類似於一組指令,因此它允許 Mage 以與 Devin 類似的方式建立計劃。 這就是 Mage 真正的閃光點,它可以快速且廉價地建立功能齊全的全端 Web 應用程式原型。 Mage 的唯一缺點是它在終端中不可用,而且您無法進一步迭代生成的程式碼庫。 現在情況改變了。隨著新的 Wasp 更新,Mage 的所有功能都被打包到 CLI 中。您只需[安裝 Wasp](https://wasp-lang.dev/docs/quick-start)並執行`wasp new` ,您就可以透過命令列提示產生一個新的全端應用程式! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uthik90clhytebvyndh0.png) 之後,您可以使用[Aider](https://aider.chat) ,這是一個命令列工具,可讓您與 GPT-3.5/GPT-4 進行配對編程,以迭代生成的程式碼庫並建立一系列很酷的新功能。 還不相信嗎?觀看這個很酷的宣傳影片,向您展示這一切是如何運作的: {% 嵌入 https://www.youtube.com/watch?v=DXunbNBpgZg %} 如果這看起來很酷,並且您想在這些工具的幫助下開始建立自己的全端 Web 應用程式,請按照以下說明進行操作! CLI 中的 Wasp AI -------------- [安裝 Wasp](https://wasp-lang.dev/docs/quick-start)後,前往終端並執行`wasp new` 這樣做將為您提供一個可供選擇的全端入門模板清單。你會想要: - 從選項清單中選擇`[5] ai-generated` - 輸入您的應用程式的描述 - 選擇您想要用於這一代的 GPT 模型和創造力水平 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iyyrvrjg4ykvftutp5k2.png) 使用這些生成設定可能會產生不同的結果,因此,如果生成的應用程式不是您第一次尋找的內容,請調整它們並重試。 並且不必太擔心透過 OpenAI API 產生的成本。由於 Wasp 利用 DSL 並為我們管理大量樣板文件,因此它顯著減少了 GPT 必須產生的程式碼量。 例如,當我們混合使用 GPT4 和 GPT3.5(預設選項)時,一個具有 Wasp AI 的應用程式通常消耗大約 25k 到 60k 代幣,每個應用程式大約消耗**0.1 到 0.2 美元**!如果我們只使用 GPT4 來執行它,那麼成本是 10 倍,這意味著它將花費大約**1 到 2 美元**。這仍然比大多數其他 AI 編碼代理便宜得多,後者每代的成本通常約為 15-40 美元。 🤯 哦,「gpt-4-1106-preview」指的是 OpenAI 的新 GPT-4-turbo 模型。因此,它比完全使用 GPT-4 更快、更便宜。 Wasp AI(和[Mage](https://usemage.ai) )使用 GPT-4 進行規劃 + GPT-3.5-turbo 進行程式碼生成的組合,我們發現它對於簡單的應用程式來說效果出奇的好。如果您的目標是複雜的應用程式,我們建議完全使用 GPT-4,因為它能夠更好地處理更高的複雜性。請注意,GPT-4 將需要更長的時間。 繼續與 AI 迭代…der ------------- 在 Mage 的初始版本中,我們收到了很多問題,詢問是否有“除錯助手”,或者在初始輸出後繼續使用 AI 生成更多功能的方法。 雖然 Wasp AI 無法做到這一點,但我們開始探索其他具有除錯功能的 AI 編碼助手,最終我們非常喜歡[Aider 的](https://aider.chat/)工作流程和效能。另外,除了尚未向公眾發布的 Devin 之外,Aider 是目前唯一允許您迭代現有程式碼庫的 AI 編碼工具。 **所以,這使得 Wasp AI + Aider 成為完美的組合!** --- ![星星](https://res.cloudinary.com/practicaldev/image/fetch/s--2jk6M804--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j3a8gkl9fcs0a8rl4zsq.gif) 順便說一句,Wasp 是免費且開源的,所以如果您喜歡我們正在做的事情,請考慮[在 Github 上給我們一顆星](https://github.com/wasp-lang/wasp)! ![黃蜂](https://res.cloudinary.com/practicaldev/image/fetch/s--5pwnEx10--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lz3ok1dpfkscsoo0n2om.gif) {% cta https://www.github.com/wasp-lang/wasp %} ⭐️ 丟黃蜂一顆星星 🙏 {% endcta %} --- 使用 Wasp AI 產生全端應用程式後,您可以透過 Aider 使用自然語言來產生新功能或偵錯目前程式碼中的問題。 就是這樣: 1. 安裝[幫助](https://aider.chat) ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/avh771m902u6ukkbd1p5.png) 2. 在 Wasp 專案目錄中的命令列中執行`aider` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ut16cyi6tlouuk9529tb.png) 3. `/add`您希望 Aider 使用的文件 4. 告訴 Aider 你想要它做什麼,例如在表單中加入“小睡次數”字段 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/af0vm9ngfilbgj9170ik.png) 5. 然後,Aider 將規劃一個行動方案,並將這些變更作為 git 提交應用程式。如果您不喜歡更改,請執行`/undo`撤銷提交 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4t0w7txe4xjsealfczke.png) 6. 如果您在嘗試使用`wasp start`執行程式碼時遇到錯誤,請將錯誤複製並貼上到聊天中,讓 Aider 為您解決。確保您已將錯誤引用的文件新增至聊天(請參閱步驟 3)! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u8nc9sty41xbgrm7xwfr.png) 7. 如果您在使用 Aider 時需要更多幫助,請查看他們的[網站](https://aider.chat)或在 Aider 中執行`/help`以獲取命令列表 未來就在這裡 ------ 透過[Wasp AI](https://wasp.sh) ,我們最終將 Mage 的 AI 輔助全端應用腳手架能力加入到 Wasp 的 CLI 中。利用 GPT-4 和其他 OpenAI 模型的強大功能,用它來啟動您的下一個全端應用程式創意。 如果您想在 AI 幫助下繼續產生功能或直接從終端進行偵錯,請使用我們上面概述的 Aider 來保持流程繼續進行。 編碼的未來確實就在這裡。嘗試一下,讓我們知道您的想法! --- 原文出處:https://dev.to/wasp/a-100-ai-driven-workflow-thats-probably-as-good-as-devin-4c67

建立完美人工智慧應用所需的所有工具。

過去十年來,人工智慧世界取得了長足發展。 人工智慧無所不在,從語音助理到軟體開發,如果我們正確使用它,它會非常有幫助。 在這樣的世界中,製作 AI 應用程式是有利可圖的,因此我在這裡介紹 25 個開源專案,您可以使用它們來製作 AI 應用程式並將其提升到新的水平。 其中有一些令人興奮的概念,例如使用語音合成與 3D 角色進行互動式溝通。堅持到底。 將會有大量的資源、文章、專案想法、指南等可供參考。 讓我們涵蓋這一切! --- 1. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ---------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/deak7rre409rzv5j5viv.png) Taipy 是一個開源 Python 庫,可用於輕鬆的端到端應用程式開發,具有假設分析、智慧管道執行、內建調度和部署工具。 我相信你們大多數人都不明白 Taipy 用於為基於 Python 的應用程式建立 GUI 介面並改進資料流管理。 因此,您可以繪製資料集的圖表,並使用類似 GUI 的滑桿來提供使用其他實用功能來處理資料的選項。 雖然 Streamlit 是一種流行的工具,但在處理大型資料集時,其效能可能會顯著下降,這使得它在生產級使用上不切實際。 另一方面,Taipy 在不犧牲性能的情況下提供了簡單性和易用性。透過嘗試 Taipy,您將親身體驗其用戶友好的介面和高效的資料處理。 在底層,Taipy 利用各種函式庫來簡化開發並增強功能。 ![圖書館](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9xts3nof4uapr7dakrl.png) 開始使用以下命令。 ``` pip install taipy ``` 我們來談談最新的[Taipy v3.1 版本](https://docs.taipy.io/en/latest/relnotes/)。 最新版本使得在 Taipy 的多功能零件物件中可視化任何 HTML 或 Python 物件成為可能。 這意味著[Folium](https://python-visualization.github.io/folium/latest/) 、 [Bokeh](https://bokeh.org/) 、 [Vega-Altair](https://altair-viz.github.io/)和[Matplotlib](https://matplotlib.org/)等程式庫現在可用於視覺化。 這也帶來了對[Plotly python 的](https://plotly.com/python/)原生支持,使繪製圖表變得更加容易。 ![陰謀蟒蛇](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdewvex88md09hvu3s80.png) 他們還使用分散式運算提高了效能,但最好的部分是 Taipy,它的所有依賴項現在都與 Python 3.12 完全相容,因此您可以在使用 Taipy 進行專案的同時使用最新的工具和程式庫。 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 例如,您可以看到[聊天演示](https://docs.taipy.io/en/release-3.1/gallery/llm/5_chatbot/),它使用 OpenAI 的 GPT-4 API 來產生對您的訊息的回應。您可以輕鬆更改程式碼以使用任何其他 API 或模型。 ![聊天演示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kug1mclhmzyad0hjchif.png) 另一個有用的事情是,Taipy 團隊提供了一個名為[Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/)的 VSCode 擴充功能來加速 Taipy 應用程式的建置。 ![太皮工作室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc1umm5hcxes0ydbuspb.png) 您也可以使用 Taipy 雲端部署應用程式。 如果您想閱讀部落格來了解程式碼庫結構,您可以閱讀 HuggingFace 的[使用 Taipy 在 Python 中為您的 LLM 建立 Web 介面](https://huggingface.co/blog/Alex1337/create-a-web-interface-for-your-llm-in-python)。 嘗試新技術通常很困難,但 Taipy 提供了[10 多個演示教程](https://docs.taipy.io/en/release-3.1/gallery/),其中包含程式碼和適當的文件供您遵循。 例如,一些現場演示範例: - [新冠儀表板](https://covid-dashboard.taipy.cloud/Country) - [推文生成](https://tweet-generation.taipy.cloud/) - [資料視覺化](https://production-planning.taipy.cloud/Data-Visualization) - [即時人臉辨識](https://face-recognition.taipy.cloud/) Taipy 在 GitHub 上有 7k+ Stars,並且處於`v3`版本,因此它們正在不斷改進。 ![利桑·阿爾·蓋布](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m8etards1b7qfpbk2scr.png) https://github.com/Avaiga/taipy Star Taipy ⭐️ --- 2. [Supabase](https://github.com/supabase/supabase) - 開源 Firebase 替代品。 ---------------------------------------------------------------------- ![蘇帕貝斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/an2b9aqiij0j2tml1c6b.png) 要建立AI應用程式,您需要一個後端,而Supabase作為優秀的後端服務提供者可以滿足這一需求。 開始使用以下 npm 指令 (Next.js)。 ``` npx create-next-app -e with-supabase ``` 這就是使用 CRUD 操作的方式。 ``` import { createClient } from '@supabase/supabase-js' // Initialize const supabaseUrl = 'https://chat-room.supabase.co' const supabaseKey = 'public-anon-key' const supabase = createClient(supabaseUrl, supabaseKey) // Create a new chat room const newRoom = await supabase .from('rooms') .insert({ name: 'Supabase Fan Club', public: true }) // Get public rooms and their messages const publicRooms = await supabase .from('rooms') .select(` name, messages ( text ) `) .eq('public', true) // Update multiple users const updatedUsers = await supabase .from('users') .eq('account_type', 'paid') .update({ highlight_color: 'gold' }) ``` 您可以閱讀[文件](https://supabase.com/docs)。 您可以使用身份驗證、即時、邊緣功能、儲存等功能建立一個速度極快的應用程式。 Supabase 涵蓋了這一切! Supabase 也提供了幾個入門套件,例如[Nextjs 與 LangChain](https://github.com/langchain-ai/langchain-nextjs-template) 、 [Stripe 與 Nextjs](https://github.com/vercel/nextjs-subscription-payments)或[AI Chatbot](https://github.com/supabase-community/vercel-ai-chatbot) 。 Supabase 在 GitHub 上擁有超過 63,000 顆星,並且擁有大量提交超過 27,000 次的貢獻者。 https://github.com/supabase/supabase 明星 Supabase ⭐️ --- 3. [Chatwoot](https://github.com/chatwoot/chatwoot) - 即時聊天、電子郵件支援、全通路服務台並擁有您的資料。 -------------------------------------------------------------------------------- ![查特伍德](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bpgjh0hdr5u5cpf2kdn7.png) Chatwoot 連接流行的客戶溝通管道,如電子郵件、網站即時聊天、Facebook、Twitter、WhatsApp、Instagram、Line 等。這有助於您從單一儀表板跨管道提供一致的客戶體驗。 這在各種情況下都可能很重要,例如當您圍繞人工智慧應用程式建立社群時。 ![聊天特烏功能](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0u3z2cdqvzhqb94h5zm.png) 您可以閱讀[文件](https://www.chatwoot.com/docs/product)來發現各種整合選項,以便更輕鬆地管理整個生態系統。 他們在每個整合中都有非常詳細的文件和快照範例,例如[帶有 WhatsApp Cloud API 的 WhatsApp 通道](https://www.chatwoot.com/docs/product/channels/whatsapp/whatsapp-cloud)。您可以根據需要一鍵式或自架部署到 Heroku。 他們在 GitHub 上擁有 18k+ Stars,並且發布了`v3.6`版本。 https://github.com/chatwoot/chatwoot 明星 Chatwoot ⭐️ --- 4. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------ ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea ``` 這是整合 CopilotTextArea 的方法。 ``` import { CopilotTextarea } from "@copilotkit/react-textarea"; import { useState } from "react"; export function SomeReactComponent() { const [text, setText] = useState(""); return ( <> <CopilotTextarea className="px-4 py-4" value={text} onValueChange={(value: string) => setText(value)} placeholder="What are your plans for your vacation?" autosuggestionsConfig={{ textareaPurpose: "Travel notes from the user's previous vacations. Likely written in a colloquial style, but adjust as needed.", chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 20, stop: [".", "?", "!"], }, }, }, }} /> </> ); } ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)。 基本概念是在幾分鐘內建立可用於基於 LLM 的全端應用程式的 AI 聊天機器人。 https://github.com/CopilotKit/CopilotKit Star CopilotKit ⭐️ --- 5. [DALL·E Mini](https://github.com/borisdayma/dalle-mini) - 根據文字提示產生圖像。 ------------------------------------------------------------------------ ![從文字生成圖像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mco3wf4nzc5j245aizpu.png) OpenAI 擁有第一個令人印象深刻的模型,用於使用 DALL·E 生成圖像。 Craiyon/DALL·E mini 嘗試使用開源模型重現這些結果。 如果您想知道這個名字,DALL-E mini 應母公司的要求更名為 Craiyon,並以更易於存取的網路應用程式格式使用類似的技術。 您可以在[Craiyon](https://www.craiyon.com/)上使用該模型。 ![蠟筆](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ntjhsr9f7t1y0idlysjw.png) 開始使用以下命令(用於開發)。 ``` pip install dalle-mini ``` 您可以閱讀[文件](https://github.com/borisdayma/dalle-mini?tab=readme-ov-file#development)。 您可以閱讀[DALL-E Mini 解釋](https://wandb.ai/dalle-mini/dalle-mini/reports/DALL-E-Mini-Explained-with-Demo--Vmlldzo4NjIxODA)來了解有關資料集、架構和所涉及演算法的更多資訊。 您可以閱讀[最佳真實感 AI 圖像和提示的終極指南](https://www.craiyon.com/blog/ultimate-guide-best-ai-art-photorealistic-images-and-prompts),以便更好地理解優質資源。 DALL·E Mini 在 GitHub 上擁有 14k+ Stars,目前處於`v0.1`版本。 https://github.com/borisdayma/dalle-mini 明星 DALL·E Mini ⭐️ --- 6. [Deepgram](https://github.com/deepgram) - 將語音 AI 建置到您的應用程式中。 --------------------------------------------------------------- ![深度圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/32enxrtcwqk6g81eazay.png) 從新創公司到 NASA,Deepgram API 每天都用於轉錄和理解數百萬分鐘的音訊。快速、準確、可擴展且經濟高效。 它為開發人員提供語音到文字和音訊智慧模型。 ![深度圖選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rdc3tqg7fvt3sw6ktle7.png) 儘管他們有免費增值模式,但免費套餐的限制足以讓您入門。 可視化效果更上一層樓。您可以檢查即時串流媒體回應或音訊檔案並比較音訊的智慧程度。 ![串流媒體](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wcvzzrqzn94gxe594hf.png) ![情緒分析](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uw6wkhzg7g6vgq7lphri.png) 您可以閱讀[文件](https://developers.deepgram.com/docs/introduction)。 您也可以閱讀 Deepgram 撰寫的[關於如何將語音辨識新增至您的 React 和 Node.js 專案的](https://deepgram.com/learn/how-to-add-speech-recognition-to-your-react-project)範例部落格。 如果您想嘗試 API 來親自了解模型的靈活性,請查看他們的[API Playground](https://playground.deepgram.com/?smart_format=true&language=en&model=nova-2) 。 https://github.com/deepgram 明星 Deepgram ⭐️ --- 7. [InvokeAI](https://github.com/invoke-ai/InvokeAI) - 領先的穩定擴散模型創意引擎。 --------------------------------------------------------------------- ![呼叫人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a1uira3ta4ufauefp0ff.png) 關於 InvokeAI 是 Stable Diffusion(開源文字到圖像和圖像到圖像生成器)的實現。 它可以在 Windows、Mac 和 Linux 機器上執行,並在 RAM 低至 4 GB 的 GPU 卡上執行。 此解決方案提供業界領先的WebUI,支援透過CLI進行終端使用,並作為多種商業產品的基礎。 ![呼叫ai](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5802r0wtxlbkqdtclce.png) 您可以閱讀有關[安裝和硬體要求](https://invoke-ai.github.io/InvokeAI/installation/INSTALLATION/)、[如何安裝不同型號](https://invoke-ai.github.io/InvokeAI/installation/050_INSTALLING_MODELS/)以及最重要的[自動安裝的資訊](https://invoke-ai.github.io/InvokeAI/installation/010_INSTALL_AUTOMATED/)。 令人興奮的功能是能夠使用另一個圖像生成圖像,如[文件](https://invoke-ai.github.io/InvokeAI/features/IMG2IMG/)中所述。 InvokeAI 在 GitHub 上有近 21k 顆星, https://github.com/invoke-ai/InvokeAI 明星 InvokeAI ⭐️ --- 8. [OpenAI](https://github.com/openai) - 您所需要的一切。 ------------------------------------------------- ![開放人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k02duibi54zzzddck91z.png) Gemini by Google 和 OpenAI 非常受歡迎,但我們在此列表中專注於 OpenAI。 如果您想了解更多訊息,可以在 Medium 上閱讀[Google AI Gemini API in web using React 🤖](https://generativeai.pub/google-gemini-api-in-web-using-react-7e5bf0bf0abc) 。這很簡單,也很切中要害。 透過 OpenAI,您可以使用 DALL·E(根據文字描述建立原創、逼真的圖像和藝術)、Whisper(語音辨識模型)和 GPT-4。在評論中告訴我們關於索拉的事吧! 您可以使用簡單的 API 開始建置。 ``` completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What are some famous astronomical observatories?"} ] ) ``` 您可以閱讀[文件](https://platform.openai.com/docs/introduction)。它提供瞭如此多的選項來建立非常酷的東西! ![文件概述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o9yi0tar96jxi4pkni81.png) 甚至 Stripe 也使用 GPT-4 來改善使用者體驗。 例如,您可以建立[Assistant 應用程式](https://platform.openai.com/docs/assistants/overview)並查看[API 遊樂場](https://platform.openai.com/playground/p/default-chat?model=text-davinci-003)以更好地理解它。 ![GPT-3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t89658h4drhy4a8zf3xs.png) 如果您需要指南,可以閱讀 Dzone 的[Integrating ChatGPT With ReactJS](https://dzone.com/articles/integrating-chatgpt-with-reactjs-a-comprehensive-g) 。 其間,OpenAI收購了Sora,獲得了壟斷地位。你怎麼認為? https://github.com/openai 明星 OpenAI ⭐️ --- 9. [DeepFaceLab](https://github.com/iperov/DeepFaceLab) - 用於建立深度贗品的領先軟體。 ------------------------------------------------------------------------ ![深臉實驗室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g32stb7uo201msv3jn8f.png) DeepFaceLab 是製作 Deepfakes 的頂級開源工具。 Deepfakes 是透過深度學習製作的經過修改的圖像和影片。它們經常被用來交換圖片或剪輯中的臉孔,有時是為了開玩笑,但也有出於有害的原因。 DeepFaceLab,用Python建置,是一個強大的deepfake工具。它可以改變媒體中的臉孔,甚至消除皺紋和老化跡象。 這些是您可以使用 DeepFaceLab 執行的一些操作。 - 換臉。 ![更換臉部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86jnuec9l6eaalwf9w51.png) - [臉部抗衰老 - YouTube](https://www.youtube.com/watch?v=Ddx5B-84ebo) 。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/axh2e6117felh4zhoh3p.png) - 更換頭部。 ![更換頭部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nyvbncox7k1u28nait50.png) - 操縱嘴唇。 您可以使用這個基本教學來了解[如何有效地使用 DeepFaceLab](https://www.youtube.com/watch?v=kOIMXt8KK8M)來完成這些事情。 您可以在[YouTube](https://www.youtube.com/channel/UCGf4OlX_aTt8DlrgiH3jN3g/videos)上看到使用此 DeepLab 演算法的影片。 不幸的是,DeepFaceLab 中沒有「讓一切正常」按鈕,但值得根據您的特定需求了解其工作流程。 儘管它於 2023 年 11 月 9 日存檔,在 GitHub 上有近 44k+ 顆星,但由於其大量的教程和可靠的演算法,它仍然是您的 AI 應用程式的可靠選擇。 https://github.com/iperov/DeepFaceLab 明星 DeepFaceLab ⭐️ --- 10. [Detectron2](https://github.com/facebookresearch/detectron2) - 基於 PyTorch 的模組化物件偵測庫。 ---------------------------------------------------------------------------------------- ![探測器2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jxe7wuf8v8y7e039ziel.png) Detectron2 是 Facebook AI Research 的下一代函式庫,提供最先進的偵測和分割演算法。它是 Detectron 和 maskrcnn-benchmark 的後繼者。 它支援 Facebook 上的多個電腦視覺研究專案和生產應用程式。 使用此[YouTube 教學](https://www.youtube.com/watch?v=eUSgtfK4ivk)將 Detectron2 與 Facebook 開發者倡導者的機器學習結合使用。 Detectron2 旨在支援各種最先進的物件偵測和分割模型,同時也適應不斷發展的前沿研究領域。 您可以閱讀[如何入門](https://detectron2.readthedocs.io/en/latest/tutorials/getting_started.html)以及 [元博客](https://ai.meta.com/blog/-detectron2-a-pytorch-based-modular-object-detection-library-/),其中深入介紹了 Detectron 的目標。 舊版的 Detectron 使用的是 Caffe,因此很難與後來結合 Caffe2 和 PyTorch 的程式碼變更一起使用。為了回應社群回饋,Facebook AI 發布了 Detectron2 作為更新的、更容易使用的版本。 Detectron2 配備了用於物件偵測的先進演算法,例如 DensePose 和全景特徵金字塔網路。 此外,Detectron2 還可以進行語義分割和全景分割,這有助於更準確地偵測和分割影像和影片中的物件。 Detectron2 不僅支援使用邊界框和實例分割遮罩進行物件偵測,還可以預測人體姿勢,與 Detectron 類似。 它們在 GitHub 儲存庫上擁有 28k+ Stars,並在 GitHub 上被 1.6k+ 開發人員使用。 https://github.com/facebookresearch/detectron2 Star Detectron2 ⭐️ --- [11.FastAI-](https://github.com/fastai/fastai)深度學習庫。 ---------------------------------------------------- ![你真好](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qvxqd22q3qamqtvwe6p.png) Fastai 是一個多功能的深度學習庫,旨在滿足從業者和研究人員的需求。它為從業者提供了高級元件,以便他們在常見的深度學習任務中快速獲得一流的結果。 同時,它為研究人員提供低階元件來實驗和開發新方法。 Detectron2 透過其分層架構實現了易用性和靈活性之間的平衡。 該架構將複雜的深度學習技術分解為可管理的抽象,簡潔地利用了 Python 的動態特性和 PyTorch 的靈活性。 它建構在較低層級 API 的層次結構之上,這些 API 提供可組合的建構塊。這樣,想要重寫部分高級 API 或加入特定行為以滿足其需求的用戶無需學習如何使用最低級別。 ![架構API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kfooe2mxrh3xplcxeg75.png) [安裝 pyTorch](https://pytorch.org/get-started/locally/)後即可開始使用以下命令。 ``` conda install -c fastai fastai ``` 您可以閱讀[文件](https://docs.fast.ai/)。 它們針對初學者、中級和專家的[教程](https://docs.fast.ai/tutorial.html)有不同的起點。 如果您想為 FastAI 做出貢獻,您應該閱讀他們的[程式碼風格指南](https://docs.fast.ai/dev/style.html)。 如果您更喜歡影片,可以在 YouTube 上觀看傑里米霍華德 (Jeremy Howard) 撰寫的[課程“0”:程式設計師實用深度學習 (fastai)](https://www.youtube.com/watch?v=gGxe2mN3kAg) 。 它們在 GitHub 上擁有超過 25,000 顆星,並已被 GitHub 上超過 16,000 名開發人員使用。 https://github.com/fastai/fastai 明星 FastAI ⭐️ --- 12.[穩定擴散](https://github.com/CompVis/stable-diffusion)- 潛在文字到影像擴散模型。 -------------------------------------------------------------------- ![穩定擴散](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/63worvztgs1cmy2owtkf.png) > 什麼是穩定擴散? 穩定擴散是指生成模型中使用的一種技術,特別是在文字到圖像合成的背景下,其中將資訊從文字描述轉移到圖像的過程是逐漸且平滑地完成的。 在潛在文字到影像擴散模型中,穩定擴散可確保來自文字描述的訊息在整個模型的潛在空間中一致地擴散或傳播。這種擴散過程有助於產生與給定文字輸入相符的高品質和逼真的圖像。 穩定的擴散機制確保模型在生成過程中不會出現突然的跳躍或不穩定。我希望這能解決問題! 下載和採樣穩定擴散的簡單方法是使用[擴散器庫](https://github.com/huggingface/diffusers/tree/main#new--stable-diffusion-is-now-fully-compatible-with-diffusers)。 ``` # make sure you're logged in with `huggingface-cli login` from torch import autocast from diffusers import StableDiffusionPipeline pipe = StableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", use_auth_token=True ).to("cuda") prompt = "a photo of an astronaut riding a horse on mars" with autocast("cuda"): image = pipe(prompt)["sample"][0] image.save("astronaut_rides_horse.png") ``` 您可以閱讀[研究論文](https://ommer-lab.com/research/latent-diffusion-models/)以及有關[穩定擴散影像修改](https://github.com/CompVis/stable-diffusion?tab=readme-ov-file#image-modification-with-stable-diffusion)的更多資訊。 例如,這是輸入。 ![輸入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zpvxxhrrvthd8w1a0rrl.png) 這是放大一點後的輸出。 ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gzqvd06kse8ifhzry0la.png) Stable Diffusion v1 是一種特定的模型配置,它採用 860M UNet 和 CLIP ViT-L/14 文字編碼器進行擴散模型,並具有下採樣因子 8 自動編碼器。該模型在 256x256 影像上進行了預訓練,隨後在 512x512 影像上進行了微調。 他們在 GitHub 儲存庫上擁有大約 64k+ Stars。 https://github.com/CompVis/stable-diffusion 恆星穩定擴散 ⭐️ --- 13. [Mocap Drones](https://github.com/jyjblrd/Mocap-Drones) - 用於房間規模追蹤的低成本動作捕捉系統。 --------------------------------------------------------------------------------- ![動作捕捉無人機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hq4hnzbx2wtxboehosi.png) 該專案需要 SFM(運動結構)OpenCV 模組,這需要您從原始程式碼編譯 OpenCV。 從`computer_code`目錄中,執行此命令來安裝節點相依性。 ``` yarn install yarn run dev // to start the web server. ``` 您將獲得前端介面的 URL 視圖。 開啟一個單獨的終端機視窗並執行命令`python3 api/index.py`來啟動後端伺服器。此伺服器負責接收攝影機串流並執行動作捕捉計算。 架構如下。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jt6e3f32scak65wfdp8s.png) 您可以觀看此[YouTube 影片](https://www.youtube.com/watch?v=0ql20JKrscQ)來了解 Mocap 無人機的工作原理,也可以觀看該專案所有者的[部落格](https://joshuabird.com/blog/post/mocap-drones)。 https://www.youtube.com/watch?v=0ql20JKrscQ 您可以閱讀[文件](https://github.com/jyjblrd/Mocap-Drones?tab=readme-ov-file#runing-the-code)。 這是一個最近的開源專案,在 GitHub 儲存庫上擁有 900 多個 star。 https://github.com/jyjblrd/Mocap-Drones 明星動捕無人機 ⭐️ --- 14. [Whisper Speech](https://github.com/collabora/WhisperSpeech) - 透過反轉 Whisper 建構的文字轉語音系統。 ------------------------------------------------------------------------------------------- ![低聲講話](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpawahh7aqsh1pnsnu76.png) 該模型與穩定擴散類似,但用於語音,功能強大且高度可自訂。 該團隊確保使用經過適當許可的語音錄音,並且所有程式碼都是開源的,使該模型對於商業應用程式來說是安全的。 目前,這些模型是在英語 LibreLight 資料集上進行訓練的。 您可以進一步研究[架構](https://github.com/collabora/WhisperSpeech?tab=readme-ov-file#architecture)。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hnfqick2y1yoxgkmwlk6.png) 您可以聽到[範例聲音](https://github.com/collabora/WhisperSpeech/assets/107984/aa5a1e7e-dc94-481f-8863-b022c7fd7434)並使用[colab](https://colab.research.google.com/drive/1xxGlTbwBmaY6GKA24strRixTXGBOlyiw)自行嘗試。 它們相當新,在 GitHub 上有大約 3k+ 的星星。 https://github.com/collabora/WhisperSpeech 星語語音 ⭐️ --- 15. [eSpeak NG](https://github.com/espeak-ng/espeak-ng) - 支援一百多種語言和口音的語音合成器。 ---------------------------------------------------------------------------- ![電子說](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a28zdxcr1jthb5bht2fi.png) eSpeak NG 是一款緊湊型開源軟體文字語音合成器,適用於 Linux、Windows、Android 和其他作業系統。它支援 100 多種語言和口音。它基於 Jonathan Duddington 建立的 eSpeak 引擎。 您可以閱讀各種系統上的[安裝指南](https://github.com/espeak-ng/espeak-ng/blob/master/docs/guide.md)。 對於類似 Debian 的發行版(例如 Ubuntu、Mint 等)。您可以使用此命令。 ``` sudo apt-get install espeak-ng ``` 您可以查看[支援的語言](https://github.com/espeak-ng/espeak-ng/blob/master/docs/languages.md)清單、閱讀[文件](https://github.com/espeak-ng/espeak-ng/tree/master?tab=readme-ov-file#documentation)並查看[功能](https://github.com/espeak-ng/espeak-ng/tree/master?tab=readme-ov-file#features)。 該模型將文字轉換為音素程式碼,表明其作為另一個語音合成引擎前端的潛在能力。 他們在 GitHub 上有 2700+ 顆星星, https://github.com/espeak-ng/espeak-ng 明星 eSpeak NG ⭐️ --- 16.[聊天機器人 UI](https://github.com/mckaywrigley/chatbot-ui) - 每個模型的人工智慧聊天。 ------------------------------------------------------------------------ ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k8smowkv6scq9lujjeab.png) 我們都使用過 ChatGPT,這個專案可以幫助我們為任何 AI 聊天機器人設定使用者介面。少一麻煩! 你可以閱讀[安裝指南](https://github.com/mckaywrigley/chatbot-ui?tab=readme-ov-file#1-install-docker)來安裝 docker、supabase CLI 和其他東西。 您可以閱讀<a href="">文件</a>並查看[演示](https://twitter.com/mckaywrigley/status/1738273242283151777?s=20)。 這在底層使用了 Supabase (Postgres),這就是我們之前討論它的原因。 我沒有討論 Vercel AI 聊天機器人,因為它與此機器人相比是一個相當新的比較。 Chatbot UI 在 GitHub 上擁有大約 25k+ Stars,因此它仍然是開發人員為任何聊天機器人建立 UI 介面的首選。 https://github.com/mckaywrigley/chatbot-ui 明星聊天機器人 UI ⭐️ --- 17. [GPT-4 & LangChain](https://github.com/mayooear/gpt4-pdf-chatbot-langchain) - 用於大型 PDF 文件的 GPT4 和 LangChain 聊天機器人。 -------------------------------------------------------------------------------------------------------------------------- ![聊天架構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0pe0xehimhyw2mfubzu9.png) 這可用於新的 GPT-4 API 來為多個大型 PDF 檔案建立 chatGPT 聊天機器人。 該系統是使用 LangChain、Pinecone、Typescript、OpenAI 和 Next.js 建構的。 LangChain 是一個簡化可擴展 AI/LLM 應用程式和聊天機器人開發的框架。 Pinecone 用作向量存儲,用於以文字格式儲存嵌入和 PDF,以便以後檢索類似文件。 您可以閱讀涉及複製、安裝依賴項和設定環境 API 金鑰[的開發指南](https://github.com/mayooear/gpt4-pdf-chatbot-langchain?tab=readme-ov-file#development)。 您可以觀看[YouTube 影片](https://www.youtube.com/watch?v=ih9PBGVVOO4),了解如何遵循和使用它。 他們在 GitHub 上擁有 14k+ Stars,僅提交了 34 次。在您的下一個人工智慧應用程式中嘗試! https://github.com/mayooear/gpt4-pdf-chatbot-langchain 明星 GPT-4 和 Langchain ⭐️ --- 18. [Amica](https://github.com/semperai/amica) - 允許您在瀏覽器中輕鬆與 3D 角色聊天。 --------------------------------------------------------------------- ![朋友](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2nvizcn717h3cteocft5.png) Amica 是一個開源接口,用於透過語音合成和語音辨識與 3D 角色進行互動式通訊。 您可以匯入 VRM 文件,調整聲音以適合角色,並產生包含情緒表達的回應文字。 他們使用 Three.js、OpenAI、Whisper、Bakllava 等進行視覺處理。您可以閱讀[Amica 的工作原理](https://docs.heyamica.com/overview/how-amica-works)及其所涉及的[核心概念](https://docs.heyamica.com/overview/core-concepts)。 您可以克隆該存儲庫並使用它來[開始](https://docs.heyamica.com/getting-started/installation)。 ``` npm i npm run dev ``` 您可以閱讀[文件](https://docs.heyamica.com/)並查看[演示](https://amica.arbius.ai/),這真是太棒了:D ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92iv9y2auly6tvenee82.png) 您可以觀看這段簡短的影片,了解它的功能。 https://www.youtube.com/watch?v=hUxAEnFiXH8 Amica 使用 Tauri 建立桌面應用程式。別擔心,我們在此清單的後面部分介紹了金牛座。 他們在 GitHub 上有 400 多個 Star,看起來非常容易使用。 https://github.com/semperai/amica Star Amica ⭐️ --- 19. [Hugging Face Transformers](https://github.com/huggingface/transformers) - 適用於 Pytorch、TensorFlow 和 JAX 的最先進的機器學習。 ---------------------------------------------------------------------------------------------------------------------- ![擁抱變形金剛臉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3acbf1f145jihy4pqar.png) Hugging Face Transformers 可以輕鬆存取最先進的預訓練模型和演算法,用於文字分類、語言生成和問答等任務。該庫建置在 PyTorch 和 TensorFlow 之上,允許用戶以最少的努力將高級 NLP 功能無縫整合到他們的應用程式中。 憑藉大量預訓練模型和支援社區,Hugging Face Transformers 簡化了基於 NLP 的解決方案的開發。 這些模型可用於執行 100 多種語言的文本相關任務,例如文字分類、資訊擷取、問答、摘要、翻譯和文字生成。 它們還可以處理與影像相關的任務,例如影像分類、物件偵測和分割,以及與音訊相關的任務,例如語音辨識和音訊分類。 他們還可以執行各種模式的多任務處理,包括表格問答、光學字元辨識、從掃描文件中提取資訊、視訊分類和視覺問答。 您可以看到大量可用的[模型](https://huggingface.co/models)。 您可以瀏覽[文件](https://huggingface.co/docs/transformers/task_summary)以取得完整的目標並向您展示可以執行的各種任務的範例。 例如,使用管道的一種方法是用於影像分割。 ``` from transformers import pipeline segmenter = pipeline(task="image-segmentation") preds = segmenter( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg" ) preds = [{"score": round(pred["score"], 4), "label": pred["label"]} for pred in preds] print(*preds, sep="\n") ``` Transformer 得到了 Jax、PyTorch 和 TensorFlow 這三個最廣泛使用的深度學習庫的支持,並且它們之間可以無縫整合。這種整合可以使用一個庫輕鬆訓練模型,然後加載它們以使用另一個庫進行推理。 它們在 GitHub 上擁有大約 120k+ 星,並被 142k+ 大量開發人員使用。試試看! https://github.com/huggingface/transformers 明星抱臉變形金剛 ⭐️ --- 20. [LLAMA](https://github.com/facebookresearch/llama) - LLaMA 模型的推理程式碼。 ------------------------------------------------------------------------ ![來電](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bia2hnh4i79w9ljj1c4l.png) Llama 2 是 Facebook Research 開發的尖端技術,使個人、創作者、研究人員和各種規模的企業能夠使用大型語言模型負責任地實驗、創新和擴展他們的想法。 最新版本包括模型權重以及預訓練和微調 Llama 語言模型的起始程式碼,參數範圍從 7B 到 70B。 開始使用涵蓋以下步驟的[安裝指南](https://github.com/facebookresearch/llama?tab=readme-ov-file#quick-start)。 - 克隆並下載儲存庫。 - 安裝所需的依賴項。 - 從 Meta 網站註冊並下載模型。 - 執行提供的腳本來下載模型。 - 使用提供的命令在本地執行所需的模型。 您可以觀看由 ZeroToMastery 製作的關於什麼是美洲駝的[YouTube 影片](https://www.youtube.com/watch?v=OqZ0CSKzu10)。 您也可以在[Hugging Face](https://huggingface.co/meta-llama)和[Meta 官方頁面](https://llama.meta.com/)上查看型號清單和更多資訊。 Ollama 基於 llama,在 GitHub 上擁有 50k+ star。請參閱文件並使用此模型進行更多研究。 https://github.com/facebookresearch/llama 明星 LLAMA ⭐️ --- 21. [Fonoster](https://github.com/fonoster/fonoster) - Twilio 的開源替代品。 --------------------------------------------------------------------- ![福諾斯特](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pruup1a8yibepdi40fjk.png) Fonoster Inc. 研究了一種創新的可編程電信堆棧,該堆疊將為企業提供完全基於雲端的實用程序,將電話服務與網路連接起來。 根據您想要實現的目標,有多種開始方法。 開始使用以下 npm 指令。 ``` npm install @fonoster/websdk // CDN is also available ``` 例如,您可以透過以下方式將 Fonoster 與 Google Speech API 結合使用。 (您將需要服務帳戶的金鑰) ``` npm install @fonoster/googleasr @fonoster/googletts ``` 這是您可以配置語音伺服器以使用插件的方法。 ``` const { VoiceServer } = require("@fonoster/voice"); const GoogleTTS = require("@fonoster/googletts"); const GoogleASR = require("@fonoster/googleasr"); const voiceServer = new VoiceServer(); const speechConfig = { keyFilename: "./google.json" }; // Set the server to use the speech APIS voiceServer.use(new GoogleTTS(speechConfig)); voiceServer.use(new GoogleASR(speechConfig)); voiceServer.listen(async(req, res) => { console.log(req); await res.answer(); // To use this verb you MUST have a TTS plugin const speech = await res.gather(); await res.say("You said " + speech); await res.hangup(); }); ``` 您可以閱讀[文件](https://fonoster.com/docs/overview/)。 他們提供了一個足以入門的免費套餐。 他們在 GitHub 上擁有大約 6k+ 顆星,並發布了 250 多個版本。 https://github.com/fonoster/fonoster 明星 Fonoster ⭐️ --- 22. [DIPY](https://github.com/dipy/dipy) - Python 中的 paragon 3D/4D+ 成像庫。 ------------------------------------------------------------------------ ![下降](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2y1ztg24l2wc1kq5u0g.png) DIPY 是 Python 中領先的 3D/4D+ 成像庫。它包含用於空間歸一化、訊號處理、機器學習、統計分析和醫學影像視覺化的各種方法。 此外,它還包含計算解剖學的專門方法,包括擴散、灌注和結構成像。 您可以開始使用。 ``` pip install dipy // run this in python console import dipy print(dipy.get_info()) ``` 如果您使用的是 anaconda 或其他系統,您可以閱讀完整的[安裝指南](https://docs.dipy.org/stable/examples_built/quick_start/quick_start.html#sphx-glr-examples-built-quick-start-quick-start-py)。 您可以閱讀[文件](https://docs.dipy.org/stable/)並存取他們的[YouTube 頻道](https://www.youtube.com/c/diffusionimaginginpython)。 你可以看看詳細的[例子](https://docs.dipy.org/stable/examples_built/index.html)。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b6x3jotln0chpoycmci.png) 他們的下載量超過 428k,並且在 GitHub 儲存庫上擁有 600 多個 Star。 https://github.com/dipy/dipy 明星 DIPY ⭐️ --- 23. [Elastic Search](https://github.com/elastic/elasticsearch) - 免費開放式、分散式、RESTful 搜尋引擎。 ---------------------------------------------------------------------------------------- ![彈性搜尋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ouw3u41qdkfjvt999lnv.png) ![資料擬合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tsn875yov9bmklfg9aqc.png) Elasticsearch 是一種分散式、RESTful 搜尋和分析引擎,能夠解決大量使用案例。 作為 Elastic Stack 的核心,它集中儲存您的資料,以實現閃電般的快速搜尋、微調的相關性以及可輕鬆擴展的強大分析。 他們闡述了使用 ElasticSearch 的用例。 ![用例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sp4qf45yzulbi4c7dire.png) Elasticsearch 使用標準 RESTful API 和 JSON。我們也使用多種語言(例如 Java、Python、.NET、SQL 和 PHP)來建立和維護客戶端。 該結構如下。 ``` const { Client } = require('@elastic/elasticsearch') const client = new Client({ node: 'http://localhost:9200' }) client .search({ index: 'social-*', body: { query: { match: { message: 'myProduct' } }, aggs: { top_10_states: { terms: { field: 'state', size: 10 } } } } }) .then(({ body }) => { const { hits } = body.hits console.log(hits) }) .catch(console.error) ``` 您可以閱讀<a href="">文件</a>並查看[功能清單](https://www.elastic.co/elasticsearch/features)。 儘管具有有用的功能,Elastic Search 的主要缺點是缺乏免費套餐。但是,您仍然可以利用免費試用版來探索和了解開源專案的架構。 Elastic Search 在 GitHub 上擁有超過 67k+ 的星星和近 1900 名貢獻者,並且處於`v8`版本中,正在不斷發展和改進。 https://github.com/elastic/elasticsearch 明星 Elastic Search ⭐️ --- 24. [Tauri](https://github.com/tauri-apps/tauri) - 使用 Web 前端建立更小、更快且安全的桌面應用程式。 ------------------------------------------------------------------------------ ![困難](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7z6iilytnkaw5d3uj6zv.png) Tauri 是一個工具包,旨在幫助開發人員利用幾乎任何可用的前端框架為主要桌面平台建立應用程式。其核心是使用 Rust 開發的,而 CLI 利用 Node.js,提供了一種真正的多語言方法來開發和維護卓越的應用程式。 Tauri 應用程式中的使用者介面目前利用 Tao 作為 macOS、Windows、Linux、Android 和 iOS 上的視窗處理庫。 為了渲染您的應用程式,Tauri 使用 WRY,這是一個為系統 Web 視圖提供統一介面的程式庫。它在 macOS 和 iOS 上利用 WKWebView、在 Windows 上利用 WebView2、在 Linux 上利用 WebKitGTK 以及在 Android 上利用 Android System WebView。 您可以使用 Vite、HTML/CSS/JS、Next.js、Svelte 等等。 開始使用以下 npm 指令。 ``` npm create tauri-app@latest ``` 您可以閱讀[文件](https://tauri.app/v1/guides/getting-started/prerequisites)並查看 Tauri 提供的[功能清單](https://tauri.app/v1/guides/features/)。 您甚至可以使用 Tauri 建立自己的 CLI,這有多酷:) 團隊提供了[YouTube 影片](https://www.youtube.com/watch?v=UxTJeEbZX-0&t=2s),讓您了解更多關於 Tauri 的訊息。 他們在 GitHub 上擁有超過 75k 顆星星,並發布了 800 多個版本。 https://github.com/tauri-apps/tauri 金牛座之星 ⭐️ --- 25. [AutoGPT](https://github.com/Significant-Gravitas/AutoGPT) - 比 ChatGPT 更令人興奮。 --------------------------------------------------------------------------------- ![自動gpt](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hjamyxzkhy7luwsi9vp.png) AutoGPT 的核心在於其主要專案,即由大型語言模型 (LLM) 驅動的半自治代理,旨在為您執行任何任務。 AutoGPT 計畫由[四個主要部分](https://docs.agpt.co/#agent)組成: - 代理 – 也稱為“AutoGPT” - 基準 – 又稱 agbenchmark - 熔爐 - 前端 了解如何使用 OpenAI 金鑰[設定 AutoGPT](https://docs.agpt.co/autogpt/setup/) 。 您可以觀看[Fireship 發布的有關 AutoGPT 的 YouTube 影片](https://www.youtube.com/watch?v=_rGXIXyNqpk)。 https://www.youtube.com/watch?v=\_rGXIXyNqpk 您也可以觀看 Sentral Media 提供的[AutoGPT 教學](https://www.youtube.com/watch?v=FeIIaJUN-4A)。 您可以閱讀[文件](https://docs.agpt.co/)並查看[專案板](https://github.com/orgs/Significant-Gravitas/projects/1),以了解目前正在開發的內容。 即使您對 AI 不太了解,您也可以嘗試 AutoGPT 以了解如何節省時間並建立很酷的東西。 由於如此出色的用例和自動化功能,他們在 GitHub Repo 上擁有大約 159k+ 的星星。 https://github.com/Significant-Gravitas/AutoGPT 明星 AutoGPT ⭐️ --- 還沒結束。 現在,讓我們探索一些有價值的資源,這些資源將幫助您學習新概念並製作更好的人工智慧應用程式。 我們會保持簡單。不掛! - [人工智慧 (AI) 課程、書籍、視訊講座和論文](https://github.com/owainlewis/awesome-artificial-intelligence) - [機器學習/深度學習/AI + Web3 - 教程](https://github.com/TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials) - [ML 初學者](https://github.com/microsoft/ML-For-Beginners)- 12 週、26 節課程、52 個測驗,適合所有人的經典機器學習。 - [機器學習框架、函式庫和軟體](https://github.com/josephmisiti/awesome-machine-learning) - [如何製作人工智慧:逐步指南 - Revelo](https://www.revelo.com/blog/how-to-make-an-ai) 希望這將幫助您學習更多概念! --- 我希望您在列表中找到有用的東西。 我介紹了一些很棒的開源專案,它們可以將您的 AI 應用程式提升到一個新的水平。 人工智慧正在改變世界,最好與人工智慧保持朋友關係,而不是忽視它。 利用它來提高生產力,並抓住機會開發一些非凡的東西。 如果您想以最佳方式改進您的專案,有些開源專案比其他專案更有用,尤其是 Taipy 和 AutoGPT。 請發表評論,讓我們知道哪個專案最讓您感到驚訝。 祝你有美好的一天!直到下一次。 在 GitHub 上關注我。 https://github.com/Anmol-Baranwal 關注 Taipy 以了解更多此類內容。 https://dev.to/taipy --- 原文出處:https://dev.to/taipy/all-the-tools-i-need-to-build-a-perfect-ai-app-2oeh

關於 Deno 和 Node 的未來

如果 Node 是今天寫的,它會是什麼樣子?一言以蔽之: [**Deno**](https://deno.land/) 。 JS 執行時內建了 Typescript 並簡化了模組解析。最重要的是,它將安全性提升到了一個新的水平,並縮小了我們在後端編寫 javascript 的方式與瀏覽器之間的差距。 不久前 ... ------- 2009 年發布的 node 以令人難以置信的速度席捲了世界。儘管最初對在後端執行 javascript 持懷疑態度,但社區的支持是無與倫比的。很快,複雜的工具出現了,幾年後(2014 年),微軟發布了 Typescript,對 Javascript 進行了雙重押注。 如今,Node 是後端開發最受歡迎的選擇之一。基於事件的伺服器理念確保了高效能/吞吐量比。執行 Javascript 對許多開發人員來說是一種易於使用的工具。在某種程度上,可以說,Node 透過降低進入門檻實現了後端開發的民主化。在過去的五年裡,我一直很高興地使用 Node,但同時,我想知道未來在等待著什麼? 街區的新來者:Deno ----------- 如網站所述,Deno 專案於 2018 年啟動,為 Javascript 和 Typescript 提供安全的執行時間。它基本上由兩部分組成: TypeScript 前端和 Rust 後端。兩者之間的通訊是透過使用`TypedArrays`進行訊息傳遞來進行。 ![替代文字](https://dev-to-uploads.s3.amazonaws.com/i/aqzvipzkxwk1v45n22s9.png) > Deno 是 JavaScript/TypeScript 執行時,具有安全的預設設定和出色的開發人員體驗。 — Deno 網站 在底層,我們找到了 Typescript 編譯器、V8 引擎和 Tokio 事件循環的快照版本。總而言之,以小於 10 MB 的二進位檔案或 Rust 箱子的形式提供。 API老化 ----- 早在 2010 年就取消了 Node 的承諾,這在早期階段對社群有所幫助。但隨著 JavaScript 開始變得越來越快並引入了等待和非同步功能,Node 的 API 開始老化。 今天我們付出了巨大的努力來讓他們加快速度,同時保持一致的版本控制。許多 API 呼叫仍必須包裝在建構函式(如`promisify`中才能與`Promise`語法一起使用。這個額外的步驟增加了開發的開銷並增加了應用程式中的樣板檔案。 相比之下,Promise 是 Deno 異步行為的本機綁定。 Rust 後端透過 Rust Futures 鏡像從 Typescript 前端接收的 Promise 物件。 Deno 中的非同步操作總是會傳回`Promise` 。 Node 的另一個值得注意的是它依賴`Buffer`物件來讀寫資料。為了實現瀏覽器介面的統一,Deno 在各處都使用了[`TypedArrays`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays) 。使用相同的資料結構時,在後端和前端讀寫檔案時保持一致會容易得多。 零設定的 TypeScript ------- 如果你使用 Typescript,你就會知道它是一個出色的工具。它引入了一個可以隨著應用程式的成長而強制執行的類型系統。這透過提供靈活性減少了傳統靜態類型的開銷。專案可以在請求中進行部分類型化,並且類型覆蓋範圍可以隨著應用程式的成長而擴展。 在 Node 中,Typescript 可以直接與`ts-node`一起使用,儘管在生產中必須小心。最安全、效能最好的選擇是使用`ts-node`進行開發。然後編譯為 javascript 以進行生產。開發的設定可能很複雜,尤其是與熱程式碼重新載入等其他功能一起使用時。 另一方面,Deno 完全是關於 Typescript 的。它使用編譯器的快照版本並捕獲未更改的檔案。你想執行 Typescript 程式碼嗎?只需執行 Deno 二進位檔案即可。沒有配置。沒有喧囂。是不是很簡單,當然它也支援javascript。 類似瀏覽器的套件解析 ---------- Node 目前的解析方案使模組解析過於複雜。該演算法在文件位置和命名方面提供了靈活性,但在複雜性方面做出了相當大的權衡。 `require`呼叫將先搜尋具有相同名稱和`.js` 、 `.json`或`.node`副檔名的檔案。如果指定的路徑不包含前導`'/'` 、 `'./'`或`'../'` node ,則假定該模組是核心模組或`node_modules`資料夾中的依賴項。如果名稱不匹配,核心模組 node 將檢查該位置的node\_modules。如果沒有找到任何內容,它將到達父目錄並繼續這樣做,直到到達檔案系統的根目錄。 此外,資料夾可以在`package.json`檔案中指定為模組。 `require`函數也知道開始檢查的所有資料夾的`package.json`檔案。一旦找到資料夾,Node 將在其中查找`index.js`或`index.node`檔案。不必提供檔案副檔名的自由和`package.json`的靈活性會顯著增加複雜性並降低效能。 Deno 透過提供兩種類型的模組解析(相對解析和基於 URL 解析)來簡化演算法: ``` import * from "https://deno.land/std/testing/asserts.ts"; ``` 另外,解析演算法不使用`package.json`檔案或`node_modules`資料夾。它使用 ES 模組導入而不是`require` 。這使我們能夠使用現代方法進行程式碼管理,而無需預編譯器,並使我們再次更接近 Javascript 在瀏覽器中的使用方式。 分散式套件管理 ------- 目前,無伺服器的採用率每年翻倍。開發人員通常將單體應用程式拆分為微服務。現在我們將微服務拆分為功能。為什麼?嗯,一方面,沒有人願意處理編排,除非我們也有。另一方面,分散式系統更加靈活,可以更快地改變。最重要的是,應用程式正在成為由更小且獨立的部分組成的系統。 典型的 JavaScript 後端應用程式僅使用 0.3% 的程式碼。其餘部分由`node_modules`資料夾中的套件組成。而且許多在執行時幾乎不被使用。同時,整個生態系統依賴一個集中的套件管理器: `npm` 。 **Deno**帶來了一種分散式套件管理方法。套件可以透過 URL 解析並隨後捕獲。應用程式更輕,更少依賴單一的集中式套件註冊表。 關於安全 ---- 在進行後端開發時,我希望安全性能夠在盒子之外發揮作用。我最不想考慮的是存取網路或檔案系統的 linter 檔案或 node 模組。 在 Deno 中,內部函數不能像在 Node 中那樣任意呼叫 V8 API。 Deno 的 API 和 JS 引擎之間的通訊是集中且統一的,基於類型化陣列的訊息傳遞。 > 除非特別允許,否則腳本無法存取檔案、環境或網路。 — 德諾.蘭 只有當使用者明確指定時,使用 Deno 執行的腳本才能存取檔案系統和網路。更好的是,可以使用 —allow 標誌在檔案、資料夾層級或網路路徑層級授予權限。這為開發人員提供了對執行時發生的讀寫操作的精細控制。 ``` $ deno --allow-net https://deno.land/std/examples/echo_server.ts ``` 與應用於從`npn`提取的依賴項的「信任」策略相比,預設的安全性是一項重大升級。借助 Deno,您可以執行和開發應用程式,並確信它們會執行預期的操作。 加起來 --- 如果 Node 在今天建置, **Deno**就是它的樣子。它提高了安全性、簡化了模組解析並執行 Typescript。 當我寫這篇文章時,我們仍處於 0.33 版本並且正在快速發展。我確信您來到這裡是因為您在某種程度上使用了 Node 或 Javascript。如果你像我一樣,你可能會喜歡它。但正如他們所說,愛某樣東西真正意味著放手。 我期待看到 Deno 超越單純的腳本執行時,並聽到生產中的第一次經驗。只要開發人員繼續顛覆自己,我們總是能期待更快、更簡單、更可靠的軟體。 最初發佈於[bogdanned.com](https://bogdanned.com/blog) 。 --- 原文出處:https://dev.to/bogdanned/on-deno-and-the-future-of-node-1l0p

在各種部落格平台,放進自己的的程式碼

在本文中,我將概述各種[部落格平台及其程式碼注入功能](https://bloggingplatforms.app/blog/blogging-platforms-with-the-best-code-injection)。 想像自己是個博主,無論您是經驗豐富還是剛起步;你不僅僅是一個文字大師。您擁有 Web 開發技能,並且渴望控制線上主頁的外觀、感覺和功能。這就是部落格平台上的程式碼注入可以發揮作用的地方! 我將指導您使用[最好的部落格平台](https://bloggingplatforms.app/)來注入自訂程式碼。 **為什麼程式碼注入很重要以及它如何使您受益** 讓我們分解一下:程式碼注入意味著在您的部落格中加入自訂程式碼(如 HTML、CSS 或 JavaScript)。此功能很有用,因為: - **獨特的設計:**擺脫模板並個性化您部落格的視覺效果。 - **特殊功能:**考慮互動式元素、自訂小工具或獨特的動畫。 - **資料追蹤:**整合您喜歡的分析工具以獲得深入的見解。 - **功能改進:**優化頁面載入速度或實現複雜功能。 ![為部落格平台注入程式碼的好處](https://bloggingplatforms.app/media/posts/blogging-platforms-with-the-best-code-injection/benefits-of-code-injection.webp) **具有最佳程式碼注入選項的 Bogging 平台** --------------------------- ### **WordPress:程式碼注入動力源** 作為內容管理系統 (CMS) 領域無可爭議的皇帝, [WordPress](https://wordpress.com/)擁有無與倫比的程式碼注入能力。 其**主題自訂**功能可讓您直接存取主題文件,使您能夠透過主題編輯器無縫整合自訂程式碼片段。 此外,**程式碼片段**和**插入頁首和頁尾等**[WordPress 外掛](https://wordpress.com/plugins)提供了使用者友善的介面,用於將程式碼注入部落格佈局的特定部分,例如頁首、頁尾或側邊欄。 #### **探索 WordPress 的程式碼注入功能:** - **主題編輯:**對於技術嫻熟的人來說,WordPress 透過內建主題編輯器授予對主題文件的完全存取權。這種精細的控制使您能夠將程式碼直接注入到模板檔案(header.php、footer.php 等)中,從而對部落格的佈局和功能進行深度自訂。 - **外掛程式:**廣泛的 WordPress 外掛程式生態系統提供了大量的程式碼注入工具。程式碼片段和插入頁首和頁尾等插件提供了用戶友好的介面,用於將程式碼片段注入部落格的特定區域,滿足所有技術背景的用戶的需求。這些插件通常配備程式碼語法突出顯示和錯誤檢查等功能,從而簡化程式碼注入過程。 #### **重要考慮因素:** - **主題相容性:**直接注入主題檔案的程式碼本質上連結到您正在使用的特定主題。如果切換主題,您可能需要修改或重新註入程式碼片段。 - **插件依賴:**雖然插件簡化了程式碼注入,但它們引入了外部依賴項。確保您選擇的外掛程式得到積極維護並與您的 WordPress 版本相容。 --- ### **Webflow:透過視覺編碼為精通設計的部落客提供支持** [Webflow](https://webflow.grsm.io/gr15bvbdlvfo)提出了一個獨特的主張:一個**視覺化開發平台**,讓您無需編寫任何程式碼即可建立自訂網站。正因為如此,Webflow 是[藝術家最好的部落格平台](https://bloggingplatforms.app/blog/best-blog-platforms-for-artists)之一。 然而,對於那些尋求更精細控制的人來說, [Webflow](https://webflow.grsm.io/gr15bvbdlvfo)提供了一個程式碼注入功能,恰當地命名為**「自訂程式碼」** 。此功能可讓您將程式碼片段直接注入網站的專案設定中,從而可以微調特定的設計元素和功能。 #### **釋放 Webflow 的程式碼注入潛力:** - **自訂程式碼:** Webflow 的自訂程式碼功能可讓您存取專案設定中指定的程式碼注入區域。在這裡,您可以注入針對網站設計和功能的特定方面的程式碼片段,例如加入自訂動畫、整合第三方服務或修改現有元素的行為。 - **Visual Canvas:** Webflow 的主要優點在於其視覺化開發介面。您無需直接操作程式碼即可實現顯著程度的自訂。然而,自訂程式碼為那些尋求更深入研究並釋放程式碼注入全部威力的人提供了一個逃生口。 #### **重要考慮因素:** - **學習曲線:**雖然 Webflow 提供了視覺化開發介面,但了解基本的 HTML、CSS 和 JavaScript 對於有效的程式碼注入非常有益。 - **範圍有限:**與 WordPress 等成熟的 CMS 相比,Webflow 的程式碼注入功能旨在微調設計元素和功能,而不是進行廣泛的結構修改。 --- ### **WebWave:為新手部落客簡化程式碼注入** [WebWave](https://webwave.me/ref/14072231082)是另一個視覺化網站建立器,它迎合了那些在用戶友好的拖放功能和注入自訂程式碼的能力之間尋求平衡的人。其**程式碼編輯器**可讓您將程式碼片段注入網站佈局的特定部分,從而提供個人化的途徑,而無需廣泛的編碼專業知識。 **探索 WebWave 的程式碼注入功能:** - **程式碼編輯器:** WebWave 的程式碼編輯器可讓您將程式碼片段直接注入網站頁面的指定部分。這種有針對性的方法可讓您自訂特定元素,例如新增自訂按鈕、整合小工具或修改現有功能。 - **初學者友善的介面:**程式碼編輯器提供了一個相對用戶友好的介面,具有語法突出顯示和基本的錯誤檢查功能,即使對 Web 開發有基本了解的部落客也可以使用它。 #### **重要考慮因素:** - **範圍有限:** WebWave 的程式碼注入功能著重於在地化修改,而不是對網站進行全面的結構變更。 - **外部依賴:**依賴 WebWave 的程式碼編輯器意味著一定程度的平台鎖定。如果您要遷移網站,自訂程式碼片段可能需要修改。 --- ### **Typedream:無程式碼環境中的程式碼注入** [Typedream](https://typedream.com/?via=blogplatforms)將自己定位為無程式碼網站建立器,在建立精美網站時優先考慮易用性。然而,它提供了有針對性的程式碼注入功能來擴展其功能並允許超出預定模板的自訂。 #### **Typedream 的程式碼注入潛力:** - **嵌入元素:**透過嵌入程式碼片段,將第三方服務、小工具或自訂元素整合到 Typedream 網站的特定區域。 - **功能增強:**透過自訂互動、動畫或獨特的視覺效果擴展 Typedream 的內建功能。 #### **重要考慮因素:** - **無程式碼優先:** Typedream 的優勢在於其簡單性和使用者友善性。程式碼注入可作為高級使用者工具使用,而不是其主要的客製化方法。 --- ### **Unicorn:程式碼注入以實現靈活性** [Unicorn Platform](https://unicornplatform.com/?via=bloggingplatforms)透過其拖放介面簡化了網站開發流程。此外,它還提供**程式碼注入**功能,可讓您透過將程式碼片段直接插入特定部分來進一步自訂您的網站。 #### **Unicorn 的程式碼注入潛力:** - **有針對性的客製化:** Unicorn 的程式碼注入功能可讓您修改單一元件或為您的網站加入新功能。整合第三方服務、建立自訂動畫或根據需要調整樣式。 - **使用者友善的介面:** Unicorn 對簡單性的關注延伸到了其程式碼注入功能,使其對於具有基本 Web 開發知識的使用者來說易於使用。 #### 重要考慮因素: - **平台依賴:**請記住,注入 Unicorn 的自訂程式碼片段依賴於平台。如果您決定遷移站點,程式碼相容性可能會成為一個問題。 --- ### **Dorik:無程式碼,但具有客製化潛力** [Dorik](https://dorik.com/?ref=can-burak72)將自己定位為專注於無程式碼原則的未來網站建立者。它的目的是擺脫傳統的頁面建立器。雖然 Dorik 並沒有專注於程式碼注入,但它在其新穎的框架中提供了客製化潛力。 #### **Dorik 的客製化潛力:** - **程式碼探索:**期望在 Dorik 上採用更具實驗性的客製化方法,可能涉及獨特的視覺化工具,而不是直接程式碼注入。 #### **重要考慮因素:** - **不斷發展的平台:** Dorik 相對較新,因此其客製化理念可能會隨著時間的推移而不斷發展。隨時了解他們的發展路線圖以獲取更多見解。 --- ### **Wix:用於擴展功能的程式碼注入** [Wix](https://www.wix.com/)是一種流行的拖放式網站建立器,透過其開發人員工具集(稱為**Corvid by Wix(以前稱為 Velo))**提供程式碼注入功能。這個先進的平台使您能夠透過編寫自訂 JavaScript 程式碼和整合外部 API 來擴展 Wix 網站的功能。 #### **利用 Corvid(以前稱為 Velo)的力量:** - **以 JavaScript 為中心:** Corvid 主要依賴 JavaScript 來實作自訂功能。對 JavaScript 的深入理解對於充分發揮其潛力至關重要。 - **API 整合:** Corvid 可以整合第三方服務和 API,從而增強您網站的功能,超越 Wix 內建工具的限制。 - **專用開發環境:**存取 Corvid 需要轉向專用開發環境,這可能會為非程式設計師帶來更陡峭的學習曲線。 #### **重要考慮因素:** - **陡峭的學習曲線:**有效利用 Corvid 需要 JavaScript 的應用知識和熟悉程式設計概念。 - **Wix 生態系內的有限控制:雖然很靈活,但 Corvid 的功能僅限於 Wix 生態系的範圍內。**廣泛的網站結構修改可能會受到限制。 --- ### **Squarespace:在易用性和客製化之間取得平衡** [Squarespace](https://www.squarespace.com/)以其用戶友好的介面和拖放功能而聞名,提供了一種經過衡量的程式碼注入方法。其**程式碼注入**功能可讓您將程式碼片段插入網站的指定區域,從而無需具備豐富的編碼知識即可實現有針對性的自訂。 #### **釋放 Squarespace 的程式碼注入潛力:** - **有針對性的客製化:** Squarespace 的程式碼注入功能適合特定的修改。嵌入自訂字體、整合社交媒體來源或加入自訂按鈕來增強部落格的外觀和感覺。 - **初學者友善的介面:** Squarespace 的程式碼注入功能優先考慮可存取性。即使具有最少編碼經驗的使用者也可以導航介面並實現基本的程式碼修改。 #### **重要考慮因素:** - **範圍有限:** Squarespace 的程式碼注入主要專注於在地化自訂,而不是對網站進行徹底的結構變更。 - **平台依賴:**注入 Squarespace 的自訂程式碼片段與平台相關。如果您要遷移網站,程式碼相容性可能會成為問題。 --- ### **Pixpa:攝影師和創意人員的程式碼注入** [Pixpa](https://www.pixpa.com/signup?refcode=BURAK10)專門為尋求展示作品平台的攝影師和創意專業人士提供服務。雖然其核心功能圍繞著令人驚嘆的視覺效果,但 Pixpa 為尋求額外控制的人提供了**程式碼注入**功能。 #### **Pixpa 的程式碼注入功能:** - **增強的功能:**注入程式碼片段以整合第三方服務,例如分析工具、支付網關或自訂聯絡表單,從而擴展部落格的功能。 - **易於使用:** Pixpa 的程式碼注入功能提供了使用者友善的介面和清晰的說明,使得非程式設計師也可以輕鬆使用。 #### **重要考慮因素:** - **有限的客製化:** Pixpa 的程式碼注入主要針對功能增強而不是廣泛的設計修改。 - **專注於利基市場:**雖然 Pixpa 非常適合創意人士,但它可能無法像更通用的平台那樣有效地迎合所有部落格利基市場。 --- ### **PageCloud:用於有針對性的增強的程式碼注入** [PageCloud](https://www.pagecloud.com/home-partners?gspk=Y2FuYnVyYWtzb2Z5YWxpb2dsdTMwNTQ&gsxid=Is2tDreeXpFm&utm_campaign=affiliate-referral-program&utm_medium=partner&utm_source=canburaksofyalioglu3054)將自己定位為具有程式碼注入功能的用戶友好的網站建立器。其**自訂程式碼**功能可讓您將程式碼片段注入網站的特定部分,從而實現有針對性的自訂。 #### **探索 PageCloud 的程式碼注入選項:** - **特定部分:** PageCloud 的程式碼注入著重於修改網站的指定部分,例如頁首、頁尾或側邊欄。這種方法非常適合整合小部件、加入自訂按鈕或微調佈局。 - **初學者的介面:** PageCloud 透過其程式碼注入功能優先考慮易用性。清晰的說明和用戶友好的介面使得那些具有最少編碼經驗的人也可以使用它。 #### **重要考慮因素:** - **範圍有限:**與 Squarespace 類似,PageCloud 的程式碼注入功能面向局部增強,而不是廣泛的結構修改。 - **平台依賴性:**自訂程式碼片段依賴PageCloud。從平台遷移可能需要程式碼調整或重新註入。然而,這可以被視為 PageCloud 提供的易用性和用戶友好介面的權衡。 --- ### **Blogger:具有基本程式碼注入功能的免費平台** [Blogger](https://www.blogger.com/)上提供了基本等級的程式碼注入功能,Blogger 是 Google 的免費部落格平台。透過其**HTML/CSS 編輯**功能,您可以存取和修改部落格範本的底層程式碼。 #### **Blogger 的程式碼注入潛力:** - **直接模板編輯:**對於熟悉程式碼的人,Blogger 授予對其模板文件的存取權限,從而可以直接修改控制部落格佈局和樣式的 HTML 和 CSS 程式碼。 - **功能有限:** Blogger 的程式碼注入功能是針對基本自訂,主要涉及編輯現有程式碼,而不是注入全新的功能。 #### **重要考慮因素:** - **所需技術專長:**直接模板編輯需要對 HTML 和 CSS 有深入的了解。對於初學者來說,這種方法可以呈現更陡峭的學習曲線。 - **控制有限:**與付費平台相比,Blogger 的免費方案對客製化施加了限制。 --- ### **Framer:為 Web 開發人員提供程式碼驅動的客製化** [Framer](https://www.framer.com/)是一個強大的視覺設計平台,整合了 React 編碼功能,為 Web 開發人員提供了一個遊樂場。雖然 Framer 主要針對應用程式開發,但其以程式碼為中心的方法為在其生態系統中建立部落格的人員提供了廣泛的客製化可能性。 #### **探索 Framer 的程式碼注入功能:** - **以開發人員為中心的客製化:**使用 Framer,您基本上可以使用 React 元件建立博客,從而可以對從佈局到互動的各個方面進行細粒度控制。 - **無限的可能性:** Framer 的程式碼注入幾乎是無限的,使您能夠製作一個突破傳統設計和功能界限的部落格。 #### **重要考慮因素:** - **陡峭的學習曲線:**有效利用 Framer 需要對 React 和 Web 開發原理有深入的了解。 - **資源密集:**與程式碼密集度較低的平台相比,在 Framer 中開發部落格可能需要更多時間和開發資源。 --- ### **Ghost:為精通程式碼的用戶提供開源靈活性** [Ghost](https://ghost.org/)以專注於純粹的部落格而聞名,提供了對開發人員有吸引力的開源靈活性。其主題結構利用 Handlebars 模板語言,允許全面的程式碼注入和客製化。 #### **Ghost的程式碼注入潛力:** - **完整的主題自訂:** Ghost 的開源特性可讓您直接修改主題文件,從而對部落格的結構和設計提供高階的控制。 - **社區驅動的支持:** Ghost 受益於蓬勃發展的開發者社區,該社區共享主題、程式碼片段和知識,培育了豐富的生態系統。 #### **重要考慮因素:** - **技術專長:** Ghost 中的有效程式碼注入需要熟悉 Handlebars 範本和 Web 開發原則。 - **自架:**為了實現完全客製化的潛力,自架您的 Ghost 部落格可能是必要的,這會帶來額外的技術開銷。 --- ### **曝光:攝影師的程式碼注入** [Exposure](https://exposure.co/)專注於視覺敘事,並擁有時尚的介面。它使攝影師和那些有視覺傾向的人能夠建立令人驚嘆的部落格來展示他們的作品。 Exposure 提供了注入自訂程式碼的能力,為進一步個性化您的線上形像打開了大門。 #### **了解 Exposure 的程式碼注入功能:** - **有針對性的調整:**將自訂程式碼注入您的 Exposure 部落格的特定區域,例如頁首、頁尾或單一頁面。 - **功能增強:**透過整合第三方工具或自訂元素來增強您的博客,擴展 Exposure 的內建功能。 #### **重要考慮因素:** - **社群支援:**考慮專門為 Exposure 上的程式碼注入量身定制的資源的可用性,因為其社群可能比某些其他平台小。 --- ### **Hashnode:為開發者部落客客製化的程式碼注入解決方案** [Hashnode](https://hashnode.com/)是一個為開發人員量身定制的社群驅動的部落格平台。它是[**最好的開發者部落格平台**](https://bloggingplatforms.app/blog/best-blogging-platforms-for-developers)之一。 它優先考慮技術討論和知識共享。使用 Hashnode,您可以注入自訂程式碼來客製化部落格的外觀和功能。 #### **探索Hashnode的程式碼注入功能:** - **自訂樣式:**使用自訂 CSS 程式碼修改 Hashnode 部落格的外觀,創造與您的品牌相符的獨特外觀。 - **嵌入和小部件:**整合程式碼片段以顯示程式碼區塊、可嵌入內容和動態小部件,豐富您的技術寫作。 #### **重要考慮因素:** - **利基焦點:** Hashnode 最適合開發人員和技術部落客。它可能不是一般興趣部落格的理想平台。 --- ### **Odoo:模組化 CMS 中的程式碼注入** [Odoo](https://www.odoo.com/)是一個龐大的開源業務管理套件,包括網站建立器和部落格模組。它提供了注入程式碼的能力,允許在 Odoo 生態系統中進行客製化。 #### **Odoo 的程式碼注入潛力:** - **深度整合:**自訂 Odoo 模組(包括您的部落格)以與特定業務工作流程或流程保持一致。 - **框架熟悉度:** Odoo 中的有效程式碼注入需要了解其基於 Python 的開發框架。 **重要考慮因素:** - **以企業為中心:** Odoo 的複雜性使其最適合擁有大量 IT 資源的企業,而不是個人部落客。 --- ### **Jimdo:有限的程式碼注入** [Jimdo](https://www.jimdo.com/)是一個用戶友好的網站建立器,提供有限程度的程式碼注入。您可以將基本 HTML 片段新增至網站的某些區域。 #### **重要考慮因素:** - **簡單性:** Jimdo 優先考慮易用性而不是廣泛的客製化選項。 - **最適合初學者:** Jimdo 上的程式碼注入可能適合簡單的修改,但無法滿足需要高級自訂的用戶的需求。 --- ### **Weebly:用於基本客製化的定向程式碼注入** [Weebly](https://www.weebly.com/)是另一個受歡迎的拖放網站建立器,提供有針對性的程式碼注入功能。其**嵌入程式碼**功能可讓您將 HTML 和 JavaScript 片段插入網站的特定部分,從而實現基本的修改和整合。 #### **Weebly 的程式碼注入潛力:** - **具體增強功能:**利用 Weebly 的程式碼注入來整合第三方小工具,例如社群媒體來源或即時聊天工具。 - **適合初學者:** Weebly 的嵌入程式碼功能為基本程式碼插入提供了一個簡單的介面。 #### **重要考慮因素:** - **Weebly 的程式碼注入範圍:**與 Squarespace 和 PageCloud 一樣,Weebly 的程式碼注入專注於局部增強而不是廣泛的結構變化。 - **平台相容性:**注入 Weebly 的自訂程式碼與平台綁定。遷移可能需要程式碼調整或重新註入。 --- ### **Tumblr:主題客製化的程式碼注入** [Tumblr](https://www.tumblr.com/)是一個以其強大的社群和社交功能而聞名的微博平台,允許透過其主題自訂選項進行一定程度的程式碼注入。 #### **Tumblr 的程式碼注入潛力:** - **主題修改:**直接存取主題檔案可讓您注入 HTML、CSS 和 JavaScript 程式碼。自訂 Tumblr 部落格的佈局、樣式和功能。 - **創意人員的靈活性:** Tumblr 的開放主題結構和對視覺表達的重視使其成為渴望獨特線上形象的創意人士的熱門選擇。 #### **重要考慮因素:** - **熟悉語法:**修改 Tumblr 主題需要對 HTML、CSS 和 JavaScript 語法有基本的了解。 - **社群驅動:** Tumblr 擁有龐大的主題開發人員社區,他們經常分享程式碼片段和自訂技巧。 --- ### **Tilda:帶有程式碼注入選項的視覺設計** [Tilda](https://tilda.cc/)是一個強調設計的模組化網站建立器,在其**零區塊**功能中提供程式碼注入功能。此功能可讓您插入自訂程式碼,提供超越其視覺化建構器工具的靈活性。 #### **Tilda 的程式碼注入潛力:** - **視覺 + 程式碼:**在 Tilda 直覺的拖放介面和程式碼注入的強大功能之間取得平衡。建立獨特的元素或修改現有區塊以進行細粒度控制。 - **有針對性的增強:**透過整合、自訂動畫或獨特的設計元素擴展 Tilda 的功能。 #### **重要考慮因素:** - **零塊特定:** Tilda 上的程式碼注入主要側重於零塊功能內的自定義,與直接主題編輯相比,提供了更結構化的方法。 - **設計優先:Tilda 專注於將拖放建構器作為主要設計工具。**程式碼注入是擴展定制的一個有價值的補充功能。 --- ### **SmugMug:針對以視覺為中心的攝影師的有限程式碼注入** [SmugMug](https://www.smugmug.com/)是一個專門為攝影師展示和銷售作品而設計的平台。它提供有限的程式碼注入功能,主要用於基本修改。 #### **SmugMug 的程式碼注入潛力:** - **有限制的自訂:**雖然 SmugMug 允許進行一些 HTML 和 CSS 自訂,但其主要重點是視覺驅動的模板和主題。 - **適合攝影師:** SmugMug 的核心受眾可能會發現程式碼注入不再那麼重要,因為該平台優先考慮易用性來展示令人驚嘆的視覺效果。 #### **重要考慮因素:** - **特定領域:** SmugMug 非常注重影像展示和銷售功能,為攝影師提供了良好的服務。對於 SmugMug 的核心用戶來說,大量的程式碼注入可能不是優先考慮的事情。 --- ### **Cargo:創意組合的程式碼注入** [Cargo](https://cargo.site/)以其極簡設計和強調展示創意作品而聞名,允許一定程度的程式碼注入。此功能使用戶能夠在預先建立的模板之外個性化他們的線上作品集。 #### **Cargo 的程式碼注入潛力:** - **有針對性的自訂:**注入程式碼片段可以進行自訂,例如自訂字體、獨特的佈局或互動式元素,以增強您的創意作品的呈現。 #### **重要考慮因素:** - **範圍有限:** Cargo 上的程式碼注入最適合在地化增強,而不是對您的產品組合進行徹底的結構性變更。 --- ### **Adobe Portfolio:為視覺藝術家提供有限的程式碼注入** [Adobe Portfolio](https://portfolio.adobe.com/)與 Adobe 的 Creative Cloud 套件集成,主要專注於視覺作品集的無縫展示。它提供有限的程式碼注入功能,通常用於較小的樣式調整或嵌入第三方內容。 #### **Adobe Portfolio 的程式碼注入潛力:** - **增強視覺效果:**利用程式碼注入來自訂工作的呈現、加入微妙的動畫或嵌入互動元素。 - **專注於集成:** Adobe Portfolio 優先考慮與其他 Adobe Creative Cloud 服務的集成,而不是廣泛的程式碼驅動自訂。 #### **重要考慮因素:** - **視覺第一:** Adobe Portfolio 的核心優勢在於其易用性和專注於令人驚嘆的視覺呈現。程式碼注入能力是次要的。 --- ### **Vev:平衡視覺設計與程式碼注入** [Vev](https://www.vev.design/?gspk=Y2FuYnVyYWtzb2Z5YWxpb2dsdTMwNTQ&gsxid=6ql2Ybh49e9T&utm_campaign=affiliate&utm_id=VevPartners&utm_medium=partnerstack&utm_source=partnerstack)在直覺的視覺化設計工具和程式碼注入的靈活性之間提供了平衡。其專用的程式碼注入區域可實現有針對性的客製化和整合。 #### **Vev 的程式碼注入潛力:** - **自訂元素:**在 Vev 視覺建構器的框架內建立獨特的元素或修改現有元素,以獲得客製化的外觀和感覺。 - **第三方整合:**透過使用程式碼無縫整合外部服務和小部件來擴展部落格的功能。 #### **重要考慮因素:** - **混合方法:** Vev 迎合了既尋求視覺化建構器的便利性又尋求目標程式碼注入修改的強大功能的使用者。 --- ### **Voog:高級客製化的程式碼注入** [Voog](https://www.voog.com/)是一個多語言網站建立器,為開發人員和尋求對其網站結構和設計進行廣泛控制的人員提供強大的程式碼注入功能。 #### **Voog 的程式碼注入潛力:** - **完整的主題控制:** Voog 的開放式結構允許直接修改主題文件,從而實現廣泛的客製化可能性。 - **API 整合:**利用 Voog 的 API 整合自訂功能並簡化工作流程。 #### **重要考慮因素:** - **技術專長:**在 Voog 中進行有效的程式碼注入需要熟悉 Web 開發原理。 - **多語言聚焦:** Voog 的優勢在於其多語言能力。如果這是一個核心需求,那麼它的程式碼注入潛力就變得特別有利。 --- ### 格式:投資組合網站的有限程式碼注入 [Format](https://format.grsm.io/vdptwrg0w0q9)迎合了尋求透過令人驚嘆的作品集網站展示其作品的創意人士。它提供一定程度的程式碼注入,但優先考慮簡單性和視覺化設計工具。 #### Format 的程式碼注入潛力: - **整合與增強:**注入程式碼以嵌入外部內容、追蹤分析或為您的產品組合加入微妙的自訂。 #### 重要考慮因素: - **視覺焦點:**與 Ghost 或 WordPress 等平台相比,Format 的體驗不太以程式碼為中心。程式碼注入主要作為補充選項。 --- ### Carbonmade:用於組合定制的程式碼注入 [Carbonmade](https://carbonmade.com/)與 Format 和 Adobe Portfolio 類似,專為建立線上作品集的創意人員量身定制。它提供了適合基本修改和增強的程式碼注入等級。 #### Carbonmade 的程式碼注入潛力: - **微調示範:**透過 CSS 調整和基於 JavaScript 的互動來自訂 Carbonmade 產品組合的外觀和感覺。 #### 重要考慮因素: - **產品組合特定:** Carbonmade 的程式碼注入功能可能無法提供與 WordPress 等成熟的 CMS 相同的深度。 ### **結論** 選擇正確的具有程式碼注入的部落格平台可以歸結為在客製化和易用性之間取得平衡。請記住,您理想的部落格平台取決於您的具體需求、技術專長以及您對線上空間的創意願景。 --- 原文出處:https://dev.to/elastoplastique/code-injection-options-for-blogging-platforms-2g0a

建立文字到 PowerPoint 應用程式(LangChain、Next.js 和 CopilotKit)

長話短說 ==== 在本文中,您將學習如何建立由 AI 驅動的 PowerPoint 應用程式,該應用程式可以搜尋網路以自動製作有關任何主題的簡報。 我們將介紹使用: - 用於應用程式框架的 Next.js 🖥️ - 法學碩士 OpenAI 🧠 - LangChain 和 Tavily 的網路搜尋人工智慧代理🤖 - 使用 CopilotKit 將 AI 整合到您的應用程式中 🪁 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztokmi3hdcthmxkj2gny.gif) --- CopilotKit:為您的應用程式建立人工智慧副駕駛 --------------------------- CopilotKit 是[開源人工智慧副駕駛平台。](https://github.com/CopilotKit/CopilotKit)我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h69i50cxsyvcknlcs6q0.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} 現在回到文章。 (本文是我們三週前發表的一篇文章的進展,但您無需閱讀該文章即可理解這一點)。 --- **先決條件** -------- 在開始建立應用程式之前,讓我們先查看建置應用程式所需的依賴項或套件 `copilotkit/react-core` :CopilotKit 前端包,帶有 React hooks,用於向副駕駛提供應用程式狀態和操作(AI 功能) `copilotkit/react-ui` :聊天機器人側邊欄 UI 的 CopilotKit 前端包 `copilotkit/react-textarea` :CopilotKit 前端包,用於在演講者筆記中進行人工智慧輔助文字編輯。 `LangChainJS` :一個用於開發由語言模型支援的應用程式的框架。 `Tavily Search API` :幫助將法學碩士和人工智慧應用程式連接到可信賴的即時知識的 API。 安裝所有專案包和依賴項 ----------- 在安裝所有專案包和依賴項之前,我們首先在終端機上執行以下命令來建立 Nextjs 專案。 ``` npx create-next-app@latest ``` 然後系統會提示您選擇一些選項。請隨意標記它們,如下所示。 ![建立 Nextjs 專案](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n668ixcvu5lnrsm9jpmq.png) 之後,使用您選擇的文字編輯器開啟新建立的 Nextjs 專案。然後在命令列中執行以下命令來安裝所有專案包和依賴項。 ``` npm i @copilotkit/backend @copilotkit/shared @langchain/langgraph @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea @heroicons/react ``` **建立 PowerPoint 應用程式前端** ------------------------ 讓我們先建立一個名為`Slide.tsx`的檔案。該文件將包含顯示和編輯投影片內容的程式碼,包括其`title` 、 `body text` 、 `background image`和`spoken narration text` 。 要建立該文件,請前往`/[root]/src/app`並建立一個名為`components`的資料夾。在 Components 資料夾中,建立`Slide.tsx`檔案。 之後,在文件頂部加入以下程式碼。程式碼定義了兩個名為`SlideModel`和`SlideProps`的 TypeScript 介面。 ``` "use client"; // Define an interface for the model of a slide, specifying the expected structure of a slide object. export interface SlideModel { title: string; content: string; backgroundImageDescription: string; spokenNarration: string; } // Define an interface for the properties of a component or function that manages slides. export interface SlideProps { slide: SlideModel; partialUpdateSlide: (partialSlide: Partial<SlideModel>) => void; } ``` 接下來,在上面的程式碼下面加入以下程式碼。程式碼定義了一個名為`Slide`功能元件,它接受`SlideProps`類型的 props。 ``` // Define a functional component named Slide that accepts props of type SlideProps. export const Slide = (props: SlideProps) => { // Define a constant for the height of the area reserved for speaker notes. const heightOfSpeakerNotes = 150; // Construct a URL for the background image using the description from slide properties, dynamically fetching an image from Unsplash. const backgroundImage = 'url("https://source.unsplash.com/featured/?' + encodeURIComponent(props.slide.backgroundImageDescription) + '")'; // Return JSX for the slide component. return ( <> {/* Slide content container with dynamic height calculation to account for speaker notes area. */} <div className="w-full relative bg-slate-200" style={{ height: `calc(100vh - ${heightOfSpeakerNotes}px)`, // Calculate height to leave space for speaker notes. }} > {/* Container for the slide title with centered alignment and styling. */} <div className="h-1/5 flex items-center justify-center text-5xl text-white text-center z-10" > {/* Textarea for slide title input, allowing dynamic updates. */} <textarea className="text-2xl bg-transparent text-black p-4 text-center font-bold uppercase italic line-clamp-2 resize-none flex items-center" style={{ border: "none", outline: "none", }} value={props.slide.title} placeholder="Title" onChange={(e) => { props.partialUpdateSlide({ title: e.target.value }); }} /> </div> {/* Container for the slide content with background image. */} <div className="h-4/5 flex" style={{ backgroundImage, backgroundSize: "cover", backgroundPosition: "center", }} > {/* Textarea for slide content input, allowing dynamic updates and styled for readability. */} <textarea className="w-full text-3xl text-black font-medium p-10 resize-none bg-red mx-40 my-8 rounded-xl text-center" style={{ lineHeight: "1.5", }} value={props.slide.content} placeholder="Body" onChange={(e) => { props.partialUpdateSlide({ content: e.target.value }); }} /> </div> </div> {/* Textarea for entering spoken narration with specified height and styling for consistency. */} <textarea className=" w-9/12 h-full bg-transparent text-5xl p-10 resize-none bg-gray-500 pr-36" style={{ height: `${heightOfSpeakerNotes}px`, background: "none", border: "none", outline: "none", fontFamily: "inherit", fontSize: "inherit", lineHeight: "inherit", }} value={props.slide.spokenNarration} onChange={(e) => { props.partialUpdateSlide({ spokenNarration: e.target.value }); }} /> </> ); }; ``` 之後,我們現在會建立一個名為`Presentation.tsx`的檔案。 該文件將包含初始化和更新投影片狀態、渲染目前投影片以及根據目前狀態動態啟用或停用按鈕實現導覽和投影片管理操作的程式碼。 要建立該文件,請將另一個文件新增至元件資料夾中,並將其命名為`Presentation.tsx` ,然後使用下列程式碼在檔案頂部匯入`React hooks` 、 `icons` 、 `SlideModel`和`Slide`元件。 ``` "use client"; import { useCallback, useMemo, useState } from "react"; import { BackwardIcon, ForwardIcon, PlusIcon, SparklesIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SlideModel, Slide } from "./Slide"; ``` 之後,在上面的程式碼下面加入以下程式碼。程式碼定義了一個`ActionButton`功能元件,它將呈現具有可自訂屬性的按鈕元素。 ``` export const ActionButton = ({ disabled, onClick, className, children, }: { disabled: boolean; onClick: () => void; className?: string; children: React.ReactNode; }) => { return ( <button disabled={disabled} className={`bg-blue-500 text-white font-bold py-2 px-4 rounded ${disabled ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"} ${className}`} onClick={onClick} > {children} </button> ); }; ``` 然後在上面的程式碼下面加入下面的程式碼。程式碼定義了一個名為「Presentation」的功能元件,用於初始化投影片的狀態並定義一個用於更新目前投影片的函數。 ``` // Define the Presentation component as a functional component. export const Presentation = () => { // Initialize state for slides with a default first slide and a state to track the current slide index. const [slides, setSlides] = useState<SlideModel[]>([ { title: `Welcome to our presentation!`, // Title of the first slide. content: 'This is the first slide.', // Content of the first slide. backgroundImageDescription: "hello", // Description for background image retrieval. spokenNarration: "This is the first slide. Welcome to our presentation!", // Spoken narration text for the first slide. }, ]); const [currentSlideIndex, setCurrentSlideIndex] = useState(0); // Current slide index, starting at 0. // Use useMemo to memoize the current slide object to avoid unnecessary recalculations. const currentSlide = useMemo(() => slides[currentSlideIndex], [slides, currentSlideIndex]); // Define a function to update the current slide. This function uses useCallback to memoize itself to prevent unnecessary re-creations. const updateCurrentSlide = useCallback( (partialSlide: Partial<SlideModel>) => { // Update the slides state by creating a new array with the updated current slide. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex), // Copy all slides before the current one. { ...slides[currentSlideIndex], ...partialSlide }, // Merge the current slide with the updates. ...slides.slice(currentSlideIndex + 1), // Copy all slides after the current one. ]); }, [currentSlideIndex, setSlides] // Dependencies for useCallback. ); // The JSX structure for the Presentation component. return ( <div className="relative"> {/* Render the current slide by passing the currentSlide and updateCurrentSlide function as props. */} <Slide slide={currentSlide} partialUpdateSlide={updateCurrentSlide} /> {/* Container for action buttons located at the top-left corner of the screen. */} <div className="absolute top-0 left-0 mt-6 ml-4 z-30"> {/* Action button to add a new slide. Disabled state is hardcoded to true for demonstration. */} <ActionButton disabled={true} onClick={() => { // Define a new slide object. const newSlide: SlideModel = { title: "Title", content: "Body", backgroundImageDescription: "random", spokenNarration: "The speaker's notes for this slide.", }; // Update the slides array to include the new slide. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex + 1), newSlide, ...slides.slice(currentSlideIndex + 1), ]); // Move to the new slide by updating the currentSlideIndex. setCurrentSlideIndex((i) => i + 1); }} className="rounded-r-none" > <PlusIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> {/* Another action button, currently disabled and without functionality. */} <ActionButton disabled={true} onClick={async () => { }} // Placeholder async function. className="rounded-l-none ml-[1px]" > <SparklesIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> </div> {/* Container for action buttons at the top-right corner for deleting slides, etc. */} <div className="absolute top-0 right-0 mt-6 mr-24"> <ActionButton disabled={slides.length === 1} // Disable button if there's only one slide. onClick={() => {}} // Placeholder function for the button action. className="ml-5 rounded-r-none" > <TrashIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> </div> {/* Display current slide number and total slides at the bottom-right corner. */} <div className="absolute bottom-0 right-0 mb-20 mx-24 text-xl" style={{ textShadow: "1px 1px 0 #ddd, -1px -1px 0 #ddd, 1px -1px 0 #ddd, -1px 1px 0 #ddd", }} > Slide {currentSlideIndex + 1} of {slides.length} {/* Current slide and total slides. */} </div> {/* Container for navigation buttons (previous and next) at the bottom-right corner. */} <div className="absolute bottom-0 right-0 mb-6 mx-24"> {/* Button to navigate to the previous slide. */} <ActionButton className="rounded-r-none" disabled={ currentSlideIndex === 0 || true} // Example condition to disable button; 'true' is just for demonstration. onClick={() => { setCurrentSlideIndex((i) => i - 1); // Update currentSlideIndex to move to the previous slide. }} > <BackwardIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> {/* Button to navigate to the next slide. */} <ActionButton className="mr-[1px] rounded-l-none" disabled={ true || currentSlideIndex + 1 === slides.length} // Example condition to disable button; 'true' is just for demonstration. onClick={async () => { setCurrentSlideIndex((i) => i + 1); // Update currentSlideIndex to move to the next slide. }} > <ForwardIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> </div> </div> ); }; ``` 要在瀏覽器上呈現 PowerPoint 應用程式,請前往`/[root]/src/app/page.tsx`檔案並新增以下程式碼。 ``` "use client"; import "./style.css"; import { Presentation } from "./components/Presentation"; export default function AIPresentation() { return ( <Presentation /> ); } ``` 如果您想要在 Powerpoint 應用程式前端新增樣式,請在`/[root]/src/app`資料夾中建立名為`style.css`的檔案。 然後導航[到此 gist 文件](https://gist.github.com/TheGreatBonnie/e7c0b790a2e2af3e669810539ba54fed),複製 CSS 程式碼,並將其新增至 style.css 檔案。 最後,在命令列上執行命令`npm run dev` ,然後導航到 http://localhost:3000/。 現在您應該在瀏覽器上查看 PowerPoint 應用程式,如下所示。 ![PowerPoint應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqcjqqmo1b2oow6y4p76.png) **將 PowerPoint 應用程式與 CopilotKit 後端集成** -------------------------------------- 讓我們先在根目錄中建立一個名為`.env.local`的檔案。然後在保存 ChatGPT 和 Tavily Search API 金鑰的檔案中加入下面的環境變數。 ``` OPENAI_API_KEY="Your ChatGPT API key" TAVILY_API_KEY="Your Tavily Search API key" ``` 若要取得 ChatGPT API 金鑰,請導覽至 https://platform.openai.com/api-keys。 ![ChatGPT API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1u65aswytyym0zpoh5wx.png) 若要取得 Tavilly Search API 金鑰,請導覽至 https://app.tavily.com/home ![泰維利搜尋 API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ugx1oqifnk24l69jjkf.png) 之後,轉到`/[root]/src/app`並建立一個名為`api`的資料夾。在`api`資料夾中,建立一個名為`copilotkit`的資料夾。 在`copilotkit`資料夾中,建立一個名為`research.ts`的檔案。然後導航到[該 Research.ts gist 文件](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c),複製程式碼,並將其新增至**`research.ts`**檔案中 接下來,在`/[root]/src/app/api/copilotkit`資料夾中建立一個名為`route.ts`的檔案。該文件將包含設定後端功能來處理 POST 請求的程式碼。它有條件地包括對給定主題進行研究的“研究”操作。 現在在文件頂部導入以下模組。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit. import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research. import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata. ``` 在上面的程式碼下面,定義一個執行時環境變數和一個註解的函數,以便使用下面的程式碼進行研究。 ``` // Define a runtime environment variable, indicating the environment where the code is expected to run. export const runtime = "edge"; // Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction<any> = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. return await researchWithLangGraph(topic); // Call the research function and return its result. }, }; ``` 然後在上面的程式碼下加入下面的程式碼來定義處理POST請求的非同步函數。 ``` // Define an asynchronous function that handles POST requests. export async function POST(req: Request): Promise<Response> { const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions. // Check if a specific environment variable is set, indicating access to certain functionality. if (process.env["TAVILY_API_KEY"]) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. } // Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, }); // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); } ``` **將 PowerPoint 應用程式與 CopilotKit 前端集成** -------------------------------------- 讓我們先導入`/[root]/src/app/components/Slide.tsx`檔案頂部的`useMakeCopilotActionable`掛鉤。 ``` import { useMakeCopilotActionable } from "@copilotkit/react-core"; ``` 在 Slide 函數中,新增以下程式碼,該程式碼使用`useMakeCopilotActionable`掛鉤來設定一個名為`updateSlide`的操作,該操作具有特定參數以及根據提供的值更新投影片的實作。 ``` useMakeCopilotActionable({ // Defines the action name. This is a unique identifier for the action within the application. name: "updateSlide", // Describes what the action does. In this case, it updates the current slide. description: "Update the current slide.", // Details the arguments that the action accepts. Each argument has a name, type, description, and a flag indicating if it's required. argumentAnnotations: [ { name: "title", // The argument name. type: "string", // The data type of the argument. description: "The title of the slide. Should be a few words long.", // Description of the argument. required: true, // Indicates that this argument must be provided for the action to execute. }, { name: "content", type: "string", description: "The content of the slide. Should generally consists of a few bullet points.", required: true, }, { name: "backgroundImageDescription", type: "string", description: "What to display in the background of the slide. For example, 'dog', 'house', etc.", required: true, }, { name: "spokenNarration", type: "string", description: "The spoken narration for the slide. This is what the user will hear when the slide is shown.", required: true, }, ], // The implementation of the action. This is a function that will be called when the action is executed. implementation: async (title, content, backgroundImageDescription, spokenNarration) => { // Calls a function passed in through props to partially update the slide with new values for the specified properties. props.partialUpdateSlide({ title, content, backgroundImageDescription, spokenNarration, }); }, }, [props.partialUpdateSlide]); // Dependencies array for the custom hook or function. This ensures that the action is re-initialized only when `props.partialUpdateSlide` changes. ``` 之後,請前往`/[root]/src/app/components/Presentation.tsx`檔案並使用下面的程式碼匯入頂部的 CopilotKit 前端套件。 ``` import { useCopilotContext } from "@copilotkit/react-core"; import { CopilotTask } from "@copilotkit/react-core"; import { useMakeCopilotActionable, useMakeCopilotReadable } from "@copilotkit/react-core"; ``` 在演示函數中,加入以下程式碼,該程式碼使用`useMakeCopilotReadable`掛鉤加入`Slides`和`currentSlide`幻燈片陣列作為應用程式內聊天機器人的上下文。掛鉤使副駕駛可以讀取簡報中的整個幻燈片集合以及當前幻燈片的資料。 ``` useMakeCopilotReadable("These are all the slides: " + JSON.stringify(slides)); useMakeCopilotReadable( "This is the current slide: " + JSON.stringify(currentSlide) ); ``` 在`useMakeCopilotReadable`掛鉤下方,新增以下程式碼,該程式碼使用`useCopilotActionable`掛鉤來設定名為`appendSlide`的操作,其中包含說明和加入多張幻燈片的實作函數。 ``` useMakeCopilotActionable( { // Defines the action's metadata. name: "appendSlide", // Action identifier. description: "Add a slide after all the existing slides. Call this function multiple times to add multiple slides.", // Specifies the arguments that the action takes, including their types, descriptions, and if they are required. argumentAnnotations: [ { name: "title", // The title of the new slide. type: "string", description: "The title of the slide. Should be a few words long.", required: true, }, { name: "content", // The main content or body of the new slide. type: "string", description: "The content of the slide. Should generally consist of a few bullet points.", required: true, }, { name: "backgroundImageDescription", // Description for fetching or generating the background image of the new slide. type: "string", description: "What to display in the background of the slide. For example, 'dog', 'house', etc.", required: true, }, { name: "spokenNarration", // Narration text that will be read aloud during the presentation of the slide. type: "string", description: "The text to read while presenting the slide. Should be distinct from the slide's content, and can include additional context, references, etc. Will be read aloud as-is. Should be a few sentences long, clear, and smooth to read.", required: true, }, ], // The function to execute when the action is triggered. It creates a new slide with the provided details and appends it to the existing slides array. implementation: async (title, content, backgroundImageDescription, spokenNarration) => { const newSlide: SlideModel = { // Constructs the new slide object. title, content, backgroundImageDescription, spokenNarration, }; // Updates the slides state by appending the new slide to the end of the current slides array. setSlides((slides) => [...slides, newSlide]); }, }, [setSlides] // Dependency array for the hook. This action is dependent on the `setSlides` function, ensuring it reinitializes if `setSlides` changes. ); ``` 在上面的程式碼下方,定義一個名為`context`的變數,該變數使用名為`useCopilotContext`的自訂掛鉤從 copilot 上下文中檢索當前上下文。 ``` const context = useCopilotContext(); ``` 之後,定義一個名為`generateSlideTask`的函數,它包含一個名為`CopilotTask`的類別。 `CopilotTask`類別定義用於產生與簡報的整體主題相關的新投影片的指令 ``` const generateSlideTask = new CopilotTask({ instructions: "Make the next slide related to the overall topic of the presentation. It will be inserted after the current slide. Do NOT carry any research", }); ``` 然後在上面的程式碼下面初始化一個名為`generateSlideTaskRunning`的狀態變數,預設值為false。 ``` const [generateSlideTaskRunning, **setGenerateSlideTaskRunning**] = useState(false); ``` 之後,使用下面的程式碼更新簡報元件中的操作按鈕,以透過新增、刪除和導覽投影片來新增動態互動。 ``` // The JSX structure for the Presentation component. return ( <div className="relative"> {/* Renders the current slide using a Slide component with props for the slide data and a method to update it. */} <Slide slide={currentSlide} partialUpdateSlide={updateCurrentSlide} /> {/* Container for action buttons positioned at the top left corner of the relative parent */} <div className="absolute top-0 left-0 mt-6 ml-4 z-30"> {/* ActionButton to add a new slide. It is disabled when a generateSlideTask is running to prevent concurrent modifications. */} <ActionButton disabled={generateSlideTaskRunning} onClick={() => { const newSlide: SlideModel = { title: "Title", content: "Body", backgroundImageDescription: "random", spokenNarration: "The speaker's notes for this slide.", }; // Inserts the new slide immediately after the current slide and updates the slide index to point to the new slide. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex + 1), newSlide, ...slides.slice(currentSlideIndex + 1), ]); setCurrentSlideIndex((i) => i + 1); }} className="rounded-r-none" > <PlusIcon className="h-6 w-6" /> </ActionButton> {/* ActionButton to generate a new slide based on the current context, also disabled during task running. */} <ActionButton disabled={generateSlideTaskRunning} onClick={async () => { setGenerateSlideTaskRunning(true); // Indicates the task is starting. await generateSlideTask.run(context); // Executes the task with the current context. setGenerateSlideTaskRunning(false); // Resets the flag when the task is complete. }} className="rounded-l-none ml-[1px]" > <SparklesIcon className="h-6 w-6" /> </ActionButton> </div> {/* Container for action buttons at the top right, including deleting the current slide and potentially other actions. */} <div className="absolute top-0 right-0 mt-6 mr-24"> {/* ActionButton for deleting the current slide, disabled if a task is running or only one slide remains. */} <ActionButton disabled={generateSlideTaskRunning || slides.length === 1} onClick={() => { console.log("delete slide"); // Removes the current slide and resets the index to the beginning as a simple handling strategy. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex), ...slides.slice(currentSlideIndex + 1), ]); setCurrentSlideIndex((i) => 0); }} className="ml-5 rounded-r-none" > <TrashIcon className="h-6 w-6" /> </ActionButton> </div> {/* Display showing the current slide index and the total number of slides. */} <div className="absolute bottom-0 right-0 mb-20 mx-24 text-xl" style={{ textShadow: "1px 1px 0 #ddd, -1px -1px 0 #ddd, 1px -1px 0 #ddd, -1px 1px 0 #ddd", }} > Slide {currentSlideIndex + 1} of {slides.length} </div> {/* Navigation buttons to move between slides, disabled based on the slide index or if a task is running. */} <div className="absolute bottom-0 right-0 mb-6 mx-24"> {/* Button to move to the previous slide, disabled if on the first slide or a task is running. */} <ActionButton className="rounded-r-none" disabled={generateSlideTaskRunning || currentSlideIndex === 0} onClick={() => { setCurrentSlideIndex((i) => i - 1); }} > <BackwardIcon className="h-6 w-6" /> </ActionButton> {/* Button to move to the next slide, disabled if on the last slide or a task is running. */} <ActionButton className="mr-[1px] rounded-l-none" disabled={generateSlideTaskRunning || currentSlideIndex + 1 === slides.length} onClick={async () => { setCurrentSlideIndex((i) => i + 1); }} > <ForwardIcon className="h-6 w-6" /> </ActionButton> </div> </div> ); ``` 現在讓我們轉到`/[root]/src/app/page.tsx`文件,使用下面的程式碼匯入 CopilotKit 前端包和文件頂部的樣式。 ``` import { CopilotKit, } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; import "@copilotkit/react-textarea/styles.css"; ``` 然後使用`CopilotKit`和`CopilotSidebar`來包裝Presentation元件,如下所示。 ``` export default function AIPresentation() { return ( <CopilotKit url="/api/copilotkit/"> <CopilotSidebar instructions="Help the user create and edit a powerpoint-style presentation. IMPORTANT NOTE: SOMETIMES you may want to research a topic, before taking further action. BUT FIRST ASK THE USER if they would like you to research it. If they answer 'no', do your best WITHOUT researching the topic first." defaultOpen={true} labels={{ title: "Presentation Copilot", initial: "Hi you! 👋 I can help you create a presentation on any topic.", }} clickOutsideToClose={false} > <Presentation /> </CopilotSidebar> </CopilotKit> ); } ``` 之後,執行開發伺服器並導航到 http://localhost:3000/。您應該會看到應用程式內聊天機器人已整合到 PowerPoint Web 應用中。 ![應用程式內聊天機器人](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rb2g54qslrrfxyx2pbcy.png) 最後,給右側的聊天機器人一個提示,例如“在 JavaScript 上建立 PowerPoint 簡報”,聊天機器人將開始產生回應,完成後,使用底部的前進按鈕瀏覽產生的幻燈片。 注意:如果聊天機器人沒有立即產生投影片,請根據其回應給予適當的後續提示。 ![PowerPoint簡報](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6dl4av0asoeokzopwra.png) 結論 -- 總而言之,您可以使用 CopilotKit 建立應用內 AI 聊天機器人,該機器人可以查看當前應用程式狀態並在應用程式內執行操作。 AI 聊天機器人可以與您的應用程式前端、後端和第三方服務對話。 完整的原始碼:https://github.com/TheGreatBonnie/aipoweredpowerpointapp --- 原文出處:https://dev.to/copilotkit/how-to-build-an-ai-powered-powerpoint-generator-langchain-copilotkit-openai-nextjs-4c76

身為軟體工程師,提升我工作效率的工具

作為開發人員,**確定工具的優先順序至關重要,**因為它們對於實現您的目標至關重要。熟練是有價值的,但正確的工具可以增強這些技能,從而在您的領域中取得更大的成功。 在本文中,我將分享我每天使用的提高工作效率的工具。這些工具幫助我完成各種任務,包括文件、線框圖、開發、測試、除錯和研究。 我將這些工具分為三類:*任務管理*、*開發*和*文件*。 **讓我們事不宜遲地深入研究這些工具。** 任務管理工具:讓事情井井有條 -------------- 對於軟體開發人員來說,保持任務有序非常重要。無論您計劃的是本月、一周還是今天,都沒關係。寫下所有任務會很有幫助,這樣您就可以了解自己的表現。 我主要使用兩個工具: **Notion**和**Linear** 。 ### Notion 當您是軟體工程師時,您經常需要組織您的工作、快速做筆記,甚至即時編寫一些文件。概念對此非常有用。 Notion讓我可以輕鬆地整理我的想法、規劃我的內容並安排我的工作。日曆範本使用簡單,您可以根據自己的喜好進行更改,並且可以加入許多詳細資訊(例如標籤)來追蹤您的任務。 我使用 Notion 來規劃我的內容。 ![概念工作區](https://cdn.hashnode.com/res/hashnode/image/upload/v1709480859081/0841cd7a-18f5-4dd7-8ad4-48d5cec3001b.png) 概念也有利於團隊追蹤任務。但是,我要討論的下一個工具對於管理軟體開發任務來說更加簡單。 我真的不喜歡到處移動門票或花很多時間在門票報告上。這個工具讓這些任務變得更容易,我認識的許多開發人員都喜歡每天使用它。這就是為什麼我想介紹 Linear。 ### [Linear](https://linear.app/) 我之前嘗試過使用 Trello 或 Jira 等工具,但我不太喜歡它。 Trello 太簡單,功能不多,而 Jira 功能很多,但使用起來很複雜(甚至 GitLab 的 Issue board 似乎更好)。 然後我找到了 Linear,它是為像我們這樣的開發者設計的。 Linear 可以輕鬆實現工作流程自動化並整合其他工具,而不會使事情變得複雜。而且用起來真的很好。使用線性,您可以獲得: - 根據您的 PR/MR 變更或進度自動更新票證。 - 複製分支名稱的簡單方法。 - 不傷眼的深色模式。 - 鍵盤快捷鍵可讓您在應用程式中快速移動。 - 使用起來既快速又有趣。 使用 Linear,我不會花太多時間在任務管理上,因此我可以更專注於編碼。 現在我們已經討論瞭如何管理任務,接下來我將分享我用於文件編寫的工具。 文件工具:軟體工程的支柱 ------------ 文件是軟體工程的基石,以至於人們常說,最好的開發人員花在編寫文件的時間比編寫程式碼的時間還要多。它有多種用途,從規劃和假設建立到追蹤效能、教育用戶以及詳細說明功能或錯誤。 在這裡,我將分享我用於文件編寫的工具,從文字編寫到圖形建立。 ### [Obsidian](https://obsidian.md/) 雖然 Notion 是一個很棒的工具,許多人可能想知道為什麼它不是我的文件首選,但我發現它更傾向於記筆記。儘管 Notion 的小部件增強了其功能,但我最近需要一個簡單的離線工具來組織想法並有效地將它們連結起來。 Obsidian 在這一領域表現出色,在反向連結和創意組織方面超越了 Notion。 ![黑曜石接口](https://cdn.hashnode.com/res/hashnode/image/upload/v1709482594433/228c2d3a-14a8-4326-a76e-a6c793ec36f2.png) Obsidian 提供了一套廣泛的筆記記錄和知識管理功能。它的知識圖直觀地表示了筆記之間的聯繫,有助於深入挖掘資訊。完整的 Markdown 支援允許靈活且強大的格式設定。 該應用程式的離線功能確保其無需網路連接即可使用,拼字檢查、API 支援以及將筆記發佈為網站或使用統一筆記結構模板的能力等其他功能也很突出。 ![知識圖譜](https://cdn.hashnode.com/res/hashnode/image/upload/v1709482699496/09473cc6-4022-4407-82d4-d3ba31b56bad.png) 我主要使用 Obsidian 來整理我的筆記。組織好後,我將它們轉移到 Notion 進行共享,因為 Obsidian 缺乏共享和同步功能。儘管如此,與 Notion 相比,Obsidian 仍然是我首選的文件工具。 然而,Notion和Obsidian只能幫助你寫文件。那麼,一些視覺效果怎麼樣呢?我們來談談[Excalidraw](https://excalidraw.com/) 。 ### [Excalidraw](https://excalidraw.com/) 向遠距工作的過渡讓我懷念使用記號筆和白板進行腦力激盪的簡單性。當語言無法表達時,視覺效果可以彌補理解複雜想法的差距。 Excalidraw 以數位方式重新建立白板體驗,這對於補充文件的快速圖表或插圖具有無價的價值。 這是我建立的圖表範例,用於闡明 React 元件生命週期。 ![React 元件生命週期圖](https://cdn.hashnode.com/res/hashnode/image/upload/v1709483920056/7325dab0-f384-4f02-917d-28a56b869ceb.png) 這些工具構成了我作為軟體工程師的文件實踐的基礎。接下來,我們將探討提高編碼效率的開發工具。 開發工具 ---- 多年來,我的開發工具發生了很大變化,隨著最近人工智慧的引入和大量使用,我發現自己發現了更多可以幫助我作為軟體工程師提高工作效率的工具。但在討論人工智慧工具之前,我們先來談談程式設計和測試工具。 我是軟體工程師,使用 Django、Next.js,有時也使用 Golang 進行開發。我建立了為資料提供服務的 API 和/或使用這些資料的接口,因此編碼和測試我的工作非常重要。這就是 Jetbrains 發揮作用的地方。 ### 編碼工具 [Jetbrains](https://www.jetbrains.com/)提供了非常強大的 IDE,讓您的工作變得更輕鬆。我堅信他們為開發人員打造了最好的 IDE。我認為,無需配置即可立即開始編碼,這是一個很大的優勢。 這是我離開使用 VsCode 的原因之一(嗯,我仍然將它用於快速專案或不太複雜的專案),因為我每次都需要同步才能確保我可以開始工作。例如,當使用 Webstorm 啟動 Next.js 專案時,我只需選擇在每次儲存時執行 Eslint、prettier 的選項,還可以自動設定可以在寫入提交之前執行的 git 掛鉤。 [Webstorm](https://www.jetbrains.com/webstorm/) IDE 還有一個漂亮的 UI,用於在偵錯模式下執行專案,而且功能非常強大。我在 Pycharm 和 Goland 上也經歷過。這些 IDE 功能強大且使用起來非常簡單。 不要誤會我的意思,VsCode 已經很強大了,但是當涉及到執行基本任務時,沒有太多麻煩或配置,例如:搜尋、重構、Git 任務(獲取、拉取、推送、PR/MR 管理等)。 感謝 Jetbrains 團隊製作如此強大的工具。 ### 測試:Insomnia、Postman 起初,我使用[Postman](https://www.postman.com/)來測試API,因為它有很多功能。但我改用了[Insomnia](https://insomnia.rest/) ,因為它更容易使用並且讓一切井井有條。 Insomnia 的一個大問題是,當它讓我建立一個帳戶來繼續使用它時,它刪除了我所有保存的工作。 這讓我在一年後又回到了 Postman。 Postman 沒有太大變化,但它有一些我非常喜歡的新的、更好的功能。現在,我又回到了 Postman,因為它感覺像是我熟悉的東西,但也有新的東西。 Insomnia 使用起來很簡單,但每次打開筆記型電腦時都必須登錄,這很煩人。本來可以很棒,但這些問題讓我開始尋找別的東西。 現在,我正在考慮嘗試[Bruno](https://www.usebruno.com/) ,這是我聽說過的新工具。 Bruno 擁有您想要的所有功能,例如 Websocket 的支援。 Bruno 的優點是一次性支付僅需 19 美元,看起來很划算。我想看看它對我來說效果如何,是否像聽起來那麼好。我很高興嘗試一下,也許稍後再討論。 ### 人工智慧工具 我經常使用 ChatGPT 和[Phind.ai](https://www.phind.com/)來撰寫技術文章、除錯和集思廣益解決方案。雖然有些人可能對他們的回答持保留態度,但我發現它們是有用的指南,補充了我自己的研究。 [Phind.ai](https://www.phind.com/)對於提供進一步探索和加強研究過程的連結特別有價值。 其他 AI 工具(例如[Copilot](https://github.com/features/copilot)和[Codium.ai)](https://www.codium.ai/)與流行的編輯器和 IDE(例如 VSCode)很好地集成,從而提高您的技能和生產力。 在編碼中有效使用人工智慧需要清楚了解您的目標。在沒有紮實掌握底層技術和清晰的溝通技巧的情況下,不建議初學者開始使用人工智慧進行編碼。一旦您掌握了這些技能,人工智慧工具就可以極大地有益於您的工作。 結論 -- 這是我很久以來第一次寫一篇與程式設計無關的文章。由於生產力是軟體工程的一個重要方面,因此我希望撰寫更多有關幫助我成為更好的軟體工程師的工具或策略的文章。 如果您對本文有疑問或回饋,請在評論中分享。您的意見有助於使該資源更好地服務每個人。以下是我們在本文中所使用的資源。 目前為止就這樣了。快樂編碼!🚀 --- 原文出處:https://dev.to/koladev/tools-that-make-me-productive-as-a-software-engineer-2dge

30 個 JavaScript 奇妙小技巧

歡迎使用我們精選的 JavaScript 技巧集合,它將幫助您優化程式碼、使其更具可讀性並節省您的時間。 讓我們深入研究 JavaScript 的功能和超越傳統的技巧,並發現這種強大的程式語言的全部潛力。 ### 1. 使用!!轉換為布林值 使用雙重否定快速將任何值轉換為布林值。 ``` let truthyValue = !!1; // true let falsyValue = !!0; // false ``` ### 2. 預設功能參數 設定函數參數的預設值以避免未定義的錯誤。 ``` function greet(name = "Guest") { return `Hello, ${name}!`; } ``` ### 3. 短 if-else 的三元運算符 `if-else`語句的簡寫。 ``` let price = 100; let message = price > 50 ? "Expensive" : "Cheap"; ``` ### 4. 動態字串的範本文字 使用模板文字在字串中嵌入表達式。 ``` let item = "coffee"; let price = 15; console.log(`One ${item} costs $${price}.`); ``` ### 5. 解構賦值 輕鬆從物件或陣列中提取屬性。 ``` let [x, y] = [1, 2]; let {name, age} = {name: "Alice", age: 30}; ``` ### 6. 用於陣列和物件克隆的擴展運算符 克隆陣列或物件而不引用原始陣列或物件。 ``` let originalArray = [1, 2, 3]; let clonedArray = [...originalArray]; ``` ### 7. 短路評估 使用邏輯運算子進行條件執行。 ``` let isValid = true; isValid && console.log("Valid!"); ``` ### 8. 可選連結 (?.) 如果引用為`nullish`則可以安全地存取巢狀物件屬性,而不會出現錯誤。 ``` let user = {name: "John", address: {city: "New York"}}; console.log(user?.address?.city); // "New York" ``` ### 9. 空合併運算子 (??) 使用`??`為`null`或`undefined`提供預設值。 ``` let username = null; console.log(username ?? "Guest"); // "Guest" ``` [![monday.com 的互動式橫幅展示了在數位介面上組織工作流程任務的雙手,並帶有「告訴我如何做」號召性用語按鈕。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xd7qdmxdd726kskelydk.png)](https://try.monday.com/9xf9ftaa4i2f) ### 10. 使用`map` 、 `filter`和`reduce`進行陣列操作 無需傳統循環即可處理陣列的優雅方法。 ``` // Map let numbers = [1, 2, 3, 4]; let doubled = numbers.map(x => x * 2); // Filter const evens = numbers.filter(x => x % 2 === 0); // Reduce const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); ``` ### 11.標記模板文字 使用模板文字進行函數呼叫以進行自訂字串處理。 ``` function highlight(strings, ...values) { return strings.reduce((prev, current, i) => `${prev}${current}${values[i] || ''}`, ''); } let price = 10; console.log(highlight`The price is ${price} dollars.`); ``` ### 12.使用Object.entries()和Object.fromEntries() 將物件轉換為陣列並返回以方便操作。 ``` let person = {name: "Alice", age: 25}; let entries = Object.entries(person); let newPerson = Object.fromEntries(entries); ``` ### 13. 唯一元素的集合物件 使用 Set 儲存任何類型的唯一值。 ``` let numbers = [1, 1, 2, 3, 4, 4]; let uniqueNumbers = [...new Set(numbers)]; ``` ### 14. 物件中的動態屬性名稱 在物件文字表示法中使用方括號來建立動態屬性名稱。 ``` let dynamicKey = 'name'; let person = {[dynamicKey]: "Alice"}; ``` ### 15. 使用bind()進行函數柯里化 建立一個新函數,在呼叫時將其 this 關鍵字設定為提供的值。 ``` function multiply(a, b) { return a * b; } let double = multiply.bind(null, 2); console.log(double(5)); // 10 ``` ### 16. 使用 Array.from() 從類別陣列物件建立陣列 將類似陣列或可迭代的物件轉換為真正的陣列。 ``` let nodeList = document.querySelectorAll('div'); let nodeArray = Array.from(nodeList); ``` ### 17. 可迭代物件的 for...of 循環 直接迭代可迭代物件(包括陣列、映射、集合等)。 ``` for (let value of ['a', 'b', 'c']) { console.log(value); } ``` ### 18. 使用 Promise.all() 實作並發 Promise 同時執行多個 Promise 並等待所有的都解決。 ``` let promises = [fetch(url1), fetch(url2)]; Promise.all(promises) .then(responses => console.log('All done')); ``` ### 19. 函數參數的剩餘參數 將任意數量的參數捕獲到陣列中。 ``` function sum(...nums) { return nums.reduce((acc, current) => acc + current, 0); } ``` [![Coursera Plus 訂閱產品包括 AWS 基礎、Google IT 支援專業憑證和商業網路安全專業化。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ys5gk2tfzcn4iniuq48s.png)](https://imp.i384100.net/c/3922519/1320997/14726) ### 20. 用於性能優化的記憶 儲存函數結果以避免冗餘處理。 ``` const memoize = (fn) => { const cache = {}; return (...args) => { let n = args[0]; // assuming single argument for simplicity if (n in cache) { console.log('Fetching from cache'); return cache[n]; } else { console.log('Calculating result'); let result = fn(n); cache[n] = result; return result; } }; }; ``` ### 21. 使用 ^ 交換值 使用 XOR 以位元運算子交換兩個變數的值,無需使用臨時變數。 ``` let a = 1, b = 2; a ^= b; b ^= a; a ^= b; // a = 2, b = 1 ``` ### 22. 使用 flat() 展平陣列 使用`flat()`方法輕鬆展平巢狀陣列,並將展平深度作為可選參數。 ``` let nestedArray = [1, [2, [3, [4]]]]; let flatArray = nestedArray.flat(Infinity); ``` ### 23. 用一元加法轉換為數字 使用一元加運算子快速將字串或其他值轉換為數字。 ``` let str = "123"; let num = +str; // 123 as a number ``` ### 24. HTML 片段的模板字串 使用模板字串建立 HTML 片段,使動態 HTML 生成更加清晰。 ``` let items = ['apple', 'orange', 'banana']; let html = `<ul>${items.map(item => `<li>${item}</li>`).join('')}</ul>`; ``` ### 25. 使用 Object.assign() 合併物件 將多個來源物件合併到一個目標物件中,有效地組合它們的屬性。 ``` let obj1 = { a: 1 }, obj2 = { b: 2 }; let merged = Object.assign({}, obj1, obj2); ``` [![符合人體工學的垂直滑鼠旨在減輕手腕壓力](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56c0z4lzxtkthnnk8gsb.jpg)](https://amzn.to/3UXGIyx) 使用符合人體工學的滑鼠優化您的編程設置,專為舒適和長時間的編碼會話而定制。 ### 26. 預設值短路 處理潛在的未定義或空變數時,使用邏輯運算子指派預設值。 ``` let options = userOptions || defaultOptions; ``` ### 27. 使用括號表示法動態存取物件屬性 使用括號表示法動態存取物件的屬性,當屬性名稱儲存在變數中時非常有用。 ``` let property = "name"; let value = person[property]; // Equivalent to person.name ``` ### 28. 使用 Array.includes() 進行存在檢查 使用includes() 檢查陣列是否包含某個值,它是indexOf 的更清晰的替代方法。 ``` if (myArray.includes("value")) { // Do something } ``` ### 29. Function.prototype.bind() 的強大功能 將函數綁定到上下文(此值)並部分套用參數,以建立更多可重複使用和模組化的程式碼。 ``` const greet = function(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`; }; const greetJohn = greet.bind({name: 'John'}, 'Hello'); console.log(greetJohn('!')); // "Hello, John!" ``` ### 30.防止物件修改 使用`Object.freeze()`防止物件進行修改,使其不可變。對於更深層的不變性,請考慮更徹底地強制不變性的函式庫。 ``` let obj = { name: "Immutable" }; Object.freeze(obj); obj.name = "Mutable"; // Fails silently in non-strict mode ``` 我希望這些 JavaScript 技巧為您提供如何進行[JavaScript 程式設計的](https://www.w3schools.com/js/)新視角。 從利用模板文字的簡潔功能到掌握`map` 、 `filter`和`reduce`的效率,這些 JavaScript 技巧將豐富您的開發工作流程並激發您的下一個專案。 讓這些 JavaScript 技巧不僅可以完善您目前的專案,還可以在您的[程式設計之旅](https://www.webdevstory.com/programming-roadmap/)中激發未來創新的靈感。 ***支持我們的技術見解*** [![請我喝杯咖啡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsm9uucbnw7x9iw0loxr.png)](https://www.buymeacoffee.com/mmainulhasan) [![透過 PayPal 按鈕捐贈](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipnhbim2ba56kt32zhn3.png)](https://www.paypal.com/donate/?hosted_button_id=GDUQRAJZM3UR8) 注意:此頁面上的某些連結可能是附屬連結。如果您透過這些連結進行購買,我可能會賺取少量佣金,而無需您支付額外費用。感謝您的支持! --- 原文出處:https://dev.to/mmainulhasan/30-javascript-tricky-hacks-gfc

100 多個專案創意

**編輯**:大家好!在對本文做出驚人反應後,我建立了一個名為「每週專案俱樂部」的專案。每週您的收件匣都會收到需要解決的問題。你可以努力解決問題,並且你將得到整個俱樂部的幫助,讓你走上正軌。了解更多並[在這裡](https://weeklyproject.club)註冊! 有一天我注意到一個模式。我注意到很多人都在努力 學習編程,但他們心中沒有特定的目標。我已經討論過如何了解您想要學習程式設計的原因可以幫助您選擇要學習的語言[!](https://pickaframework.com/articles/why/) ,以及如何實際做出決定([在這裡!](https://pickaframework.com/feature_fishing/) )但是專案有什麼幫助呢? 當我指導程式設計師時,我發現有一個專案可以幫助排除其他一些幹擾,例如想知道你是否使用了正確的語言。透過專注於一個特定的目標,你就不用那麼費力去擔心*這*是否正是你應該使用的語言。結果是你建立了一些簡潔的東西,並且一路上你學到了一些東西! 2隻鳥,1塊石頭。 這就是為什麼我為初學者程式設計師策劃了這個專案清單。許多人列出了大量的專案來學習編程,但很少按照難度進行組織。我瀏覽了幾個流行的程式設計專案想法清單。如果您想查看完整列表,可以在頁面底部找到來源。 我將其分為教程和想法。教程包含資源連結,而想法只是專案的一般描述。我還列出了我最喜歡的初學者清單。 看看,看看是否有什麼啟發你! 教學 == 我的最愛 ---- - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) 簡單的 --- - [使用 C# 和 Xamarin 建立空白應用程式(正在進行中)](https://www.intertech.com/Blog/xamarin-tutorial-part-1-create-a-blank-app/) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立加載畫面](https://medium.freecodecamp.org/how-to-build-a-delightful-loading-screen-in-5-minutes-847991da509f) - [使用 JS 建立 HTML 計算器](https://medium.freecodecamp.org/how-to-build-an-html-calculator-app-from-scratch-using-javascript-4454b8714b98) - [建立 React Native Todo 應用程式](https://egghead.io/courses/build-a-react-native-todo-application) - 使用 Node.js 編寫 Twitter 機器人 ``` - [Part 1](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-in-just-38-lines-of-code-ed92db9eb078) ``` ``` - [Part 2](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-part-2-do-more-2ef1e039715d) ``` - [建立一個簡單的 RESTFUL Web 應用程式](https://closebrace.com/tutorials/2017-03-02/creating-a-simple-restful-web-app-with-nodejs-express-and-mongodb) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [建立一個工作抓取 Web 應用程式](https://medium.freecodecamp.org/how-i-built-a-job-scraping-web-app-using-node-js-and-indreed-7fbba124bbdc) - [使用 Python 挖掘 Twitter 資料](https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/) - [使用 Scrapy 和 MongoDB 抓取網站](https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/) - [如何使用 Python 和 Selenium WebDriver 進行抓取](http://www.byperth.com/2018/04/25/guide-web-scraping-101-what-you-need-to-know-and-how-to-scrape-with-python-selenium-webdriver/) - [我應該使用 BeautifulSoup 觀看哪部電影](https://medium.com/@nishantsahoo.in/which-movie-should-i-watch-5c83a3c0f5b1) - [使用 Flask 建立微博](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) - 在 Django 中建立部落格 Web 應用程式 ``` - [Part I : Introduction](https://tutorial.djangogirls.org/en/) ``` ``` - [Part II : Extension To Add More Features](https://legacy.gitbook.com/book/djangogirls/django-girls-tutorial-extensions/details) ``` - [選擇您自己的冒險演示](https://www.twilio.com/blog/2015/03/choose-your-own-adventures-presentations-wizard-mode-part-1-of-3.html) - [使用 Flask 和 RethinkDB 建立待辦事項列表](https://realpython.com/blog/python/rethink-flask-a-simple-todo-list-powered-by-flask-and-rethinkdb/) 中等的 --- - [透過建立簡單的 RPG 遊戲來學習 C#](http://scottlilly.com/learn-c-by-building-a-simple-rpg-index/) - [用 C# 創作 Rogue-like 遊戲](https://roguesharp.wordpress.com/) - [使用 Clojure 建構 Twitter 機器人](http://howistart.org/posts/clojure/1/index.html) - [建立拼字檢查器](https://bernhardwenzel.com/articles/clojure-spellchecker/) - [使用 Java 建立簡單的 HTTP 伺服器](http://javarevisited.blogspot.com/2015/06/how-to-create-http-server-in-java-serversocket-example.html) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [建立具有使用者身份驗證的 Spring Boot 應用程式](https://scotch.io/tutorials/build-a-spring-boot-app-with-user-authentication) - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [使用純 JS 建立應用程式](https://medium.com/codingthesmartway-com-blog/pure-javascript-building-a-real-world-application-from-scratch-5213591cfcd6) - [建立無伺服器 React.js 應用程式](http://serverless-stack.com/) - [建立 Trello 克隆](http://codeloveandboards.com/blog/2016/01/04/trello-tribute-with-phoenix-and-react-pt-1/) - [使用 React、Node、MongoDB 和 SocketIO 建立角色投票應用程式](http://sahatyalkabov.com/create-a-character-voting-app-using-react-nodejs-mongodb-and-socketio/) - [React 教學:克隆 Yelp](https://www.fullstackreact.com/articles/react-tutorial-cloning-yelp/) - [使用 React.js 和 Node.js 建立簡單的中型克隆](https://codeburst.io/build-simple-medium-com-on-node-js-and-react-js-a278c5192f47) - [在 JS 中整合 MailChimp](https://medium.freecodecamp.org/how-to-integrate-mailchimp-in-a-javascript-web-app-2a889fb43f6f) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立新聞應用程式](https://medium.freecodecamp.org/create-a-news-app-using-react-native-ced249263627) - [學習 React 的 Webpack](https://medium.freecodecamp.org/learn-webpack-for-react-a36d4cac5060) - [建立您自己的 React 樣板](https://medium.freecodecamp.org/how-to-build-your-own-react-boilerplate-2f8cbbeb9b3f) - [基本 React+Redux 入門教學](https://hackernoon.com/a-basic-react-redux-introductory-tutorial-adcc681eeb5e) - [建立一個預約安排程序](https://hackernoon.com/build-an-appointment-scheduler-using-react-twilio-and-cosmic-js-95377f6d1040) - 使用 Angular 2+ 建立具有離線功能的 Hacker News 用戶端 ``` - [Part 1](https://houssein.me/angular2-hacker-news) ``` ``` - [Part 2](https://houssein.me/progressive-angular-applications) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` 難的 -- - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 14 章是用 C 寫的) - [用 C 語言寫一個 Shell](https://brennan.io/2015/01/16/write-a-shell-in-c/) - [編寫 FUSE 文件系統](https://www.cs.nmsu.edu/~pfeiffer/fuse-tutorial/) - [建立您自己的文字編輯器](http://viewsourcecode.org/snaptoken/kilo/) - [建立自己的 Lisp](http://www.buildyourownlisp.com/) - [建構 CoreWiki](https://www.youtube.com/playlist?list=PLVMqA0_8O85yC78I4Xj7z48ES48IQBa7p)這是一個 Wiki 風格的內容管理系統,完全用 C# 使用 ASP.NET Core 和 Razor Pages 編寫。您可以[在這裡](https://github.com/csharpfritz/CoreWiki)找到原始程式碼。 - [建構 JIRA 與 Clojure 和 Atlassian Connect 的集成](https://hackernoon.com/building-a-jira-integration-with-clojure-atlassian-connect-506ebd112807) - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 4-13 章是用 Java 寫的) - [使用 Mocha、React、Redux 和 Immutable 透過測試優先開發來建立全端電影投票應用程式](https://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html) - [使用 React 和 Node 建立 Twitter Stream](https://scotch.io/tutorials/build-a-real-time-twitter-stream-with-node-and-react-js) - 使用 Webtask.io 建立無伺服器 MERN Story 應用程式 ``` - [Part 1](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-1) ``` ``` - [Part 2](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-2) ``` - [使用 React + Parcel 建立 Chrome 擴充功能](https://medium.freecodecamp.org/building-chrome-extensions-in-react-parcel-79d0240dd58f) ``` [Testing React App With Pupepeteer and Jest](https://blog.bitsrc.io/testing-your-react-app-with-puppeteer-and-jest-c72b3dfcde59) ``` - [用 React 編寫生命遊戲](https://medium.freecodecamp.org/create-gameoflife-with-react-in-one-hour-8e686a410174) - [建立帶有情感分析的聊天應用程式](https://codeburst.io/build-a-chat-app-with-sentiment-analysis-using-next-js-c43ebf3ea643) - [建立全端 Web 應用程式設置](https://hackernoon.com/full-stack-web-application-using-react-node-js-express-and-webpack-97dbd5b9d708) - 建立隨機報價機 ``` - [Part 1](https://www.youtube.com/watch?v=3QngsWA9IEE) ``` ``` - [Part 2](https://www.youtube.com/watch?v=XnoTmO06OYo) ``` ``` - [Part 3](https://www.youtube.com/watch?v=us51Jne67_I) ``` ``` - [Part 4](https://www.youtube.com/watch?v=iZx7hqHb5MU) ``` ``` - [Part 5](https://www.youtube.com/watch?v=lpba9vBqXl0) ``` ``` - [Part 6](https://www.youtube.com/watch?v=Jvp8j6zrFHE) ``` ``` - [Part 7](https://www.youtube.com/watch?v=M_hFfrN8_PQ) ``` - 使用 Angular 6 建立美麗的現實世界應用程式: ``` - [Part I](https://medium.com/@hamedbaatour/build-a-real-world-beautiful-web-app-with-angular-6-a-to-z-ultimate-guide-2018-part-i-e121dd1d55e) ``` - [使用 BootStrap 4 和 Angular 6 建立響應式佈局](https://medium.com/@tomastrajan/how-to-build-responsive-layouts-with-bootstrap-4-and-angular-6-cfbb108d797b) - [使用 Django 和測試驅動開發建立待辦事項列表](http://www.obeythetestinggoat.com/) - [使用 Python 建立 RESTful 微服務](http://www.skybert.net/python/developing-a-restful-micro-service-in-python/) - [使用 Docker、Flask 和 React 的微服務](https://testdriven.io/) - [使用 Flask 建立簡單的 Web 應用程式](https://pythonspot.com/flask-web-app-with-python/) - [使用 Flask 建立 RESTful API – TDD 方式](https://scotch.io/tutorials/build-a-restful-api-with-flask-the-tdd-way) - [在 20 分鐘內建立 Django API](https://codeburst.io/create-a-django-api-in-under-20-minutes-2a082a60f6f3) 想法 == 簡單的 --- ### 99 瓶 - 建立一個程序,列印歌曲“牆上的 99 瓶啤酒”的每一行。 - 不要使用所有數字的列表,也不要手動輸入所有數字。請改用內建函數。 - 除了短語“取下一個”之外,您不得直接在歌詞中輸入任何數字/數字名稱。 - 請記住,當您還剩下 1 瓶時,「瓶子」一詞將變為單數。 ### 魔術8球 - 模擬神奇的 8 球。 - 允許使用者輸入他們的問題。 - 顯示正在進行的訊息(即“思考”)。 - 建立 20 個回應,並顯示隨機回應。 - 允許用戶提出另一個問題或退出。 - 獎金: ``` - Add a gui. ``` ``` - It must have a box for users to enter the question. ``` ``` - It must have at least 4 buttons: ``` ``` - ask ``` ``` - clear (the text box) ``` ``` - play again ``` ``` - quit (this must close the window) ``` ### 石頭剪刀布遊戲 - 建立一個石頭剪刀布遊戲。 - 讓玩家選擇石頭、剪刀或布。 - 讓計算機選擇它的移動方式。 - 比較選擇並決定誰獲勝。 - 列印結果。 - 子目標: ``` - Give the player the option to play again. ``` ``` - Keep a record of the score (e.g. Player: 3 / Computer: 6). ``` ### 倒數時鐘 - 建立一個程序,允許使用者選擇時間和日期,然後以給定的時間間隔(例如每秒)列印一條訊息,告訴使用者距離所選時間還有多長時間。 - 子目標: ``` - If the selected time has already passed, have the program tell the user to start over. ``` ``` - If your program asks for the year, month, day, hour, etc. separately, allow the user to be able to type in either the month name or its number. ``` ``` - TIP: Making use of built in modules such as time and datetime can change this project from a nightmare into a much simpler task. ``` 中等的 --- ### 番茄計時器 建立一個番茄計時器。 番茄計時器是一種時間管理方法。該技術使用計時器將工作分解為多個時間間隔,通常長度為 25 分鐘,中間間隔短暫的休息。這些間隔被命名為“pomodoros”,是意大利語單字“pomodoro”(番茄)的英文複數形式,以西里洛在大學時使用的番茄形狀的廚房計時器命名。 原始技巧有六個步驟: 決定要完成的任務。 設定番茄計時器(傳統上為 25 分鐘)。 完成任務。 當計時器響起時結束工作並在一張紙上畫上複選標記。 如果您的複選標記少於四個,請短暫休息(3-5 分鐘),然後轉到步驟 2。 四個番茄鐘後,休息較長時間(15-30 分鐘),將複選標記計數重設為零,然後轉到步驟 1。 要了解有關番茄計時器的更多訊息[,請單擊此處](https://en.wikipedia.org/wiki/Pomodoro_Technique) ### 谷歌案例 - 這是一個可以讓你玩英文句子的遊戲。 - 使用者將以任何格式輸入一個句子。(大寫或小寫或兩者的混合) - 程式必須將給定的句子轉換為Google大小寫。什麼是Google大小寫句子風格?\[know\_about\_it\_here:\](這是一種寫作風格,我們將所有小寫字母替換為大寫字母,留下所有單字的首字母)。 - 子目標: ``` - Program must then convert the given sentence in camel case.To know more about camel case ``` ``` [click_here](https://en.wikipedia.org/wiki/Camel_case) ``` ``` - Sentence can be entered with any number of spaces. ``` ### 擲骰子模擬器 - 允許使用者輸入骰子的面數以及應擲骰子的次數。 - 您的程式應該模擬擲骰子並追蹤每個數字出現的次數(這不必顯示)。 - 最後,列印出每個數字出現的次數。 - 子目標: ``` - Adjust your program so that if the user does not type in a number when they need to, the program will keep prompting them to type in a real number until they do so. ``` ``` - Put the program into a loop so that the user can continue to simulate dice rolls without having to restart the entire program. ``` ``` - In addition to printing out how many times each side appeared, also print out the percentage it appeared. If you can, round the percentage to 4 digits total OR two decimal places. ``` - 獎金: ``` - You are about to play a board game, but you realize you don't have any dice. Fortunately you have this program. ``` ``` - 1. Create a program that opens a new window and draws 2 six-sided dice ``` ``` - 2. Allow the user to quit, or roll again ``` ``` - Allow the user to select the number of dice to be drawn on screen(1-4) 2. Add up the total of the dice and display it ``` ### 計算並修復綠雞蛋和火腿 你們有些人可能還記得蘇博士的故事「綠雞蛋和火腿」。對於那些不記得或從未聽說過的人,[這](http://pastebin.com/XMY48CnN)是這個故事。然而,我給你的故事有一個問題——每次使用「我」這個詞時,它都是小寫的。 由於此問題,您的工作是執行以下操作: - 將我給您的故事複製到常規文字檔案中。 - 建立一個程式來通讀故事並在任何時候將字母 i 變為大寫。 (當它也用在 sam-I-am 的名字中時,請務必更改它。) - 讓你的程式建立一個新文件,並讓它正確地寫出故事。 - 印出有多少錯誤被修正。 - 完成後,您應該已經糾正了[這麼多](https://i.imgur.com/GRkj3yz.jpg)錯誤。 難的 -- ### 隨機維基百科文章 如果您曾造訪維基百科,您可能已經注意到螢幕左側有一個指向隨機文章的連結。雖然看到您被帶到哪篇文章可能很有趣,但有時看到文章的名稱會很好,這樣您就可以在聽起來很無聊時跳過它。幸運的是,維基百科有一個 API,允許我們這樣做[點擊這裡](https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=10&format=json)。 然而,有一個困境。由於維基百科擁有有關世界各地主題的文章,其中一些文章的標題中包含特殊字元。例如,關於西班牙畫家[埃拉斯托·科爾特斯·華雷斯 (Erasto Cortés Juárez)](https://en.wikipedia.org/wiki/Erasto_Cort%C3%A9s_Ju%C3%A1rez)的文章中就有 é 和 á。如果您查看這篇特定文章的[API](https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=39608394&inprop=url&format=json) ,您將看到標題是“Erasto Cort\\u00e9s Ju\\u00e1rez”,並且 \\u00e9 和 \\u00e1 正在替換前面提到的兩個字母。 (有關這是什麼的訊息,請首先查看文件中[本頁](https://docs.python.org/2/howto/unicode.html)的前半部分)。為了讓你的程式正常運作,你必須以某種方式處理這個問題。 - 建立一個程序,從官方維基百科 API 中提取標題,然後一一詢問用戶是否願意閱讀該文章。 - 例子: ``` - If the first title is Reddit, then the program should ask something along the lines of "Would you like to read about Reddit?" If the user says yes, then the program should open up the article for the user to read. ``` ``` - HINT: Click [here](https://en.wikipedia.org/wiki?curid=39608394) to see how the article's ID can be used to access the actual article. ``` - 子目標: ``` - As mentioned before, do something about the possibility of unicode appearing in the title. ``` ``` - Whether you want your program to simply filter out these articles or you want to actually turn the codes into readable characters, that's up to you. ``` ``` - Make the program pause once the user has selected an article to read, and allow him or her to continue browsing different article titles once finished reading. ``` ``` - Allow the user to simply press ENTER to be asked about a new article. ``` ### 天氣如何? 如果您想了解 API 的基礎知識,請查看 iamapizza 的[這篇](http://www.reddit.com/r/explainlikeimfive/comments/qowts/eli5_what_is_api/c3z9kok)文章。 - 建立一個程序,從 OpenWeatherMap.org 提取資料並列印有關當前天氣的訊息,例如您居住的地方的最高氣溫、最低氣溫和雨量。 - 子目標: ``` - Print out data for the next 5-7 days so you have a 5 day/week long forecast. ``` ``` - Print the data to another file that you can open up and view at, instead of viewing the information in the command line. ``` ``` - If you know html, write a file that you can print information to so that your project is more interesting. ``` - 尖端: ``` - APIs that are in Json are essentially lists and dictionaries. Remember that to reference something in a list, you must refer to it by what number element it is in the list, and to reference a key in a dictionary, you must refer to it by its name. ``` ``` - Don't like Celsius? Add &units=imperial to the end of the URL of the API to receive your data in Fahrenheit. ``` ### 來源 - https://github.com/tuvtran/project-based-learning - https://github.com/jorgegonzalez/beginner-projects - https://github.com/MunGell/awesome-for-beginners/blob/master/README.md - https://github.com/sarahbohr/AbsoluteBeginnerProjects --- 你怎麼認為?您喜歡透過特定專案進行學習還是不喜歡透過特定專案進行學習? --- 原文出處:https://dev.to/samborick/100-project-ideas-oda

學習 Rust:一個乾淨的開始

我決定是時候學習[Rust 了](https://www.rust-lang.org/),為了保持自己的動力,我將在這裡記錄學習的進展。 ![費里斯螃蟹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0xl5mafhbjgfuowu62t.png) 有關於我的一些;我是一名 Web 開發人員,雖然已經涉足多年,但已經從事了大約 5 年。我有使用[Perl](https://www.perl.org/)和[PHP](https://www.php.net/)的經驗,但我的日常工作是 JavaScript/TypeScript,無論是透過[NodeJS](https://nodejs.org/en)還是[ReactJS](https://react.dev/) 。我想學習 Rust 沒有什麼特別的原因,只是學習新事物很有趣。 我的第一個停靠點是Google `learn rust` ,這引導我找到了[「這本書」](https://doc.rust-lang.org/book/) 。這本書是 Rust 社群為新手(或所謂的 Rustlings)編寫的入門指南,旨在「紮實掌握這門語言」。 公共學習 ---- 我選擇公開記錄我的 Rust 學習之旅,因為我相信公開學習的力量。透過分享我的成功、挑戰和見解,我將加強自己的理解,並希望為其他走類似道路的人提供資源。 我親眼目睹了這種方法的價值。我邀請讀者提供回饋、更正和貢獻。雖然我認識到公共學習並不適合所有人,但我個人發現它非常有益,並希望激勵其他人考慮它。那麼,讓我們深入學習這些課程。 第 1 課“入門” --------- 本課分為 3 個部分: - 安裝 - 你好世界! - 你好,貨物! ### 安裝 看到列出的安裝,我鬆了口氣,我擔心我必須查找如何安裝 Rust。我使用的是 Windows 計算機,但決定在 Linux 中學習 Rust,因此我將透過 WSL 使用 Ubuntu。 安裝指令看起來很簡單,它使用curl來下載一些東西,然後透過sh進行管道傳輸,所以我們可以假設下載的專案是某種bash腳本。 ``` curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh ``` 不管你信不信,這是我犯下的第一個錯誤。我看到`Rust is installed now. Great!`訊息並繼續下一課。如果我繼續閱讀下去,我會發現我需要單獨安裝編譯器。 > Linux 使用者通常應該根據其發行版的文件安裝 GCC 或 Clang。例如,如果您使用 Ubuntu,則可以安裝 build-essential 套件。 不過,這很容易解決,我很快就回到了正軌。 ``` sudo apt install build-essential ``` ### 你好世界! 下一部分是開發社群的主要內容,即深受喜愛的“Hello, World!”例子。 ![你好世界](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l2navm68azq2jbk9mcsf.png) 我在這裡學到了一些東西,函數是用`fn`關鍵字聲明的,任何 Rust 應用程式的入口點都是`main.rs`檔案中的`main`函數,標準命名約定是使用下劃線來分隔函數和檔案名稱中的單字。 正是在這個階段,我發現我沒有安裝編譯器,我認為這是像這樣的簡單部分的真正原因,以確保我們都設定正確。 ### 你好,貨物! 上一節很簡單,這節也很簡單,但向我們介紹了[Cargo](https://crates.io/) ,它是 Rust 的套件管理器,作為一個 JS 開發者,我的腦海裡直接想到了 NPM。 Cargo 允許我們做一些很酷的事情: - 為我們的包命名。 - 新增包依賴項。 - 用一個命令執行我們的程式。 - 使用除錯模式和發布模式來建立我們的程式。 - 檢查我們的程式是否編譯,但沒有實際建立它。 這個範例讓我們重新創造我們的`Hello, World!`例如但以貨運方式。程式碼非常簡單,幾乎不值得展示,但它就是這樣。 ``` fn main() { println!("Hello, world!"); } ``` 第 2 課“猜謎遊戲” ----------- 第二課沒有任何小節,本課的目標是編寫一個猜謎遊戲,用戶輸入一個數字,我們將其與隨機選擇的數字進行比較,遊戲繼續,直到用戶猜出確切的數字。 我們仍然沒有做任何突破性的事情,但從列印靜態文字到動態獲取用戶輸入並返回結果的進展仍然很好。 ### VS程式碼 正是在這一點上,我決定在`nano`中進行程式碼變更不是一個好主意,我需要在 VSCode 中開啟專案。我加入了一些擴展,希望能讓開發變得更容易。這些是[rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) 、[板條箱](https://marketplace.visualstudio.com/items?itemName=serayuzgur.crates)和[Even Better TOML](https://marketplace.visualstudio.com/items?itemName=tamasfe.even-better-toml) 。你可以使用任何你喜歡的編輯器,我只是習慣了 VSCode。 ![VSCode 標誌](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rq9m8kkxv6milsxbv5zw.png) ### 製作遊戲 讓我們來看看遊戲教程,它讓我們使用貨物來設定專案,並很快向我們介紹了一些新概念 - `use`關鍵字。 - 可變變數。 - 錯誤處理。 - 文件位置 #### `use`關鍵字 `use`關鍵字允許我們從其他庫中提取程式碼,作為一名 Web 開發人員,我想將其與[import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)進行比較。預設情況下,Rust 將能夠存取「標準」庫中的一組專案,這稱為前奏,但如果您想存取其他任何內容,則必須使用`use` 。 在他們給出的範例中,我們確實`use std::io;`它允許我們存取`io`命名空間,這確實感覺有點奇怪,因為我們已經可以存取`std` ,這意味著`std::io`也可以存取。 #### 可變變數 在 JavaScript 領域,我們有不可變變數和可變變數的概念,它們是`const`和`let` ,其中`const`是不可變的,而`let`不是。 Rust 有點不同,因為除非另有說明,否則所有變數都是不可變的,變數關鍵字也總是`let` ,或者至少據我所知到目前為止是這樣。 ``` let mut var1 = String::new(); // mutable let mut var2 = String::from("Test String"); // mutable let var3 = 6; // immutable ``` 這本書讓我們知道,第三課將回歸可變性。 #### 錯誤處理 我們介紹了兩種類型的錯誤處理`.expect` ,它們不會嘗試任何類型的恢復,但會在應用程式崩潰和`match`時發布一條訊息。 `Match`從函數中取得`Result` ,然後允許您根據`Result`呼叫函數。在範例中,我們給出了`parse`並告訴它要么是`Ok`要么是`Err` ,在`match`中我們可以定義一個在這兩種情況下呼叫的函數。我假設當我們開始處理更多樣化的函數時,match 將能夠處理所有`Result`類型。 #### 文件位置 這是迄今為止我最喜歡 Rust 的部分,我知道它不應該那麼令人興奮,但我認為它是。當您執行命令`cargo doc` Cargo 時,Cargo 將掃描您正在使用的所有程式碼,並產生解釋功能以及如何使用它們的說明頁面。 目前還沒有太多解釋,但我希望這些文件是從程式碼中的註解產生的,即使這不是那種情況,可以自我記錄的程式碼庫對我來說是如此有趣。 ### 偏離了人跡罕至的地方 此時,我已經完成了前兩課,並決定對猜謎遊戲進行一些更改。我將遊戲循環提取到它自己的函數中,並加入了解析失敗的錯誤訊息。 我不喜歡的一件事是這條線的`magic` 。 ``` let guess: u32 = match guess.trim().parse() ``` 我不喜歡這種感覺,就像 parse 神奇地知道它的目標類型一樣。所以我閱讀了 VSCode 中的解析工具提示,它教導了有關`turbofish`語法的內容。我不知道人們是否不喜歡這種語法,或者這本書的作者是否認為它對於初學者來說太複雜,但在我看來,它更有意義。我們告訴 parse 我們想要什麼類型,然後我們的`let`從中推論出類型,而不是相反。 ``` let guess = match guess.trim().parse::<u32>() ``` 這是修改後的程式碼。 {% 嵌入 https://replit.com/@andrewb05/Guessing-game %} 註銷 -- 感謝您與我一起踏上這段旅程。我計劃繼續這個系列並涵蓋整本書。如果您想關注,可以按下「關注」按鈕以獲得新帖子的通知。 正如我之前所說,請隨意留下任何反饋,如果您也在公開學習,請在評論中留下您的系列的連結,以便我可以查看。 非常感謝您的閱讀。如果您想在開發之外與我聯繫,這裡有我的[Twitter](https://twitter.com/Link2Twenty)和[linkedin,](https://www.linkedin.com/in/andrew-bone-ba241b179/)歡迎來打個招呼 😊。 --- 原文出處:https://dev.to/link2twenty/learning-rust-a-clean-start-4eom

2024 年每個雲端工程師都應該了解的 7 種程式語言!

近年來,在各種程式設計訓練營的指導中,我獲得了獨特的機會來指導和支援眾多熱衷於在雲端工程和 DevOps 領域取得成功的初級開發人員。我注意到這些有抱負的工程師中反覆出現的一個主題是,他們渴望深入了解雲端運算的複雜性,但常常對大量可用的程式語言和工具感到不知所措。這種認識激發了我的想法,即建立一個全面且平易近人的指南,為任何開始雲端工程之旅的人介紹基本的程式語言。 同樣,到 2024 年,每個雲端工程師都應該了解以下七種程式語言,每種語言都因其相關性、功能和在實現現代雲端解決方案中的作用而被選擇。 1. 翼 ---- ![只是一個翅膀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6syu6oqhs93z0sq77cvf.png) [Wing](https://github.com/winglang/wing)的設計理念強調生產力、安全性和效率,使開發人員能夠在整個開發過程中保持單一、直覺的工作流程。 透過將基礎設施資源視為一等公民,Wing 允許開發人員直接在其應用程式程式碼中定義、互動和管理這些資源。這種整合顯著降低了與管理雲端基礎架構相關的複雜性和潛在錯誤,從而更輕鬆地建置和部署安全、可擴展的應用程式。 Wing 的主要功能之一是它能夠編譯為基礎設施即程式碼 (IaC) 格式,例如 Terraform 和 JavaScript。 Wing 對雲端應用程式本地模擬的支援徹底改變了開發人員的工作效率。在部署之前能夠在本地環境中執行、視覺化、互動和除錯雲端應用程式可以顯著加快開發週期並提高應用程式品質。此功能與易於與 DevOps 實踐整合的語言設計相結合,可確保開發人員能夠更有效地應用持續整合和持續部署 (CI/CD) 方法,從而與現代軟體開發實踐保持一致。 看看[Wing 的互動遊樂場,](https://www.winglang.io/play/)了解 Wing 語言的工作原理。 使用 Wing 非常輕鬆且超級簡單。 您可以在幾秒鐘內安裝 Wing 並開始自動化您的雲端工作流程。 ``` npm install -g winglang ``` 您可以使用以下命令驗證您的安裝。 ``` wing -V ``` 使用 CLI 引導新專案:使用 new 命令,然後修改 main.w 使其具有以下內容: ``` wing new empty ``` ``` bring cloud; // define a queue, a bucket and a counter let bucket = new cloud.Bucket(); let counter = new cloud.Counter(initial: 1); let queue = new cloud.Queue(); // When a message is received in the queue it should be consumed // by the following closure queue.setConsumer(inflight (message: str) => { // Increment the distributed counter, the index variable will // store the value prior to the increment let index = counter.inc(); // Once two messages are pushed to the queue, e.g. "Wing" and "Queue". // Two files will be created: // - wing-1.txt with "Hello Wing" // - wing-2.txt with "Hello Queue" bucket.put("wing-{index}.txt", "Hello, welcome to winglang world!"); log("file wing-{index}.txt created"); }); ``` 使用 wing it 指令透過我們新建立的應用程式啟動控制台: ``` wing it main.w ``` Wing 控制台為您提供雲端應用程式的視圖,使開發人員能夠更快地迭代和熱重載: ![溫朗前衛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mmrz484dh0fvf220uhg4.png) 透過 Wing 的有關[Wing 入門](https://www.winglang.io/docs/start-here/local)的文件探索更多資訊。 2.Python -------- ![僅限蟒蛇](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7gdgxhcb4mjywdih30u.png) 由於其簡單性、多功能性和強大的生態系統, [Python](https://github.com/python)仍然是雲端工程師不可或缺的語言。其廣泛的庫和框架集合(例如用於 Web 應用程式的 Flask 和用於機器學習的 TensorFlow)使 Python 成為開發各種基於雲端的服務的首選語言。此外,Python 在自動化、腳本編寫和資料分析中的作用確保了它仍然是雲端基礎設施管理、自動化任務和雲端應用程式快速原型設計的關鍵工具。 3. 成長 ----- ![戈蘭](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p5ggz0p6ix46uqifhmd7.png) [Go](https://github.com/golang/go)或 Golang 由 Google 設計,在雲端工程師中越來越受歡迎,用於建立高效能和可擴展的雲端服務。它的高效、簡單和內建的並發支援使其成為開發微服務、分散式系統和容器化應用程式的絕佳選擇。 Go 與雲端平台的兼容性及其有效處理繁重網路流量和複雜處理任務的能力有助於其在雲端基礎設施專案中的日益普及。 4. JavaScript(使用 Node.js) ------------------------- ![Node.js 語言](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5q16t3w3zf8xctgrlvg.png) [JavaScript](https://en.wikipedia.org/wiki/JavaScript) ,特別是與 Node.js 一起使用時,對於專注於建置和部署可擴展且高效的 Web 應用程式的雲端工程師來說至關重要。 Node.js 允許在伺服器端使用 JavaScript,從而能夠開發適合雲端的快速、非阻塞、事件驅動的應用程式。 JavaScript 在客戶端和伺服器端開發中的普遍存在也促進了全端開發能力,使其對於從事基於雲端的 Web 服務和應用程式的工程師來說非常寶貴。 5. 生鏽 ----- ![長時間休息](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3f1w421ksertrrldyod.png) [Rust](https://www.rust-lang.org/)由於強調安全性、速度和無需垃圾收集器的並發性而在雲端運算領域獲得了發展勢頭。這些功能使 Rust 成為尋求開發高效能、安全且可靠的雲端服務和基礎設施的雲端工程師的有吸引力的選擇。 Rust 的記憶體安全保證和機器程式碼的高效編譯使其成為雲端環境中系統級和嵌入式應用程式的理想語言,在雲端環境中,效能和安全性至關重要。 6. Kubernetes YAML ------------------ ![Kubernetes yaml](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mga2ylbbc9g98w4hjkmg.png) 雖然[Kubernetes YAML](https://kubernetes.io/docs/concepts/overview/working-with-objects/) (YAML 不是標記語言)不是傳統意義上的程式語言,但對於使用 Kubernetes(容器編排事實上的標準)的雲端工程師來說至關重要。掌握 Kubernetes YAML 對於跨雲端環境定義、部署和管理容器化應用程式至關重要。了解 Kubernetes 資源檔案和配置的複雜性使工程師能夠利用容器編排的全部功能,確保可擴展、有彈性且高效的雲端原生應用程式。 7.Terraform HCL(HashiCorp配置語言) ------------------------------ ![地形鹽酸鹽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ke9hjhkw6k2i9zald105.png) [Terraform HCL](https://github.com/hashicorp/hcl) (HashiCorp 配置語言)是 2024 年雲端工程師的必備語言,尤其是那些參與基礎設施即程式碼 (IaC) 實踐的工程師。 HCL 是 Terraform 使用的配置語言,Terraform 是一種廣泛採用的工具,使工程師能夠使用聲明性配置方法定義、配置和管理雲端基礎架構。學習 Terraform HCL 使雲端工程師能夠自動化跨不同服務供應商的雲端資源部署和生命週期管理,確保雲端環境的一致性、可重複性和可擴展性。 ### 包起來 到 2024 年,所有語言都有自己的優勢,我很高興將自己關於雲端工程和 DevOps 的想法放在一起。 如果我能為我的學生提供建議,在這個不斷發展的領域迅速擴展的過程中,掌握 Wing 將成為一個令人信服的選擇。 [Wing](https://www.winglang.io/)為雲端工程師和開發人員提供了獨特的優勢,提供控制臺本地測試、熱重載(對大多數雲端工程師來說是一個挑戰)和增強的可擴展性,更不用說雲端應用程式的安全性了。 --- 原文出處:https://dev.to/pavanbelagatti/7-programming-languages-every-cloud-engineer-should-know-in-2024-1kcd

🎉 我們的 Web 框架在 GitHub 上達到了 9,000 顆星! ⭐️9️⃣0️⃣0️⃣0️⃣⭐️

![黃蜂合影](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6mrq2mqbhb8dwvrfp26.png) **TL;DR - 儘管困難重重,我們建立的 Web 框架還是達到了一個里程碑!請查看(如果您喜歡的[話,請給我們加星支持](https://github.com/wasp-lang/wasp)- 謝謝!🙏),並閱讀下文以了解我們的故事以及我們是如何走到這一步的。** 作為一名開發人員,建立自己的 Web 框架可能是您能做的最可怕的事情之一。幾乎可以肯定你的專案將會失敗,作為額外的好處,其他開發人員會一路取笑你,數出它不起作用的所有原因。 &lt; 圖&gt; ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mcu9469qr7fdcy9wwl8o.gif) 分享您對新 Web 框架的想法是怎樣的感覺 這對我們來說沒有什麼不同。當我們開始 Wasp 時,每個人都問*“為什麼要另一個 Web 框架?為什麼有人會在成熟、著名的框架旁邊使用你的工具?”* 。我承認,這些都是好問題,但我們並沒有找到所有答案,甚至還沒有接近答案。但這絕對不是我們不這麼做的理由。 &lt; 圖&gt; ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/loncvv6cn5ox644gggvy.png) 三年前,當我們推出 Wasp Alpha 時 我們繼續前進。我們心中有一個願景,我們想看看能否將其變成現實。**我們根本不在乎黃蜂是死是活,我們只知道我們需要堅持到底,這才是最重要的**。幾個月後,我們發布了 Alpha 版本並獲得了第一批 100 顆星。結果,這帶來了更多問題,我們距離弄清楚我們想像的概念是否真的能飛還差得遠。 **但是,我們也無法相信有人真的為我們的倉庫加註了星標。我們既驚訝又興奮**。我仍然清楚地記得 Martin Šošić 問我*“Matija,你能想像我們建立的專案在 GitHub 上獲得 1000 星嗎?”* 。我們倆立即搖頭大笑,心想*:“是啊,就是這樣啊!”* 。 &lt; 圖&gt; ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9z36qtjswggstpgggoyh.png) 我們的第一次社群更新,慶祝 GitHub 上的 100 顆星! 9,500 顆星,近 3 年後,我們今天在這裡。 Wasp 即將進入 GitHub 上的精英 10,000 星俱樂部,與行業巨頭並駕齊驅。**我們啟動的框架,並根據社群的寶貴回饋進一步開發,正在被各種開發人員使用 - 從週末專案到新創公司和頂級企業**。用 Wasp 建立的新創公司[已被收購](https://dev.to/wasp/from-idea-to-exit-building-and-selling-an-ai-powered-saas-in-5-months-27d9)。我今天剛在 Upwork 上看到一則招募廣告,其中一家公司正在招募[Open SaaS](https://github.com/wasp-lang/open-saas) (React 和 Node.js 的開源免費樣板啟動器,由 Wasp 提供支援)開發人員🤯。 ![開放式SaaS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t8qyb3a7qxwbg8d2x5g7.png) 回想起來,我仍然覺得難以置信。從我哥哥女朋友(現在是妻子)的公寓開始,我們幾乎沒有開源也沒有社區建設經驗,但我們卻做出了全世界開發人員日常使用的產品,並且願意選擇使用它而不是主流的著名框架我們都知道。我們對此感到無比榮幸和謙卑。 我們仍然有很多問題(認為這些問題永遠不會消失),但現在也開始感覺我們得到了一些正確的答案。 &lt; 圖&gt; ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6md2ilfye1jss9mr7a60.png) 我們今天收到的回饋 謝謝閱讀![在這裡](https://github.com/wasp-lang/wasp)了解有關 Wasp 的更多資訊並支持我們達到 10,000 顆星的旅程。 PS:如果您想知道誰是黃蜂隊的真正老闆,現在我們終於在上面的照片中明確了這一點。必須把這個小傢伙一直帶到山頂,這樣他才能得到一個漂亮的鏡頭。 🐝 --- 原文出處:https://dev.to/wasp/our-web-framework-reached-9000-stars-on-github-9000-jij

31 位女性科技內容創作者值得關注

我是一名開發人員倡導者,作為我工作的一部分,我們行銷團隊的人員經常問我... **“嘿,你知道有哪些擁有大量女性粉絲的內容創作者可供我們接觸嗎?我們很難找到很多。”** 可悲的事實是,這樣的人並不多。那麼,讓我們改變這一點。 今天是女性歷史月的第一天,您可以關注、支持並與不同類別的 31 位創作者互動。透過此列表,您可以在本月的每一天查看新的創作者,並找到新的追蹤者。 我想念你最喜歡的創作者了嗎?留下評論並附上他們的連結。 我嘗試按一般內容類別進行分組。如果您在此處看到您的名字並認為我歪曲了您的內容,請告訴我,以便我可以進行修復。 開始。 直播主播 ---- 1. [Bashbunni](https://www.twitch.tv/bashbunni/about) - 直播 Go!尼維姆!軟體開發 2. [Ali](https://links.ali.dev/) - 直播、軟體開發、安全。無論你在哪裡上網,阿里都有內容。 3. [Salma](https://whitep4nth3r.com/) - 軟體工程師、直播程式設計師和開發教育者 4. [Esther](https://www.twitch.tv/timeenjoyed) - 即時編碼與學習 5. [Leah](https://www.twitch.tv/leahtcodes) - 編碼、學習、遊戲和友誼 科技娛樂、網頁開發教學、提示 -------------- 6\. [Kedasha Kerr](https://www.instagram.com/itsthatlady.dev/) - IG 帳戶,充滿了來自您最喜歡的 Github Dev Advocate 的編碼技巧和有趣內容 7\. [Bukola](https://www.youtube.com/@Bukola1) - 從事科技工作,住在紐約,分享技巧 8\. \[真實\](https://www.instagram.com/mewtru/ ) - 為了我們的娛樂而用程式碼對使用者體驗做出犯罪行為。 9\. [Rita Codes](https://www.instagram.com/rita_codes/)開發者和遊戲玩家對開發者面臨的日常困境進行了一些熱門看法 10\. [Tiff 從事技術](https://www.youtube.com/c/TiffInTech)模型轉型開發,Tiff 有一些在技術職業生涯中取得成功的技巧 11\. [Ale Thomas](https://www.instagram.com/pikacodes/)軟體開發者讓我們在開發者的困境中保持歡笑 12\. \[娜雅\](https://www.youtube.com/@TheBlackFemaleEngineer ) - 致力於創造內容作為少數群體進入科技世界的資源 13\. [NaniLemons](https://www.tiktok.com/@nanilemons) - 程式設計師幽默、科技新聞和一般樂趣 14\. [Jess Chan -](https://www.youtube.com/c/TheCoderCoder)初學者網頁開發人員的實用技巧 15\. [Ania Kubow](https://www.youtube.com/@AniaKubow) - 如果這是網頁開發主題,Ania 可能會有一個教學。一探究竟。 16\. [Mal-](https://linktr.ee/malware_yml)有時是建設性的,有時是娛樂性的,總是一段美好時光 技術寫作 ---- 17\. [Christine Belzie](https://chrissycodes.hashnode.dev/) - 言語很重要,Chrissy 在這裡幫助我們所有人提高技術寫作技能。 德夫雷爾 ---- 18\. [Rizel Scarlett](https://dev.to/blackgirlbytes) - 向最好的人之一學習 Web5 和 Devrel! 19\. [Tessa Kriesel](https://www.tessakriesel.com/) - Devrel 策略女王 20\. [Haimantika](https://haimantika.dev) - Devrel 和技術寫作。將 hashnode 的開發倡導者放在這個網站上是不是很奇怪?或許。 資料科學 ---- 21\. [Sundas Khalid](https://www.youtube.com/channel/UCteRPiisgIoHtMgqHegpWAQ) - 進入資料科學產業的技巧 無障礙 --- 22\. [Africa Kenyah](https://www.youtube.com/channel/UCiaMi-uLijoOEPT0lfaQCvw) - 擁有豐富知識的無障礙工程師 設計與開發 ----- 23\. [Amy Dutton](https://www.youtube.com/c/selfteachme) - 準備好提升您的開發和設計技能了嗎?關注艾米! 24\. [Stephanie Stimac](https://seaotta.dev/) - 對設計和開發有興趣?史蒂芬妮甚至就此寫了一本書。 25\. [Muhtanya](https://www.tiktok.com/@muhtanya)藝術、設計與工程 一般開發/技術和職業 ---------- 26\. [Cassidy Williams](https://blog.cassidoo.co/) - 軟體開發、部落格、時事通訊,甚至還有一款會讓你發瘋的名為 Jumblie 的遊戲。 27.【Shaundaip】(https://www.tiktok.com/@shaundaip ) - 頂級演講者和開發者的新 tiktok 帳戶 28\. [Gift Egwuenu](https://www.youtube.com/@giftegwuenu) - 科技職業和僑民生活 開源 -- 29\. [Bekah](https://dev.to/bekahhw) - Bekah 無所不在,並且總是傳授如何在技術和開源領域取得成功的知識。 雲端/DevOps --------- 30\. [Myra](https://www.tiktok.com/@myraintech) - 關於雲端和安全領域的技術、生活方式和旅行 遊戲玩家 ---- 31\. [Krista Byte](https://www.tiktok.com/@kristabyte)致力於增強世界各地女性遊戲玩家的權能 謝謝閱讀。我希望您找到一些值得喜愛的新內容創作者! 要了解我的最新動態,您可以在 Dev 上關注我,[在社交上與我聯繫](https://www.biodrop.io/amandamartin-dev),並查看我在[Wix for Developers YouTube](https://www.youtube.com/@WixforDevelopers)上所做的一些工作。 --- 原文出處:https://dev.to/amandamartindev/31-women-in-tech-content-creators-to-follow-now-4642

我正在建立一個全端應用程式:以下是我將要使用的庫......

您可以使用無數的框架和函式庫來改進您的全端應用程式。 我們將介紹令人興奮的概念,例如應用程式內通知、使用 React 製作影片、從為開發人員提供的電子郵件 API 到在瀏覽器中建立互動式音樂。 那我們就開始吧。 (不要忘記為這些庫加註星標以表示您的支持)。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qqoipyuoxgb83swyoo4a.gif) https://github.com/CopilotKit/CopilotKit --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------ ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea ``` 這是整合 CopilotTextArea 的方法。 ``` import { CopilotTextarea } from "@copilotkit/react-textarea"; import { useState } from "react"; export function SomeReactComponent() { const [text, setText] = useState(""); return ( <> <CopilotTextarea className="px-4 py-4" value={text} onValueChange={(value: string) => setText(value)} placeholder="What are your plans for your vacation?" autosuggestionsConfig={{ textareaPurpose: "Travel notes from the user's previous vacations. Likely written in a colloquial style, but adjust as needed.", chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 20, stop: [".", "?", "!"], }, }, }, }} /> </> ); } ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)。 基本概念是在幾分鐘內建立可用於基於 LLM 的全端應用程式的 AI 聊天機器人。 https://github.com/CopilotKit/CopilotKit --- 2. [Storybook](https://github.com/storybookjs/storybook) - UI 開發、測試和文件變得簡單。 --------------------------------------------------------------------------- ![故事書](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78rfum1ydisn51qhb408.png) Storybook 是一個用於獨立建立 UI 元件和頁面的前端工作坊。它有助於 UI 開發、測試和文件編制。 他們在 GitHub 上有超過 57,000 次提交、81,000 多個 star 和 1300 多個版本。 這是您為專案建立簡單元件的方法。 ``` import type { Meta, StoryObj } from '@storybook/react'; import { YourComponent } from './YourComponent'; //👇 This default export determines where your story goes in the story list const meta: Meta<typeof YourComponent> = { component: YourComponent, }; export default meta; type Story = StoryObj<typeof YourComponent>; export const FirstStory: Story = { args: { //👇 The args you need here will depend on your component }, }; ``` 您可以閱讀[文件](https://storybook.js.org/docs/get-started/setup)。 如今,UI 除錯起來很痛苦,因為它們與業務邏輯、互動狀態和應用程式上下文糾纏在一起。 Storybook 提供了一個獨立的 iframe 來渲染元件,而不會受到應用程式業務邏輯和上下文的干擾。這可以幫助您將開發重點放在元件的每個變體上,甚至是難以觸及的邊緣情況。 https://github.com/storybookjs/storybook --- 3. [Appwrite](https://github.com/appwrite/appwrite) - 您的後端減少麻煩。 --------------------------------------------------------------- ![應用程式寫入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x568uz21seyygw6b72z.png) ![帶有 appwrite 的 sdk 列表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cp7k8qnamsluto7eifpl.png) Appwrite 的開源平台可讓您將身份驗證、資料庫、函數和儲存體新增至您的產品中,並建立任何規模的任何應用程式、擁有您的資料並使用您喜歡的編碼語言和工具。 他們有很好的貢獻指南,甚至不厭其煩地詳細解釋架構。 開始使用以下 npm 指令。 ``` npm install appwrite ``` 您可以像這樣建立一個登入元件。 ``` "use client"; import { useState } from "react"; import { account, ID } from "./appwrite"; const LoginPage = () => { const [loggedInUser, setLoggedInUser] = useState(null); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const login = async (email, password) => { const session = await account.createEmailSession(email, password); setLoggedInUser(await account.get()); }; const register = async () => { await account.create(ID.unique(), email, password, name); login(email, password); }; const logout = async () => { await account.deleteSession("current"); setLoggedInUser(null); }; if (loggedInUser) { return ( <div> <p>Logged in as {loggedInUser.name}</p> <button type="button" onClick={logout}> Logout </button> </div> ); } return ( <div> <p>Not logged in</p> <form> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <button type="button" onClick={() => login(email, password)}> Login </button> <button type="button" onClick={register}> Register </button> </form> </div> ); }; export default LoginPage; ``` 您可以閱讀[文件](https://appwrite.io/docs)。 Appwrite 可以非常輕鬆地建立具有開箱即用的擴充功能的可擴展後端應用程式。 https://github.com/appwrite/appwrite --- 4. [Wasp](https://github.com/wasp-lang/wasp) - 用於 React、node.js 和 prisma 的類似 Rails 的框架。 --------------------------------------------------------------------------------------- ![黃蜂](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fi2mwazueoc3ezjx8a9q.png) 使用 React 和 Node.js 開發全端 Web 應用程式的最快方法。這不是一個想法,而是一種建立瘋狂快速全端應用程式的不同方法。 這是將其整合到元件中的方法。 ``` import getRecipes from "@wasp/queries/getRecipes"; import { useQuery } from "@wasp/queries"; import type { User } from "@wasp/entities"; export function HomePage({ user }: { user: User }) { // Due to full-stack type safety, `recipes` will be of type `Recipe[]` here. const { data: recipes, isLoading } = useQuery(getRecipes); // Calling our query here! if (isLoading) { return <div>Loading...</div>; } return ( <div> <h1>Recipes</h1> <ul> {recipes ? recipes.map((recipe) => ( <li key={recipe.id}> <div>{recipe.title}</div> <div>{recipe.description}</div> </li> )) : 'No recipes defined yet!'} </ul> </div> ); } ``` 您可以閱讀[文件](https://wasp-lang.dev/docs)。 https://github.com/wasp-lang/wasp --- 5. [Novu](https://github.com/novuhq/novu) - 將應用程式內通知新增至您的應用程式! -------------------------------------------------------------- ![再次](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/716b7biilet4auudjlcu.png) Novu 提供開源通知基礎架構和功能齊全的嵌入式通知中心。 這就是如何使用`React`建立 novu 元件以用於應用程式內通知。 ``` import { NovuProvider, PopoverNotificationCenter, NotificationBell, } from "@novu/notification-center"; function App() { return ( <> <NovuProvider subscriberId={process.env.REACT_APP_SUB_ID} applicationIdentifier={process.env.REACT_APP_APP_ID} > <PopoverNotificationCenter> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> </> ); } export default App; ``` 您可以閱讀[文件](https://docs.novu.co/getting-started/introduction)。 https://github.com/novuhq/novu --- 6. [Remotion](https://github.com/remotion-dev/remotion) - 使用 React 以程式設計方式製作影片。 ------------------------------------------------------------------------------- ![遠端](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmnrxhsc7b9mm5oagflm.png) 使用 React 建立真正的 MP4 影片,使用伺服器端渲染和參數化擴展影片製作。 開始使用以下 npm 指令。 ``` npm init video ``` 它為您提供了一個幀號和一個空白畫布,您可以在其中使用 React 渲染任何您想要的內容。 這是一個範例 React 元件,它將當前幀渲染為文字。 ``` import { AbsoluteFill, useCurrentFrame } from "remotion";   export const MyComposition = () => { const frame = useCurrentFrame();   return ( <AbsoluteFill style={{ justifyContent: "center", alignItems: "center", fontSize: 100, backgroundColor: "white", }} > The current frame is {frame}. </AbsoluteFill> ); }; ``` 您可以閱讀[文件](https://www.remotion.dev/docs/)。 過去兩年,remotion 團隊因製作 GitHub Wrapped 而聞名。 https://github.com/remotion-dev/remotion --- [7.NocoDB](https://github.com/nocodb/nocodb) - Airtable 的替代品。 ------------------------------------------------------------- ![諾科資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iw3tchfgyzehye5c39xq.png) Airtable 的免費開源替代品是 NocoDB。它可以使用任何 MySQL、PostgreSQL、SQL Server、SQLite 或 MariaDB 資料庫製作智慧型電子表格。 其主要目標是讓強大的計算工具得到更廣泛的使用。 開始使用以下 npx 指令。 ``` npx create-nocodb-app ``` 您可以閱讀[文件](https://docs.nocodb.com/)。 NocoDB 的建立是為了為世界各地的數位企業提供強大的開源和無程式碼資料庫介面。 您可以非常快速地將airtable資料匯入NocoDB。 https://github.com/nocodb/nocodb --- 8.[新穎](https://github.com/steven-tey/novel)- 所見即所得編輯器,具有人工智慧自動完成功能。 ------------------------------------------------------------------- ![小說](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uo34vd9twpxcpbpzgchi.png) 它使用`Next.js` 、 `Vercel AI SDK` 、 `Tiptap`作為文字編輯器。 開始使用以下 npm 指令。 ``` npm i novel ``` 您可以這樣使用它。有多種選項可用於改進您的應用程式。 ``` import { Editor } from "novel"; export default function App() { return <Editor />; } ``` https://github.com/steven-tey/novel --- 9. [Blitz](https://github.com/blitz-js/blitz) - 缺少 NextJS 的全端工具包。 ----------------------------------------------------------------- ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vz6ineg1o7xyv7pwbuqn.png) Blitz 繼承了 Next.js 的不足,為全球應用程式的交付和擴展提供了經過實戰考驗的函式庫和約定。 開始使用以下 npm 指令。 ``` npm install -g blitz ``` 這就是您如何使用 Blitz 建立新頁面。 ``` const NewProjectPage: BlitzPage = () => { const router = useRouter() const [createProjectMutation] = useMutation(createProject) return ( <div> <h1>Create New Project</h1> <ProjectForm submitText="Create Project" schema={CreateProject} onSubmit={async (values) => { // This is equivalent to calling the server function directly const project = await createProjectMutation(values) // Notice the 'Routes' object Blitz provides for routing router.push(Routes.ProjectsPage({ projectId: project.id })) }} /> </div> ); }; NewProjectPage.authenticate = true NewProjectPage.getLayout = (page) => <Layout>{page}</Layout> export default NewProjectPage ``` 您可以閱讀[文件](https://blitzjs.com/docs/get-started)。 它使建築物改善了數倍。 ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cc4mb5wdksjv1ybx71co.png) https://github.com/blitz-js/blitz --- 10. [Supabase](https://github.com/supabase/supabase) - 開源 Firebase 替代品。 ----------------------------------------------------------------------- ![蘇帕貝斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksfygjhrzhmsg9cnvobs.png) 我們大多數人都已經預料到 SUPABASE 會出現在這裡,因為它實在是太棒了。 開始使用以下 npm 指令 (Next.js)。 ``` npx create-next-app -e with-supabase ``` 這是使用 supabase 建立用戶的方法。 ``` import { createClient } from '@supabase/supabase-js' // Initialize const supabaseUrl = 'https://chat-room.supabase.co' const supabaseKey = 'public-anon-key' const supabase = createClient(supabaseUrl, supabaseKey) // Create a new user const { user, error } = await supabase.auth.signUp({ email: '[email protected]', password: 'example-password', }) ``` 您可以閱讀[文件](https://supabase.com/docs)。 您可以使用身份驗證、即時、邊緣功能、儲存等功能建立一個速度極快的應用程式。 Supabase 涵蓋了這一切! 他們還提供了一些入門套件,例如 AI 聊天機器人和 Stripe 訂閱。 https://github.com/supabase/supabase --- [11.Refine](https://github.com/refinedev/refine) - 企業開源重組工具。 ------------------------------------------------------------ ![精煉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qx0kd6t2jzdtf90k5ke3.png) 建立具有無與倫比的靈活性的管理面板、儀表板和 B2B 應用程式 您可以在一分鐘內使用單一 CLI 命令進行設定。 它具有適用於 15 多個後端服務的連接器,包括 Hasura、Appwrite 等。 開始使用以下 npm 指令。 ``` npm create refine-app@latest ``` 這就是使用 Refine 新增登入資訊的簡單方法。 ``` import { useLogin } from "@refinedev/core"; const { login } = useLogin(); ``` 您可以閱讀[文件](https://refine.dev/docs/)。 https://github.com/refinedev/refine --- 12. [Zenstack](https://github.com/zenstackhq/zenstack) - 資料庫到 API 和 UI 只需幾分鐘。 ----------------------------------------------------------------------------- ![禪斯塔克](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b6n2ea3jeeva6uujoex.png) TypeScript 工具包,透過強大的存取控制層增強 Prisma ORM,並釋放其全端開發的全部功能。 開始使用以下 npx 指令。 ``` npx zenstack@latest init ``` 這是透過伺服器適配器建立 RESTful API 的方法。 ``` // pages/api/model/[...path].ts import { requestHandler } from '@zenstackhq/next'; import { enhance } from '@zenstackhq/runtime'; import { getSessionUser } from '@lib/auth'; import { prisma } from '@lib/db'; // Mount Prisma-style APIs: "/api/model/post/findMany", "/api/model/post/create", etc. // Can be configured to provide standard RESTful APIs (using JSON:API) instead. export default requestHandler({ getPrisma: (req, res) => enhance(prisma, { user: getSessionUser(req, res) }), }); ``` 您可以閱讀[文件](https://zenstack.dev/docs/welcome)。 https://github.com/zenstackhq/zenstack --- 13. [Buildship](https://github.com/rowyio/buildship) - 低程式碼視覺化後端建構器。 -------------------------------------------------------------------- ![建造船](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzlrynz5xephv4t9layd.png) 對於您正在使用無程式碼應用程式建構器(FlutterFlow、Webflow、Framer、Adalo、Bubble、BravoStudio...)或前端框架(Next.js、React、Vue...)建立的應用程式,您需要一個後端來支援可擴展的 API、安全工作流程、自動化等。BuildShip 為您提供了一種完全視覺化的方式,可以在易於使用的完全託管體驗中可擴展地建立這些後端任務。 這意味著您不需要在雲端平台上爭論或部署東西、執行 DevOps 等。只需立即建置和交付 🚀 https://github.com/rowyio/buildship --- 14. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ----------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohv3johuz92lsaux52oq.png) Taipy 是一個開源 Python 庫,用於輕鬆的端到端應用程式開發, 具有假設分析、智慧管道執行、內建調度和部署工具。 開始使用以下命令。 ``` pip install taipy ``` 這是一個典型的Python函數,也是過濾器場景中使用的唯一任務。 ``` def filter_genre(initial_dataset: pd.DataFrame, selected_genre): filtered_dataset = initial_dataset[initial_dataset['genres'].str.contains(selected_genre)] filtered_data = filtered_dataset.nlargest(7, 'Popularity %') return filtered_data ``` 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 他們還有很多可供您建立的[演示應用程式教學](https://docs.taipy.io/en/latest/knowledge_base/demos/)。 https://github.com/Avaiga/taipy --- 15. [LocalForage](https://github.com/localForage/localForage) - 改進了離線儲存。 ------------------------------------------------------------------------ ![當地飼料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hlrka5pybvmgmo2djel.png) LocalForage 是一個 JavaScript 函式庫,它透過使用非同步資料儲存和簡單的、類似 localStorage 的 API 來改善 Web 應用程式的離線體驗。它允許開發人員儲存多種類型的資料而不僅僅是字串。 開始使用以下 npm 指令。 ``` npm install localforage ``` 只需包含 JS 檔案並開始使用 localForage。 ``` <script src="localforage.js"></script> ``` 您可以閱讀[文件](https://localforage.github.io/localForage/#installation)。 https://github.com/localForage/localForage --- 16. [Zod](https://github.com/colinhacks/zod) - 使用靜態類型推斷的 TypeScript-first 模式驗證。 ------------------------------------------------------------------------------- ![佐德](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s6zvmqr0lv93vsrhofs.png) Zod 的目標是透過最大限度地減少重複的類型聲明來對開發人員友好。使用 Zod,您聲明一次驗證器,Zod 將自動推斷靜態 TypeScript 類型。將更簡單的類型組合成複雜的資料結構很容易。 開始使用以下 npm 指令。 ``` npm install zod ``` 這是您在建立字串架構時自訂一些常見錯誤訊息的方法。 ``` const name = z.string({ required_error: "Name is required", invalid_type_error: "Name must be a string", }); ``` 您可以閱讀[文件](https://zod.dev/)。 它適用於 Node.js 和所有現代瀏覽器 https://github.com/colinhacks/zod --- 17.[多普勒](https://github.com/DopplerHQ)- 管理你的秘密。 ----------------------------------------------- ![多普勒](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gycxnuiiwsvibryrytlc.png) 您可以透過在具有開發、暫存和生產環境的專案中組織機密來消除機密蔓延。 開始使用以下指令 (MacOS)。 ``` $ brew install dopplerhq/cli/doppler $ doppler --version ``` 這是安裝 Doppler CLI[的 GitHub Actions 工作流程](https://github.com/DopplerHQ/cli-action)。 您可以閱讀[文件](https://docs.doppler.com/docs/start)。 ``` name: Example action on: [push] jobs: my-job: runs-on: ubuntu-latest steps: - name: Install CLI uses: dopplerhq/cli-action@v3 - name: Do something with the CLI run: doppler secrets --only-names env: DOPPLER_TOKEN: ${{ secrets.DOPPLER_TOKEN }} ``` https://github.com/DopplerHQ --- 18. [FastAPI](https://github.com/tiangolo/fastapi) - 高效能、易於學習、快速編碼、可用於生產。 ------------------------------------------------------------------------- ![快速API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h2awncoia6255ycl95lk.png) FastAPI 是一個現代、快速(高效能)的 Web 框架,用於基於標準 Python 類型提示使用 Python 3.8+ 建立 API。 開始使用以下命令。 ``` $ pip install fastapi ``` 這是您開始使用 FastAPI 的方式。 ``` from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` 您的編輯器將自動完成屬性並了解它們的類型,這是使用 FastAPI 的最佳功能之一。 您可以閱讀[文件](https://fastapi.tiangolo.com/)。 https://github.com/tiangolo/fastapi --- 19. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 ---------------------------------------------------------------------------- ![流動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct732wv07pvwx0nmavp5.png) Flowise 是一款開源 UI 視覺化工具,用於建立客製化的 LLM 編排流程和 AI 代理程式。 開始使用以下 npm 指令。 ``` npm install -g flowise npx flowise start OR npx flowise start --FLOWISE_USERNAME=user --FLOWISE_PASSWORD=1234 ``` 這就是整合 API 的方式。 ``` import requests url = "/api/v1/prediction/:id" def query(payload): response = requests.post( url, json = payload ) return response.json() output = query({ question: "hello!" )} ``` 您可以閱讀[文件](https://docs.flowiseai.com/)。 https://github.com/FlowiseAI/Flowise --- 20. [Scrapy](https://github.com/scrapy/scrapy) - Python 的快速進階網頁爬行和抓取框架.. ------------------------------------------------------------------------ ![鬥志旺盛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1b2y1hzdsphw43b6v7b.png) Scrapy 是一個快速的高級網路爬行和網頁抓取框架,用於爬行網站並從頁面中提取結構化資料。它可用於多種用途,從資料探勘到監控和自動化測試。 開始使用以下命令。 ``` pip install scrapy ``` 建造並執行您的網路蜘蛛。 ``` pip install scrapy cat > myspider.py <<EOF import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://www.zyte.com/blog/'] def parse(self, response): for title in response.css('.oxy-post-title'): yield {'title': title.css('::text').get()} for next_page in response.css('a.next'): yield response.follow(next_page, self.parse) EOF scrapy runspider myspider.py ``` 您可以閱讀[文件](https://scrapy.org/doc/)。 它擁有大約 50k+ 的星星,因此對於網頁抓取來說具有巨大的可信度。 https://github.com/scrapy/scrapy --- 21. [Tone](https://github.com/Tonejs/Tone.js) - 在瀏覽器中製作互動式音樂。 ------------------------------------------------------------- ![音調.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fokxsoblaohgs4tx75g3.png) 開始使用以下 npm 指令。 ``` npm install tone ``` 這是您開始使用 Tone.js 的方法 ``` // To import Tone.js: import * as Tone from 'tone' //create a synth and connect it to the main output (your speakers) const synth = new Tone.Synth().toDestination(); //play a middle 'C' for the duration of an 8th note synth.triggerAttackRelease("C4", "8n"); ``` 您可以閱讀[文件](https://github.com/Tonejs/Tone.js?tab=readme-ov-file#installation)。 https://github.com/Tonejs/Tone.js --- 22. [Spacetime](https://github.com/spencermountain/spacetime) - 輕量級 javascript 時區庫。 ----------------------------------------------------------------------------------- ![時空](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abfyfuzt4nw4h7b8usab.png) 您可以計算遠端時區的時間;支持夏令時、閏年和半球。按季度、季節、月份、週來定位時間.. 開始使用以下 npm 指令。 ``` npm install spacetime ``` 您可以這樣使用它。 ``` <script src="https://unpkg.com/spacetime"></script> <script> var d = spacetime('March 1 2012', 'America/New_York') //set the time d = d.time('4:20pm') d = d.goto('America/Los_Angeles') d.time() //'1:20pm' </script> ``` https://github.com/spencermountain/spacetime --- 23. [Mermaid](https://github.com/mermaid-js/mermaid) - 從類似 markdown 的文字產生圖表。 ---------------------------------------------------------------------------- ![美人魚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ggubn86xv7fznxol6fw7.png) 您可以使用 Markdown with Mermaid 等文字產生流程圖或序列圖等圖表。 這就是建立圖表的方法。 ``` sequenceDiagram Alice->>John: Hello John, how are you? loop Healthcheck John->>John: Fight against hypochondria end Note right of John: Rational thoughts! John-->>Alice: Great! John->>Bob: How about you? Bob-->>John: Jolly good! ``` 它將做出如下圖。 ![圖表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bbuo2ey5q2x3sjwywizg.png) 您可以閱讀[VS Code](https://docs.mermaidchart.com/plugins/visual-studio-code)的[文件](https://mermaid.js.org/intro/getting-started.html)和外掛程式。 請參閱[即時編輯器](https://mermaid.live/edit#pako:eNpVkE1PwzAMhv9KlvM-2AZj62EIxJd24ADXXLzEbaKlcUkdUDX1v5MONomcnNevXz32UWoyKAvZ4mfCoPHRQRWhVuHeO42T7XZHNhTiFb0nMdRjYelbQETRUbpTwRM1uQ2erbaoDyqI_AbnZfjZVZYFVOBCy8J2DWlLwUQHKmAwKrwRo4gnF5Xid-gd2FEAL9hSyp12pMIpNcee2ArxEhH4LG-3D7TPoAPcnhL_4WVxcgHZkfedqIjMSI5ljbEGZ_LyxwFaSbZYo5JFLg3Eg5Iq9NkHiemjC1oWHBOOZWoM8PlQ_8Un45iiLErwbRY9gcH8PUrumuHKlWs5J2oKpasGPUWfZcvctMVsNrSnlWOb9lNN9ax1xkJk-7VZzVaL1RoWS1zdLuFmuTR6P9-sy8X1vDS3V_MFyL7vfwD_bJ1W)中的範例。 https://github.com/mermaid-js/mermaid --- 24.[公共 API](https://github.com/public-apis/public-apis) - 20 多個類別的 1400 多個 API。 ------------------------------------------------------------------------------- ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjapk9rwlzdl6bcyqdnl.png) 我們主要使用外部 API 來建立應用程式,在這裡您可以找到所有 API 的清單。網站連結在最後。 它在 GitHub 上擁有大約 279k+ 顆星。 ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rld5i88smezo1naawz7a.png) 從儲存庫取得網站連結非常困難。所以,我把它貼在這裡。 網址 - [Collective-api.vercel.app/](https://collective-api.vercel.app/) https://github.com/public-apis/public-apis --- 25. [Framer Motion](https://github.com/framer/motion) - 像魔法一樣的動畫。 ----------------------------------------------------------------- ![成幀器運動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hn4ecqkrhs8f4729bzps.png) 可用的最強大的動畫庫之一。 Framer 使用簡單的聲明性語法意味著您編寫的程式碼更少。更少的程式碼意味著您的程式碼庫更易於閱讀和維護。 您可以建立事件和手勢,並且使用 Framer 的社區很大,這意味著良好的支援。 開始使用以下 npm 指令。 ``` npm install framer-motion ``` 您可以這樣使用它。 ``` import { motion } from "framer-motion" <motion.div whileHover={{ scale: 1.2 }} whileTap={{ scale: 1.1 }} drag="x" dragConstraints={{ left: -100, right: 100 }} /> ``` 您可以閱讀[文件](https://www.framer.com/motion/introduction/)。 https://github.com/framer/motion --- 26.[順便說一句](https://github.com/btw-so/btw)- 在幾分鐘內建立您的個人部落格。 ---------------------------------------------------------- ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnne3lrfpolotmxkdz2m.png) 順便說一句,您可以註冊並使用,而無需安裝任何東西。您也可以使用開源版本自行託管。 ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rli7hpoccqwpvba29b4.png) 使用順便說一句建立的[範例部落格](https://www.siddg.com/about)。 https://github.com/btw-so/btw --- 27. [Formbricks](https://github.com/formbricks/formbricks) - 開源調查平台。 -------------------------------------------------------------------- ![成型磚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tp6ggyom33vdifd3m1vt.png) Formbricks 提供免費、開源的測量平台。透過精美的應用程式內、網站、連結和電子郵件調查收集用戶旅程中每個點的回饋。在 Formbricks 之上建置或利用預先建置的資料分析功能。 開始使用以下 npm 指令。 ``` npm install @formbricks/js ``` 這就是您開始使用 formbricks 的方法。 ``` import formbricks from "@formbricks/js"; if (typeof window !== "undefined") { formbricks.init({ environmentId: "claV2as2kKAqF28fJ8", apiHost: "https://app.formbricks.com", }); } ``` 您可以閱讀[文件](https://formbricks.com/docs/getting-started/quickstart-in-app-survey)。 https://github.com/formbricks/formbricks --- 28. [Stripe](https://github.com/stripe) - 支付基礎設施。 ------------------------------------------------- ![條紋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79yvcgsi4744cmryh15j.png) 數以百萬計的各種規模的公司在線上和親自使用 Stripe 來接受付款、發送付款、自動化財務流程並最終增加收入。 開始使用以下 npm 指令 (React.js)。 ``` npm install @stripe/react-stripe-js @stripe/stripe-js ``` 這就是使用鉤子的方法。 ``` import React, {useState} from 'react'; import ReactDOM from 'react-dom'; import {loadStripe} from '@stripe/stripe-js'; import { PaymentElement, Elements, useStripe, useElements, } from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { event.preventDefault(); if (elements == null) { return; } // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { // Show error to your customer setErrorMessage(submitError.message); return; } // Create the PaymentIntent and obtain clientSecret from your server endpoint const res = await fetch('/create-intent', { method: 'POST', }); const {client_secret: clientSecret} = await res.json(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return ( <form onSubmit={handleSubmit}> <PaymentElement /> <button type="submit" disabled={!stripe || !elements}> Pay </button> {/* Show error message to your customers */} {errorMessage && <div>{errorMessage}</div>} </form> ); }; const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh'); const options = { mode: 'payment', amount: 1099, currency: 'usd', // Fully customizable with appearance API. appearance: { /*...*/ }, }; const App = () => ( <Elements stripe={stripePromise} options={options}> <CheckoutForm /> </Elements> ); ReactDOM.render(<App />, document.body); ``` 您可以閱讀[文件](https://github.com/stripe/react-stripe-js?tab=readme-ov-file#minimal-example)。 您幾乎可以整合任何東西。它有一個巨大的選項清單。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67f3pb2i8xolt635rp2p.png) https://github.com/stripe --- 29. [Upscayl](https://github.com/upscayl/upscayl) - 開源 AI 影像升級器。 ---------------------------------------------------------------- ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c1837rev5jb260ro2sd.png) 適用於 Linux、MacOS 和 Windows 的免費開源 AI Image Upscaler 採用 Linux 優先概念建構。 它可能與全端無關,但它對於升級圖像很有用。 ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4qq1wm3wey3vihn9al4.png) 透過最先進的人工智慧,Upscayl 可以幫助您將低解析度影像變成高解析度。清脆又鋒利! https://github.com/upscayl/upscayl --- 30.[重新發送](https://github.com/resend)- 為開發人員提供的電子郵件 API。 ------------------------------------------------------- ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3auhh3hbxjmmzehe5v0.png) 您可以使用 React 建立和傳送電子郵件。 2023 年最受炒作的產品之一。 開始使用以下 npm 指令。 ``` npm install @react-email/components -E ``` 這是將其與 next.js 專案整合的方法。 ``` import { EmailTemplate } from '@/components/email-template'; import { Resend } from 'resend'; const resend = new Resend(process.env.RESEND_API_KEY); export async function POST() { const { data, error } = await resend.emails.send({ from: '[email protected]', to: '[email protected]', subject: 'Hello world', react: EmailTemplate({ firstName: 'John' }), }); if (error) { return Response.json({ error }); } return Response.json(data); } ``` 您可以閱讀[文件](https://resend.com/docs/introduction)。 ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rer9ym187e4i9l11afkg.png) 基本概念是一個簡單、優雅的介面,讓您可以在幾分鐘內開始發送電子郵件。它可以透過適用於您最喜歡的程式語言的 SDK 直接融入您的程式碼中。 https://github.com/resend --- 哇!如此長的專案清單。 我知道您有更多想法,分享它們,讓我們一起建造:D 如今建立全端應用程式並不難,但每個應用程式都可以透過有效地使用優秀的開源專案來解決任何問題來增加這一獨特因素。 例如,您可以建立一些提供通知或建立 UI 流來抓取資料的東西。 我希望其中一些內容對您的開發之旅有用。他們擁有一流的開發人員經驗;你可以依賴他們。 由於您將要建造東西,因此您可以在這裡找到一些[瘋狂的想法](https://github.com/florinpop17/app-ideas)。 祝你有美好的一天!直到下一次。 --- 原文出處:https://dev.to/copilotkit/im-building-a-full-stack-app-here-are-the-libraries-im-going-to-use-51nk

我如何建立 NotesGPT – 一個全端人工智慧語音筆記應用程式

上週,我推出了[notesGPT](https://usenotesgpt.com/) ,這是一款免費開源語音記事應用程式,上週迄今為止已有[35,000 名訪客](https://twitter.com/nutlope/status/1760053364791050285)、7,000 名用戶和超過 1,000 名 GitHub star。它允許您錄製語音筆記,使用[Whisper](https://github.com/openai/whisper)進行轉錄,並透過[Together](https://together.ai/)使用 Mixtral 來提取操作項並將其顯示在操作項視圖中。它也是[完全開源的](https://github.com/nutlope/notesgpt),配備了身份驗證、儲存、向量搜尋、操作項,並且在行動裝置上完全響應,易於使用。 我將向您詳細介紹我是如何建造它的。 架構和技術堆疊 ------- 這是架構的快速圖表。我們將更深入地討論每個部分,並同時展示程式碼範例。 ![架構圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjl3i4bu23fn0pabldsw.png) 這是我使用的整體技術堆疊: - 資料庫和雲端函數的[convex](https://convex.dev/) - Next.js [App Router](https://nextjs.org/docs/app)框架 - [複製](https://replicate.com/)Whisper 轉錄 - LLM 與[JSON 模式](https://docs.together.ai/docs/json-mode)的[Mixtral](https://mistral.ai/news/mixtral-of-experts/) - [Together.ai](http://Together.ai)用於推理和嵌入 - 用於儲存語音註釋的[凸檔存儲](https://docs.convex.dev/file-storage) - [凸向量搜尋](https://docs.convex.dev/vector-search)用於向量搜尋 - 負責使用者身份驗證的[職員](https://clerk.dev/) - [Tailwind CSS](https://tailwindcss.com/)樣式 登陸頁面 ---- 該應用程式的第一部分是您導航到notesGPT 時看到的登入頁面。 ![NotesGPT 的登陸頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hfscmudh4l33oab3azw.png) 用戶首先看到的是這個登陸頁面,它與應用程式的其餘部分一起使用 Next.js 和 Tailwind CSS 進行樣式建立。我喜歡使用 Next.js,因為它可以輕鬆啟動 Web 應用程式並編寫 React 程式碼。 Tailwind CSS 也很棒,因為它允許您在網頁上快速迭代,同時與 JSX 保持在同一檔案中。 與 Clerk 和 Convex 進行身份驗證 ----------------------- 當使用者點擊主頁上的任一按鈕時,他們將被導向到登入畫面。這是由 Clerk 提供支援的,這是一個與 Convex 很好整合的簡單身份驗證解決方案,我們將在整個後端使用它,包括雲端功能、資料庫、儲存和向量搜尋。 ![認證頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02khgd6f2jfew1w7dufn.png) Clerk 和 Convex 都很容易設定。您只需在這兩個服務上建立一個帳戶,安裝它們的 npm 庫,執行`npx convex dev`來設定您的凸資料夾,然後建立一個如下所示的`ConvexProvider.ts`檔案來包裝您的應用程式。 ``` 'use client'; import { ReactNode } from 'react'; import { ConvexReactClient } from 'convex/react'; import { ConvexProviderWithClerk } from 'convex/react-clerk'; import { ClerkProvider, useAuth } from '@clerk/nextjs'; const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!); export default function ConvexClientProvider({ children, }: { children: ReactNode; }) { return ( <ClerkProvider publishableKey={process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY!} > <ConvexProviderWithClerk client={convex} useAuth={useAuth}> {children} </ConvexProviderWithClerk> </ClerkProvider> ); } ``` 請查看[Convex Quickstart](https://docs.convex.dev/quickstart/nextjs)和[Convex Clerk](https://docs.convex.dev/auth/clerk) auth 部分以了解更多詳細資訊。 設定我們的架構 ------- 您可以在有或沒有模式的情況下使用 Convex。就我而言,我知道資料的結構並想要定義它,所以我在下面這樣做了。這也為您提供了一個非常好的類型安全 API,可以在與資料庫互動時使用。我們定義兩個表格-一個用於儲存所有語音註解資訊的`notes`表和用於提取的操作專案的`actionItems`表。我們還將定義索引,以便能夠透過`userId`和`noteId`快速查詢資料。 ``` import { defineSchema, defineTable } from 'convex/server'; import { v } from 'convex/values'; export default defineSchema({ notes: defineTable({ userId: v.string(), audioFileId: v.string(), audioFileUrl: v.string(), title: v.optional(v.string()), transcription: v.optional(v.string()), summary: v.optional(v.string()), embedding: v.optional(v.array(v.float64())), generatingTranscript: v.boolean(), generatingTitle: v.boolean(), generatingActionItems: v.boolean(), }) .index('by_userId', ['userId']) .vectorIndex('by_embedding', { vectorField: 'embedding', dimensions: 768, filterFields: ['userId'], }), actionItems: defineTable({ noteId: v.id('notes'), userId: v.string(), task: v.string(), }) .index('by_noteId', ['noteId']) .index('by_userId', ['userId']), }); ``` 儀表板 --- 現在我們已經有了後端和身份驗證設定以及模式,我們可以看看如何獲取資料。登入應用程式後,用戶可以查看其儀表板,其中列出了他們錄製的所有語音筆記。 ![儀表板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6u9f1b60kgfp4txbszur.png) 為此,我們首先在凸資料夾中定義一個查詢,該查詢使用 auth 接收`userId` ,驗證其有效,並傳回與使用者的`userId`相符的所有註解。 ``` export const getNotes = queryWithUser({ args: {}, handler: async (ctx, args) => { const userId = ctx.userId; if (userId === undefined) { return null; } const notes = await ctx.db .query('notes') .withIndex('by_userId', (q) => q.eq('userId', userId)) .collect(); const results = Promise.all( notes.map(async (note) => { const count = ( await ctx.db .query('actionItems') .withIndex('by_noteId', (q) => q.eq('noteId', note._id)) .collect() ).length; return { count, ...note, }; }), ); return results; }, }); ``` 之後,我們可以透過凸提供的函數使用使用者的驗證令牌來呼叫此`getNotes`查詢,以在儀表板中顯示所有使用者的註解。我們使用伺服器端渲染在伺服器上取得此資料,然後將其傳遞到`<DashboardHomePage />`客戶端元件。這也確保了客戶端上的資料也保持最新。 ``` import { api } from '@/convex/_generated/api'; import { preloadQuery } from 'convex/nextjs'; import DashboardHomePage from './dashboard'; import { getAuthToken } from '../auth'; const ServerDashboardHomePage = async () => { const token = await getAuthToken(); const preloadedNotes = await preloadQuery(api.notes.getNotes, {}, { token }); return <DashboardHomePage preloadedNotes={preloadedNotes} />; }; export default ServerDashboardHomePage; ``` 錄製語音筆記 ------ 最初,使用者的儀表板上不會有任何語音註釋,因此他們可以點擊「錄製新語音註釋」按鈕來錄製。他們將看到以下螢幕,允許他們進行錄製。 ![錄製語音筆記頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3lm22akd3zanf3ar0za.png) 這將使用本機瀏覽器 API 錄製語音筆記,將檔案保存在 Convex 檔案儲存中,然後透過 Replicate 將其傳送至 Whisper 進行轉錄。我們要做的第一件事是在凸資料夾中定義一個`createNote`突變,它將接收此記錄,在凸資料庫中保存一些訊息,然後呼叫耳語操作。 ``` export const createNote = mutationWithUser({ args: { storageId: v.id('_storage'), }, handler: async (ctx, { storageId }) => { const userId = ctx.userId; let fileUrl = (await ctx.storage.getUrl(storageId)) as string; const noteId = await ctx.db.insert('notes', { userId, audioFileId: storageId, audioFileUrl: fileUrl, generatingTranscript: true, generatingTitle: true, generatingActionItems: true, }); await ctx.scheduler.runAfter(0, internal.whisper.chat, { fileUrl, id: noteId, }); return noteId; }, }); ``` 耳語動作如下圖所示。它使用 Replicate 作為 Whisper 的託管提供者。 ``` export const chat = internalAction({ args: { fileUrl: v.string(), id: v.id('notes'), }, handler: async (ctx, args) => { const replicateOutput = (await replicate.run( 'openai/whisper:4d50797290df275329f202e48c76360b3f22b08d28c196cbc54600319435f8d2', { input: { audio: args.fileUrl, model: 'large-v3', translate: false, temperature: 0, transcription: 'plain text', suppress_tokens: '-1', logprob_threshold: -1, no_speech_threshold: 0.6, condition_on_previous_text: true, compression_ratio_threshold: 2.4, temperature_increment_on_fallback: 0.2, }, }, )) as whisperOutput; const transcript = replicateOutput.transcription || 'error'; await ctx.runMutation(internal.whisper.saveTranscript, { id: args.id, transcript, }); }, }); ``` 此外,所有這些檔案都可以在 Convex 儀表板的「檔案」下看到。 ![凸形儀表板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mz51ysreunwsk52tqjr9.png) 生成行動專案 ------ 使用者完成語音記錄並透過耳語進行轉錄後,輸出將傳遞到 Together AI 中。我們同時顯示此加載畫面。 ![頁面載入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rcr80meap2xql9nrzlf.png) 我們首先定義一個我們希望輸出所在的模式。然後,我們將此模式傳遞到 Together.ai 上託管的 Mixtral 模型中,並提示辨識語音註釋的摘要、文字記錄,並根據成績單。然後我們將所有這些資訊保存到 Convex 資料庫中。為此,我們在凸資料夾中建立一個凸動作。 ``` // convex/together.ts const NoteSchema = z.object({ title: z .string() .describe('Short descriptive title of what the voice message is about'), summary: z .string() .describe( 'A short summary in the first person point of view of the person recording the voice message', ) .max(500), actionItems: z .array(z.string()) .describe( 'A list of action items from the voice note, short and to the point. Make sure all action item lists are fully resolved if they are nested', ), }); export const chat = internalAction({ args: { id: v.id('notes'), transcript: v.string(), }, handler: async (ctx, args) => { const { transcript } = args; const extract = await client.chat.completions.create({ messages: [ { role: 'system', content: 'The following is a transcript of a voice message. Extract a title, summary, and action items from it and answer in JSON in this format: {title: string, summary: string, actionItems: [string, string, ...]}', }, { role: 'user', content: transcript }, ], model: 'mistralai/Mixtral-8x7B-Instruct-v0.1', response_model: { schema: NoteSchema, name: 'SummarizeNotes' }, max_tokens: 1000, temperature: 0.6, max_retries: 3, }); const { title, summary, actionItems } = extract; await ctx.runMutation(internal.together.saveSummary, { id: args.id, summary, actionItems, title, }); }); ``` 當 Together.ai 做出回應時,我們會看到最終畫面,使用者可以在左側的記錄和摘要之間切換,並查看並勾選右側的操作專案。 ![完整語音筆記頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cnd6j68hgusa0aj2buhv.png) 向量搜尋 ---- 該應用程式的最後一部分是向量搜尋。我們使用 Together.ai 嵌入來嵌入文字記錄,並使人們可以根據文字記錄的語義在儀表板中進行搜尋。 我們透過在凸資料夾中建立一個`similarNotes`操作來實現此目的,該操作接受使用者的搜尋查詢,為其產生嵌入,並找到要在頁面上顯示的最相似的註釋。 ``` export const similarNotes = actionWithUser({ args: { searchQuery: v.string(), }, handler: async (ctx, args): Promise<SearchResult[]> => { // 1. Create the embedding const getEmbedding = await togetherai.embeddings.create({ input: [args.searchQuery.replace('/n', ' ')], model: 'togethercomputer/m2-bert-80M-32k-retrieval', }); const embedding = getEmbedding.data[0].embedding; // 2. Then search for similar notes const results = await ctx.vectorSearch('notes', 'by_embedding', { vector: embedding, limit: 16, filter: (q) => q.eq('userId', ctx.userId), // Only search my notes. }); return results.map((r) => ({ id: r._id, score: r._score, })); }, }); ``` 結論 -- 就像這樣,我們建立了一個可投入生產的全端人工智慧應用程式,配備身份驗證、資料庫、儲存和 API。請隨意查看[notesGPT,](https://usenotesgpt.com/)以從您的筆記或[GitHub 儲存庫](https://github.com/nutlope/notesGPT)產生操作專案以供參考。如果您有任何疑問,[請私訊我](twitter.com/nutlope),我將非常樂意回答! --- 原文出處:https://dev.to/nutlope/how-i-built-notesgpt-a-full-stack-ai-voice-note-app-265o

軟體工程師面試學習指南

[本·羅戈揚](https://www.linkedin.com/in/benjaminrogojan/) 軟體工程面試與其他技術面試一樣,需要充分的準備。有許多主題需要涵蓋,以確保您準備好應對有關演算法、資料結構、設計、最佳化以及不斷增長的主題的連續問題。 因此,我在最後一輪面試中建立了一個清單,涵蓋了許多熱門話題。 為了幫助您追蹤進度,我們針對下面列出的相同問題編制了一份全面的清單; [該列表可以在這裡找到](https://docs.google.com/spreadsheets/d/19hSRrL4l3gRiJ5ucH9q4iwFo2QHgic9gGMNUrcn1mm0/edit?usp=sharing)。 ### **聆聽經典熱身** 1. [fizzbuzz](https://www.hackerrank.com/challenges/fizzbuzz/problem) 2. [子陣列和等於 K](https://leetcode.com/problems/subarray-sum-equals-k/) 3. [陣列:左旋轉](https://www.hackerrank.com/challenges/ctci-array-left-rotation/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays) 4. [字串:製作字謎詞](https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings) 5. [第 N 次斐波那契數](https://www.algoexpert.io/questions/Nth%20Fibonacci) 你怎麼做的?花點時間對這些經典作品進行評價。我們在面試過程中的某個時刻被問到了其中大部分問題,而且通常是在早期就被問到的淘汰式問題。它們通常與演算法和資料結構關係不大,但仍然需要對循環和陣列有很好的理解(是的,陣列是一種資料結構)。 ### **演算法和資料結構** #### **預習問題** 在觀看有關資料結構和演算法的影片內容之前,請考慮嘗試以下這些問題。看看你能否回答他們。這將幫助您知道要關注什麼。 1. [985. 查詢後偶數之和](https://leetcode.com/problems/sum-of-even-numbers-after-queries/) 2. [657. 機器人回歸原點](https://leetcode.com/problems/robot-return-to-origin/) 3. [961. 2N 陣列中的 N 重複元素](https://leetcode.com/problems/n-repeated-element-in-size-2n-array/) 4. [110.平衡二元樹](https://leetcode.com/problems/balanced-binary-tree/) 5. [3. 最長無重複字元的子字串](https://leetcode.com/problems/longest-substring-without-repeating-characters/) 6. [19. 從清單結尾刪除第 N 個節點](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) 7. [23. 合併 k 個排序列表](https://leetcode.com/problems/merge-k-sorted-lists/) 8. [31. 下一個排列](https://leetcode.com/problems/next-permutation/) ### 演算法和資料結構影片 #### 資料結構 ![](https://cdn-images-1.medium.com/max/1600/1*Dyu63sMUVL-gYEZISOE2BQ.jpeg) 1. [資料結構與演算法 #1 --- 什麼是資料結構?](https://www.youtube.com/watch?v=bum_19loj9A) --- 影片 2. [多調光](https://archive.org/details/0102WhatYouShouldKnow/02_05-multidimensionalArrays.mp4)--- 影片 3. [動態陣列](https://www.coursera.org/learn/data-structures/lecture/EwbnV/dynamic-arrays)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 4. [調整陣列大小](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 5. [資料結構:鍊錶](https://youtu.be/njTh_OwMljA)--- 影片 6. [核心鍊錶與陣列](https://www.coursera.org/learn/data-structures-optimizing-performance/lecture/rjBs9/core-linked-lists-vs-arrays)--- 影片 7. [指針到指針](https://www.eskimo.com/~scs/cclass/int/sx8.html)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 8. [資料結構:樹](https://youtu.be/oSWTXtMglKE)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 9. [資料結構:堆](https://youtu.be/t0Cq6tVNRBA)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 10. [資料結構:哈希表](https://youtu.be/shs0KM3wKv8)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 11. [電話簿問題](https://www.coursera.org/learn/data-structures/lecture/NYZZP/phone-book-problem)---影片 12. [資料結構:堆疊和佇列](https://youtu.be/wjI1WNcIntg)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 13. [使用堆疊後進先出](https://archive.org/details/0102WhatYouShouldKnow/05_01-usingStacksForLast-inFirst-out.mp4)--- 影片 14. [資料結構:計算機科學速成課程#14](https://youtu.be/DuDz6B4cqVc)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 15. [資料結構:嘗試](https://www.youtube.com/watch?v=zIjfhVPRZCg)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 #### 演算法 ![](https://cdn-images-1.medium.com/max/1600/1*bPpvELo9_QqQsDz7CSbwXQ.gif) 1. [演算法:圖搜尋、DFS 和 BFS](https://www.youtube.com/watch?v=zaBhtODEL0w&list=PLX6IKgS15Ue02WDPRCmYKuZicQHit9kFt)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 2. [BFS(廣度優先搜尋)和DFS(深度優先搜尋)](https://www.youtube.com/watch?v=uWL6FJhq5fM) --- 影片 3. [演算法:二分查找](https://youtu.be/P3YID7liBug)---影片 4. [二元搜尋樹回顧](https://www.youtube.com/watch?v=x6At0nzX92o&index=1&list=PLA5Lqm4uh9Bbq-E0ZnqTIa8LRaL77ica6)--- 影片 5. [用於面試的 Python 演算法](https://www.youtube.com/watch?v=p65AHm9MX80)[ ](https://archive.org/details/0102WhatYouShouldKnow/03_01-resizableArrays.mp4)--- 影片 6. [演算法:遞歸](https://youtu.be/KEEKn7Me-ms)---影片 7. [演算法:冒泡排序](https://youtu.be/6Gv8vg0kcHc)--- 影片 8. [演算法:歸併排序](https://youtu.be/KF2j-9iSf4Q)--- 影片 9. [演算法:快速排序](https://youtu.be/SLauY6PpjW4)---影片 ### **大 O 表示法** 1. [大 O 表示法與時間複雜度簡介(資料結構與演算法 #7)](https://www.youtube.com/watch?v=D6xkbGLQesk) --- 影片 2. [哈佛 CS50 --- 漸近符號](https://www.youtube.com/watch?v=iOq5kSKqeR4)--- 影片 3. [演算法複雜度分析的簡單介紹](http://discrete.gr/complexity/)--- Post 4. [備忘錄](http://bigocheatsheet.com/)--- 帖子 ### **動態規劃** 1. [動態規劃(像程式設計師一樣思考)---影片](https://www.youtube.com/watch?v=iv_yHjmkv4I) 2. [演算法:記憶化與動態規劃 --- 影片](https://www.youtube.com/watch?v=P8Xa2BitN3I&t=13s) 3. 6 [.006:動態規劃 I:斐波那契、最短路徑 --- 影片](https://www.youtube.com/watch?v=OQ5jsbhAv_M&t=7s) 4. [6.006:動態規劃 II:文字對齊、二十一點 --- 影片](https://www.youtube.com/watch?v=ENyox7kNKeY&t=4s) 5. [動態規劃 --- 帖子](https://www.topcoder.com/community/competitive-programming/tutorials/dynamic-programming-from-novice-to-advanced/) ### **字串操作** 1. [編碼面試問答:最長的連續字元](https://www.youtube.com/watch?v=qRNB8CV3_LU)--- 影片 2. [Sedgewick --- 子字串搜尋](https://www.coursera.org/learn/algorithms-part2/home/week/4)--- 影片 #### 面試問題演練 1. [谷歌編碼面試 --- 普世價值樹問題](https://www.youtube.com/watch?v=7HgsS8bRvjo)--- 影片 2. [Google 編碼面試問題和答案 #1:第一個重複出現的字元](https://www.youtube.com/watch?v=GJdiM-muYqc)--- 影片 3. [在二元搜尋樹中找到最小和最大元素](https://www.youtube.com/watch?v=Ut90klNN264&index=30&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P)--- 影片 4. [求二元樹的高度](https://www.youtube.com/watch?v=_pnqMz5nrRs&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P&index=31)--- 影片 5. [檢查二元樹是否為二元搜尋樹](https://www.youtube.com/watch?v=yEwSGhSsT0U&index=35&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P)--- 影片 6. [什麼是尾遞歸?為什麼這麼糟?](https://www.quora.com/What-is-tail-recursion-Why-is-it-so-bad) --- 影片 ### **學後問題** 現在您已經學習了一些,並觀看了一些影片,讓我們嘗試更多問題! 1. [越大越好](https://www.hackerrank.com/challenges/bigger-is-greater/problem) 2. [6.之字折線轉換](https://leetcode.com/problems/zigzag-conversion/) 3. [7. 反轉整數](https://leetcode.com/problems/reverse-integer/) 4. [40. 組合和 II](https://leetcode.com/problems/combination-sum-ii/) 5. [43. 字串相乘](https://leetcode.com/problems/multiply-strings/) 6. [拉里的陣列](https://www.hackerrank.com/challenges/larrys-array/problem) 7. [短回文](https://www.hackerrank.com/challenges/short-palindrome/problem) 8. [65. 有效號碼](https://leetcode.com/problems/valid-number/) 9. [越大越好](https://www.hackerrank.com/challenges/bigger-is-greater/problem) 10. [完整計數排序](https://www.hackerrank.com/challenges/countingsort4/problem) 11. [莉莉的家庭作業](https://www.hackerrank.com/challenges/lilys-homework/problem) 12. [普通孩子](https://www.hackerrank.com/challenges/common-child/problem) 13. [459. 重複子字串模式](https://leetcode.com/problems/repeated-substring-pattern/) 14. [27. 刪除元素](https://leetcode.com/problems/remove-element/) 15. [450. 刪除 BST 中的節點](https://leetcode.com/problems/delete-node-in-a-bst/) 16. [659. 將陣列分割成連續的子序列](https://leetcode.com/problems/split-array-into-consecutive-subsequences/) 17. [最大值有界的子陣列數](https://leetcode.com/problems/number-of-subarrays-with-bounded-maximum) 18. [組合和 IV](https://leetcode.com/problems/combination-sum-iv) 19. [買賣股票的最佳時機(有冷卻時間)](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown) 20. [最長重複字元替換](https://leetcode.com/problems/longest-repeating-character-replacement) 21. [成對交換節點](https://leetcode.com/problems/swap-nodes-in-pairs) 22. [二元樹右側視圖](https://leetcode.com/problems/binary-tree-right-side-view) 23. [展平嵌套列表迭代器](https://leetcode.com/problems/flatten-nested-list-iterator) 24. [二元樹層次順序遍歷](https://leetcode.com/problems/binary-tree-level-order-traversal) 25. [二元搜尋樹迭代器](https://leetcode.com/problems/binary-search-tree-iterator) 26. [對鏈最大長度](https://leetcode.com/problems/maximum-length-of-pair-chain) 27. [將鍊錶拆分為多個部分](https://leetcode.com/problems/split-linked-list-in-parts) ### **操作性程式設計問題** 有些公司不會問你演算法問題。相反,他們可能會更專注於實施和營運問題。這些通常更小眾,涉及實際問題,例如循環資料和執行某種任務。這些類型的問題通常不需要太多練習,因為更多的是了解陣列和 HashMap 等基本概念並追蹤您對它們所做的事情。 1. [袋鼠問題](https://www.hackerrank.com/challenges/kangaroo/problem) 2. [打破記錄](https://www.hackerrank.com/challenges/breaking-best-and-worst-records/problem) 3. [查找字串](https://www.hackerrank.com/challenges/find-a-string/problem)[迭代器](https://www.hackerrank.com/challenges/itertools-permutations/problem) 4. [不知道!](https://www.hackerrank.com/challenges/no-idea/problem) 5. [程式設計師的日子](https://www.hackerrank.com/challenges/day-of-the-programmer/problem) 6. [排行榜](https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem) 7. [詞序](https://www.hackerrank.com/challenges/word-order/problem) 8. [夏洛克和方塊](https://www.hackerrank.com/challenges/sherlock-and-squares/problem) 9. [均衡陣列](https://www.hackerrank.com/challenges/equality-in-a-array/problem) 10. [蘋果和橘子](https://www.hackerrank.com/challenges/apple-and-orange/problem) 11. [更多操作風格問題](https://www.hackerrank.com/domains/python) ### **系統設計影片** 系統設計問題是至關重要的問題,表明您不僅僅是一名編碼員。身為工程師,您需要能夠思考大局。某些服務屬於哪裡,您需要什麼樣的伺服器,您將如何管理流量等等。所有這些想法都表明您能夠設計軟體,而不僅僅是編寫人們告訴您編寫的程式碼。 1. [停車場系統](https://youtu.be/DSGsa0pu8-k)---影片 2. [什麼是應用程式](https://www.youtube.com/watch?v=vvhC64hQZMk)--- 影片 3. [優步設計](https://youtu.be/umWABit-wbk)---影片 4. [Instagram](https://www.youtube.com/watch?v=QmX2NPkJTKg) --- 影片 5. [Tinder 服務](https://www.youtube.com/watch?v=xQnIN9bW0og)--- 影片 ### **作業系統** 作業系統問題比較少見,但是對執行緒、調度、記憶體等概念有紮實的理解是有好處的,即使只是基本的理解。當被問到進程和線程有什麼區別而不知道答案時,這是非常尷尬的。 1. [常見作業系統面試問題](https://www.geeksforgeeks.org/commonly-asked-operating-systems-interview-questions-set-1/) 2. [什麼是翻譯後備緩衝區?](https://www.geeksforgeeks.org/operating-system-translation-lookaside-buffer-tlb/) 3. [為什麼循環法可以避免優先反轉問題?](https://leetcode.com/discuss/interview-question/operating-system/220604/Why-does-Round-Robin-avoid-the-Priority-Inversion-Problem) 4. [中斷與系統呼叫---檔案系統中的「inode」是什麼?](https://leetcode.com/discuss/interview-question/operating-system/124838/Interrupt-Vs-System-Call) 5. [作業系統面試題目及答案 --- 第一部分](https://www.youtube.com/watch?v=b18X4uOKjHs) 6. [什麼是內核 --- Gary 解釋](https://www.youtube.com/watch?v=mycVSMyShk8) 7. [循環演算法教程(CPU調度)](https://www.youtube.com/watch?v=aWlQYllBZDs) 8. [LRU 快取的魔力(Google 開發 100 天)](https://www.youtube.com/watch?v=R5ON3iwx78M) --- 影片 9. [MIT 6.004 L15:記憶體層次結構](https://www.youtube.com/watch?v=vjYF_fAZI5E&list=PLrRW1w6CGAcXbMtDFj205vALOGmiRc82-&index=24)--- 影片 10. [中斷](https://www.youtube.com/watch?v=uFKi2-J-6II&list=PLCiOXwirraUCBE9i_ukL8_Kfg6XNv7Se8&index=3)---影片 11. [調度](https://www.youtube.com/watch?v=-Gu5mYdKbu4&index=4&list=PLCiOXwirraUCBE9i_ukL8_Kfg6XNv7Se8)---影片 ### **執行緒數** ![](https://cdn-images-1.medium.com/max/1600/1*uSHd3KSxg363C1frMv2KwQ.png) 1. [用戶級線程與內核級線程](https://leetcode.com/discuss/interview-question/operating-system/124631/User-Level-thread-Vs-Kernel-Level-thread) 2. [行程和線程簡介](https://www.youtube.com/watch?v=exbKr6fnoUw)--- 影片 3. [進程和線程之間的區別 --- 佐治亞理工學院 --- 高級操作系統](https://www.youtube.com/watch?v=O3EyzlZxx3g&t=11s)--- 影片 4. [分叉和多線程之間的區別](https://leetcode.com/discuss/interview-question/operating-system/125024/Difference-between-forking-and-multithreading) ### **物件導向** ![](https://cdn-images-1.medium.com/max/1600/1*8LHiDwWhrU4iegYiNnKX_A.png) 與作業系統類似,並不是每次面試都會問你有關物件導向程式設計的問題,但你永遠不知道。您需要確保記住計算機 162 課程中的基礎知識。 1. [Java 程式設計教學 --- 49 --- 繼承](https://www.youtube.com/watch?v=9JpNY-XAseg)--- 影片 2. [Java 程式設計教學 --- 55 --- 多態性簡介](https://www.youtube.com/watch?v=0xw06loTm1k)--- 影片 3. [Java 程式設計教學 --- 58 --- 抽象類別與具體類別](https://www.youtube.com/watch?v=TyPNvt6Zg8c)--- 影片 4. [Java 程式設計教學 --- 57 --- 重寫規則](https://www.youtube.com/watch?v=zN9pKULyoj4&t=3s)--- 影片 5. [Java 程式設計教學 --- 59 --- 保存物件的類](https://www.youtube.com/watch?v=slY5Ag7IjM0) 6. [物件導向程式設計](https://www.youtube.com/watch?v=lbXsrHGhBAU)---影片 ### **設計模式** 如果您像我們一樣,我們不會被教導所有各種設計模式。因此,最好了解它們的工作原理以及使用它們的原因。一些面試問題可以很簡單,例如“為什麼要使用工廠類?” 1. [工廠設計模式](https://www.youtube.com/watch?v=ub0DXaeV6hA)---影片 2. [觀察者設計模式](https://youtu.be/wiQdrH2YpT4)---影片 3. [適配器設計模式](https://www.youtube.com/watch?v=qG286LQM6BU&list=PLF206E906175C7E07&index=13)---影片 4. [立面設計模式](https://www.youtube.com/watch?v=B1Y8fcYrz5o&list=PLF206E906175C7E07&index=14)---影片 5. [責任鏈設計模式](https://www.youtube.com/watch?v=jDX6x8qmjbA&list=PLF206E906175C7E07&index=22)---影片 6. [解譯器設計模式](https://www.youtube.com/watch?v=6CVymSJQuJE&list=PLF206E906175C7E07&index=23)---影片 7. [單例設計模式教學](https://www.youtube.com/watch?v=NZaXM67fxbs&list=PLF206E906175C7E07&index=7)--- 影片 8. [第 6 章(第 1 部分)--- 模式(影片)](https://youtu.be/LAP2A80Ajrg?list=PLJ9pm_Rc9HesnkwKlal_buSIHA-jTZMpO&t=3344) --- 影片 9. [Head First 設計模式](https://www.amazon.com/Head-First-Design-Patterns-Freeman/dp/0596007124)--- 影片 ### SQL 這是最後一節。你們中的許多人可能不會被問到那麼多 SQL 問題。不過,我始終認為放在後口袋是件好事。 #### SQL --- 問題 1. [262. 行程和用戶](https://leetcode.com/problems/trips-and-users/) 2. [601. 體育場人流量](https://leetcode.com/problems/human-traffic-of-stadium/) 3. [185. 部門前三薪資](https://leetcode.com/problems/department-top-three-salaries/) 4. [626.交換席位](https://leetcode.com/problems/exchange-seats/) 5. [駭客排名報告](https://www.hackerrank.com/challenges/the-report/problem) 6. [177.第N最高薪水](https://leetcode.com/problems/nth-highest-salary/) 7. [對稱對](https://www.hackerrank.com/challenges/symmetric-pairs/problem) 8. [職業](https://www.hackerrank.com/challenges/placements/problem)[安置](https://www.hackerrank.com/challenges/occupations/problem) 9. [奧利凡德的庫存](https://www.hackerrank.com/challenges/harry-potter-and-wands/problem) #### SQL --- 影片 1. [IQ15:6 個 SQL 查詢面試問題](https://www.youtube.com/watch?v=uAWWhEA57bE)--- 影片 2. [了解 ROW\_NUMBER 和分析函數](https://www.youtube.com/watch?v=QFj-hZi8MKk)--- 影片 3. [分析函數的高級實現](https://www.youtube.com/watch?v=G3kYPzLWtpo&t=4s)--- 影片 4. [分析函數的高級實現第 2 部分](https://www.youtube.com/watch?v=XecU6Ieyu-4&t=54s)--- 影片 5. [聰明的貓頭鷹 SQL 影片](https://www.youtube.com/watch?v=2-1XQHAgDsM&list=PL6EDEB03D20332309)--- 影片 #### SQL 後問題 1. [二元樹節點](https://www.hackerrank.com/challenges/binary-search-tree-1/problem) 2. [氣象觀測站 18](https://www.hackerrank.com/challenges/weather-observation-station-18/problem) 3. [挑戰](https://www.hackerrank.com/challenges/challenges/problem)[列印素數](https://www.hackerrank.com/challenges/print-prime-numbers/problem) 4. [595.大國](https://leetcode.com/problems/big-countries/) 5. [626.交換席位](https://leetcode.com/problems/exchange-seats/) 6. [SQL 面試問題:3 個技術篩選練習(針對資料分析師)](https://data36.com/sql-interview-questions-tech-screening-data-analysts/) 面試可能會很困難,因為你會覺得自己沒有任何進展。擁有本學習指南將幫助您追蹤您的進度並讓您更好地了解自己的表現! 祝你好運! 另外,如果您想閱讀/觀看更多精彩的貼文或影片: [在 SaturnCloud 上使用 Jupyter Notebook 連接到大查詢第 2 部分](https://www.youtube.com/watch?v=O1cBN5gJtdw&t=15s) [身為資料科學家你應該閱讀的三本書](https://www.coriers.com/three-books-you-must-read-if-you-want-a-career-as-a-data-scientist/) [Hadoop 與關聯式資料庫](http://www.acheronanalytics.com/acheron-blog/hadoop-vs-relational-databases) [算法如何變得不道德和有偏見](http://www.acheronanalytics.com/acheron-blog/how-do-machines-learn-bias-data-science) [如何改善資料驅動策略](http://www.acheronanalytics.com/acheron-blog/how-to-improve-your-data-driven-strategy) [如何開發穩健演算法](https://medium.com/better-programming/how-to-develop-a-robust-algorithm-c38e08f32201) [資料科學家必須具備的 4 項技能](https://www.theseattledataguy.com/4-skills-data-scientist-must-have/) [SQL 最佳實踐 - 設計 ETL 影片](http://www.acheronanalytics.com/acheron-blog/sql-best-practices-designing-an-etl-video) --- 原文出處:https://dev.to/seattledataguy/the-interview-study-guide-for-software-engineers-764

Next.js 14 使用瀏覽器爬蟲,進行即時資料抓取的預訂應用程式

目錄 == - [介紹](#introduction) - [技術堆疊](#tech-stack) - [特徵](#features) - [設定 Next.js 應用程式](#step-1-setting-up-the-nextjs-application) - [安裝所需的套件](#step-2-installing-required-packages) - [設定 Redis 連接](#step-3-setting-up-redis-connection) - [配置 BullMQ 佇列](#step-4-configuring-bullmq-queue) - [Next.js 儀器設置](#step-5-nextjs-instrumentation-setup) - [設定 Bright Data 的抓取瀏覽器](#step-6-setting-up-bright-datas-scraping-browser) - [Bright Data 的抓取瀏覽器是什麼?](#what-is-bright-datas-scraping-browser) - [設定 Bright Data 抓取瀏覽器的步驟](#steps-to-set-up-bright-datas-scraping-browser) - [使用 Puppeteer 實作抓取邏輯](#implementing-the-scraping-logic-with-puppeteer) - [航班搜尋功能](#flight-search-feature) - [顯示航班搜尋結果](#displaying-flight-search-results) - [探索完整的指南和程式碼庫](#discover-the-complete-guide-and-codebase) - [在 YouTube 上觀看詳細說明](#watch-the-detailed-explanation-on-youtube) - [在 GitHub 上探索完整程式碼](#explore-the-full-code-on-github) - [結論](#conclusion) 介紹 == 在不斷發展的 Web 開發領域,有效收集、處理和顯示外部來源資料的能力變得越來越有價值。無論是市場研究、競爭分析或客戶洞察,網路抓取在釋放網路資料的巨大潛力方面都發揮著至關重要的作用。 這篇部落格文章介紹了建立強大的 Next.js 應用程式的綜合指南,該應用程式旨在從領先的旅行搜尋引擎之一 Kayak 抓取航班資料。透過利用 Next.js 的強大功能以及 BullMQ、Redis 和 Puppeteer 等現代技術。 技術堆疊 ==== - [Next.js](https://nextjs.org/docs) - [順風CSS](https://tailwindcss.com/docs) - [下一個介面](https://nextui.org/docs) - [健康)狀況](https://zustand.surge.sh/) - [條紋](https://stripe.com/docs) - [Bright Data 的抓取瀏覽器](https://brdta.com/kishansheth21) - [打字稿](https://www.typescriptlang.org/docs) - [雷迪斯](https://redis.io/documentation) - [BullMQ](https://docs.bullmq.io/) - [傀儡師](https://pptr.dev/) - [智威湯遜](https://jwt.io/introduction) - [阿克西奧斯](https://axios-http.com/docs/intro) - [PostgreSQL](https://www.postgresql.org/docs) - [棱鏡](https://www.prisma.io/docs) 特徵 == - 🚀 帶有 Tailwind CSS 的 Next.js 14 應用程式目錄 - 體驗由最新 Next.js 14 提供支援的時尚現代的 UI,並使用 Tailwind CSS 進行設計,以實現完美的外觀和感覺。 - 🔗 API 路由和伺服器操作 - 深入研究與 Next.js 14 的 API 路由和伺服器操作的無縫後端集成,確保高效的資料處理和伺服器端邏輯執行。 - 🕷 使用 Puppeteer Redis 和 BullMQ 進行抓取 - 利用 Puppeteer 的強大功能進行進階 Web 抓取,並使用 Redis 和 BullMQ 管理佇列和作業以實現強大的後端操作。 - 🔑 用於身份驗證和授權的 JWT 令牌 - 使用 JWT 令牌保護您的應用程式,為整個平台提供可靠的身份驗證和授權方法。 - 💳 支付網關 Stripe - 整合 Stripe 進行無縫支付處理,為預訂旅行、航班和飯店提供安全、輕鬆的交易。 - ✈️ 使用 Stripe 支付網關預訂旅行、航班和飯店 - 使用我們的 Stripe 支援的支付系統,讓您的旅遊預訂體驗變得輕鬆。 - 📊 從多個網站抓取即時資料 - 從多個來源抓取即時資料,保持領先,讓您的應用程式更新最新資訊。 - 💾 使用 Prisma 將抓取的資料儲存在 PostgreSQL 中 - 利用 PostgreSQL 和 Prisma 高效儲存和管理抓取的資料,確保可靠性和速度。 - 🔄 用於狀態管理的 Zustand - 透過 Zustand 簡化狀態邏輯並增強效能,在您的應用程式中享受流暢且可管理的狀態管理。 - 😈 該應用程式的最佳功能 - 使用 Bright Data 的抓取瀏覽器抓取不可抓取的資料。 ![抓取瀏覽器迷因](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e0ytki1wpsbvluk1qkpo.jpg) Bright Data的抓取瀏覽器為我們提供了自動驗證碼解決功能,可以幫助我們抓取不可抓取的資料。 第 1 步:設定 Next.js 應用程式 --------------------- 1. **建立 Next.js 應用程式**:首先建立一個新的 Next.js 應用程式(如果您還沒有)。您可以透過在終端機中執行以下命令來完成此操作: ``` npx create-next-app@latest booking-app ``` 2. **導航到您的應用程式目錄**:變更為您新建立的應用程式目錄: ``` cd booking-app ``` 步驟2:安裝所需的軟體包 ------------ 您需要安裝多個軟體包,包括 Redis、BullMQ 和 Puppeteer Core。執行以下命令來安裝它們: ``` npm install ioredis bullmq puppeteer-core ``` - `ioredis`是 Node.js 的強大 Redis 用戶端,支援與 Redis 進行通訊。 - `bullmq`以 Redis 作為後端來管理作業和訊息佇列。 - `puppeteer-core`可讓您控制外部瀏覽器以進行抓取。 步驟3:設定Redis連接 ------------- 在適當的目錄(例如`lib/` )中建立一個檔案(例如`redis.js` )來配置 Redis 連線: ``` // lib/redis.js import Redis from 'ioredis'; // Use REDIS_URL from environment or fallback to localhost const REDIS_URL = process.env.REDIS_URL || 'redis://localhost:6379'; const connection = new Redis(REDIS_URL); export { connection }; ``` 步驟4:配置BullMQ佇列 -------------- 透過在 Redis 配置所在的相同目錄中建立另一個檔案(例如, `queue.js` )來設定 BullMQ 佇列: ``` // lib/queue.js import { Queue } from 'bullmq'; import { connection } from './redis'; export const importQueue = new Queue('importQueue', { connection, defaultJobOptions: { attempts: 2, backoff: { type: 'exponential', delay: 5000, }, }, }); ``` 第 5 步:Next.js 儀器設置 ------------------ Next.js 允許偵測,可以在 Next.js 配置中啟用。您還需要建立一個用於作業處理的工作文件。 1.**在 Next.js 中啟用 Instrumentation** :將以下內容新增至`next.config.js`以啟用 Instrumentation: ``` // next.config.js module.exports = { experimental: { instrumentationHook: true, }, }; ``` 2.**建立用於作業處理的 Worker** :在您的應用程式中,建立一個檔案 ( `instrumentation.js` ) 來處理作業處理。該工作人員將使用 Puppeteer 來執行抓取任務: ``` // instrumentation.js export const register = async () => { if (process.env.NEXT_RUNTIME === 'nodejs') { const { Worker } = await import('bullmq'); const puppeteer = await import('puppeteer-core'); const { connection } = await import('./lib/redis'); const { importQueue } = await import('./lib/queue'); new Worker('importQueue', async (job) => { // Job processing logic with Puppeteer goes here }, { connection, concurrency: 10, removeOnComplete: { count: 1000 }, removeOnFail: { count: 5000 }, }); } }; ``` 第 6 步:設定 Bright Data 的抓取瀏覽器 --------------------------- 在設定 Bright 資料抓取瀏覽器之前,我們先來談談什麼是抓取瀏覽器。 ### Bright Data 的抓取瀏覽器是什麼? Bright Data 的抓取瀏覽器是一款用於自動網頁抓取的尖端工具,旨在與 Puppeteer、Playwright 和 Selenium 無縫整合。它提供了一套網站解鎖功能,包括代理輪換、驗證碼解決等,以提高抓取效率。它非常適合需要互動的複雜網頁抓取,透過在 Bright Data 基礎架構上託管無限的瀏覽器會話來實現可擴展性。如欲了解更多詳情,請造訪[光明資料](https://brdta.com/kishansheth21)。 ![明亮的資料抓取瀏覽器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c70ochb1lgdrusgicwz4.png) <a id="steps-to-set-up-bright-datas-scraping-browser"></a> #### 第 1 步:導覽至 Bright Data 網站 首先造訪[Brightdata.com](https://brdta.com/kishansheth21) 。這是您存取 Bright Data 提供的豐富網頁抓取資源和工具的入口。 ![光明資料首頁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/afgkpgytcytoqfuq0h8w.png) #### 第 2 步:建立帳戶 造訪 Bright Data 網站後,註冊並建立一個新帳戶。系統將提示您輸入基本資訊以啟動並執行您的帳戶。 ![登入/註冊 Bright Data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ffha75szs9tubh8kra9j.png) #### 第 3 步:選擇您的產品 在產品選擇頁面上,尋找代理商和抓取基礎設施產品。本產品專為滿足您的網路抓取需求而設計,提供強大的資料擷取工具和功能。 ![光明資料產品](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b058azlmjv30po6289fh.png) #### 第 4 步:新增代理 在「代理程式和抓取基礎設施」頁面中,您會找到一個「新增按鈕」。點擊此按鈕開始將新的抓取瀏覽器新增到您的工具包的過程。 ![新代理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2jscxsyt9yess1nvzi4z.png) #### 第五步:選擇抓取瀏覽器 將出現一個下拉列表,您應該從中選擇抓取瀏覽器選項。這告訴 Bright Data 您打算設定一個新的抓取瀏覽器環境。 ![選擇抓取瀏覽器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i483ipx7spwne65c6tep.png) #### 第 6 步:為您的抓取瀏覽器命名 為您的新抓取瀏覽器指定一個唯一的名稱。這有助於稍後辨識和管理它,特別是如果您計劃對不同的抓取專案使用多個瀏覽器。 ![抓取瀏覽器名稱](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n0qnitec7s7gki7t3826.png) #### 步驟7:新增瀏覽器 命名您的瀏覽器後,按一下「新增」按鈕。此操作完成了新的抓取瀏覽器的建立。 ![新增抓取瀏覽器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ao6n1edyyx2no621nh01.png) #### 第 8 步:查看您的抓取瀏覽器詳細訊息 新增抓取瀏覽器後,您將被導向到一個頁面,您可以在其中查看新建立的抓取瀏覽器的所有詳細資訊。這些資訊對於整合和使用至關重要。 ![抓取瀏覽器詳細訊息](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ev33mbgznevn6h9p60g6.png) #### 第 9 步:存取程式碼和整合範例 尋找“查看程式碼和整合範例”按鈕。點擊此按鈕將為您提供如何跨多種程式語言和程式庫整合和使用抓取瀏覽器的全面視圖。對於希望自訂抓取設定的開發人員來說,此資源非常寶貴。 ![程式碼和整合範例按鈕](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/30araqzko585yzmhrumd.png) #### 第 10 步:整合您的抓取瀏覽器 最後,複製 SRS\_WS\_ENDPOINT 變數。這是一條關鍵訊息,您需要將其整合到原始程式碼中,以便您的應用程式能夠與您剛剛設定的抓取瀏覽器進行通訊。 ![抓取瀏覽器端點](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqhpglz1lngobguk2nu4.png) 透過遵循這些詳細步驟,您已在 Bright Data 平台中成功建立了一個抓取瀏覽器,準備好處理您的網頁抓取任務。請記住,Bright Data 提供廣泛的文件和支持,幫助您最大限度地提高抓取專案的效率和效果。無論您是在收集市場情報、進行研究還是監控競爭格局,新設定的抓取瀏覽器都是資料收集庫中的強大工具。 ### 第 7 步:使用 Puppeteer 實作抓取邏輯 從我們上次設定用於抓取航班資料的 Next.js 應用程式的地方開始,下一個關鍵步驟是實現實際的抓取邏輯。此過程涉及利用 Puppeteer 連接到瀏覽器實例、導航到目標 URL(在我們的範例中為 Kayak)並抓取必要的飛行資料。提供的程式碼片段概述了實現此目標的複雜方法,與我們先前建立的 BullMQ 工作設定無縫整合。讓我們分解這個抓取邏輯的元件,並了解它如何適合我們的應用程式。 #### 建立與瀏覽器的連接 我們抓取過程的第一步是透過 Puppeteer 建立與瀏覽器的連線。這是透過利用`puppeteer.connect`方法來完成的,該方法使用 WebSocket 端點 ( `SBR_WS_ENDPOINT` ) 連接到現有的瀏覽器實例。此環境變數應設定為您正在使用的抓取瀏覽器服務的 WebSocket URL,例如 Bright Data: ``` const browser = await puppeteer.connect({ browserWSEndpoint: SBR_WS_ENDPOINT, }); ``` #### 開啟新頁面並導航到目標 URL 連線後,我們在瀏覽器中建立一個新頁面並導航到作業資料中指定的目標 URL。此 URL 是我們打算從中抓取航班資料的特定 Kayak 搜尋結果頁面: ``` const page = await browser.newPage(); await page.goto(job.data.url); ``` #### 抓取航班資料 我們邏輯的核心在於從頁面中抓取航班資料。我們透過使用`page.evaluate`來實現這一點,這是一種 Puppeteer 方法,允許我們在瀏覽器上下文中執行腳本。在此腳本中,我們等待必要的元素加載,然後繼續收集航班資訊: - **Flight Selector** :我們以`.nrc6-wrapper`類別為目標元素,其中包含航班詳細資訊。 - **資料擷取**:對於每個航班元素,我們提取詳細訊息,例如航空公司徽標、出發和到達時間、航班持續時間、航空公司名稱和價格。出發和到達時間經過清理,以刪除最後不必要的數值,確保我們準確地捕捉時間。 - **價格處理**:價格在刪除所有非數字字元後提取為整數,確保其可用於數值運算或比較。 擷取的資料被建構成飛行物件陣列,每個物件都包含上述詳細資訊: ``` const scrappedFlights = await page.evaluate(async () => { // Data extraction logic const flights = []; // Process each flight element // ... return flights; }); ``` #### 錯誤處理和清理 我們的抓取邏輯被包裝在一個 try-catch 區塊中,以在抓取過程中優雅地處理任何潛在的錯誤。無論結果如何,我們都會確保瀏覽器在finally區塊中正確關閉,從而保持資源效率並防止潛在的記憶體洩漏: ``` try { // Scraping logic } catch (error) { console.log({ error }); } finally { await browser.close(); console.log("Browser closed successfully."); } ``` #### 整個程式碼 ``` const SBR_WS_ENDPOINT = process.env.SBR_WS_ENDPOINT; export const register = async () => { if (process.env.NEXT_RUNTIME === "nodejs") { const { Worker } = await import("bullmq"); const puppeteer = await import("puppeteer"); const { connection } = await import("./lib/redis"); const { importQueue } = await import("./lib/queue"); new Worker( "importQueue", async (job) => { const browser = await puppeteer.connect({ browserWSEndpoint: SBR_WS_ENDPOINT, }); try { const page = await browser.newPage(); console.log("in flight scraping"); console.log("Connected! Navigating to " + job.data.url); await page.goto(job.data.url); console.log("Navigated! Scraping page content..."); const scrappedFlights = await page.evaluate(async () => { await new Promise((resolve) => setTimeout(resolve, 5000)); const flights = []; const flightSelectors = document.querySelectorAll(".nrc6-wrapper"); flightSelectors.forEach((flightElement) => { const airlineLogo = flightElement.querySelector("img")?.src || ""; const [rawDepartureTime, rawArrivalTime] = ( flightElement.querySelector(".vmXl")?.innerText || "" ).split(" – "); // Function to extract time and remove numeric values at the end const extractTime = (rawTime: string): string => { const timeWithoutNumbers = rawTime .replace(/[0-9+\s]+$/, "") .trim(); return timeWithoutNumbers; }; const departureTime = extractTime(rawDepartureTime); const arrivalTime = extractTime(rawArrivalTime); const flightDuration = ( flightElement.querySelector(".xdW8")?.children[0]?.innerText || "" ).trim(); const airlineName = ( flightElement.querySelector(".VY2U")?.children[1]?.innerText || "" ).trim(); // Extract price const price = parseInt( ( flightElement.querySelector(".f8F1-price-text")?.innerText || "" ) .replace(/[^\d]/g, "") .trim(), 10 ); flights.push({ airlineLogo, departureTime, arrivalTime, flightDuration, airlineName, price, }); }); return flights; }); } catch (error) { console.log({ error }); } finally { await browser.close(); console.log("Browser closed successfully."); } }, { connection, concurrency: 10, removeOnComplete: { count: 1000 }, removeOnFail: { count: 5000 }, } ); } }; ``` ### 步驟8:航班搜尋功能 基於我們的航班資料抓取功能,讓我們將全面的航班搜尋功能整合到我們的 Next.js 應用程式中。此功能將為使用者提供一個動態介面,透過指定出發地、目的地和日期來搜尋航班。利用強大的 Next.js 框架以及現代 UI 庫和狀態管理,我們建立了引人入勝且響應迅速的航班搜尋體驗。 #### 航班搜尋功能的關鍵組成部分 1. **動態城市選擇**:此功能包括來源和目的地輸入的自動完成功能,由預先定義的城市機場程式碼清單提供支援。當使用者輸入時,應用程式會過濾並顯示匹配的城市,透過更輕鬆地尋找和選擇機場來增強用戶體驗。 2. **日期選擇**:使用者可以透過日期輸入選擇預期的航班日期,為規劃旅行提供彈性。 3. **抓取狀態監控**:啟動抓取作業後,應用程式透過定期 API 呼叫來監控作業的狀態。這種非同步檢查允許應用程式使用抓取過程的狀態更新 UI,確保使用者了解進度和結果。 #### 航班搜尋元件的完整程式碼 ``` "use client"; import { useAppStore } from "@/store"; import { USER_API_ROUTES } from "@/utils/api-routes"; import { cityAirportCode } from "@/utils/city-airport-codes"; import { Button, Input, Listbox, ListboxItem } from "@nextui-org/react"; import axios from "axios"; import Image from "next/image"; import { useRouter } from "next/navigation"; import React, { useEffect, useRef, useState } from "react"; import { FaCalendarAlt, FaSearch } from "react-icons/fa"; const SearchFlights = () => { const router = useRouter(); const { setScraping, setScrapingType, setScrappedFlights } = useAppStore(); const [loadingJobId, setLoadingJobId] = useState<number | undefined>(undefined); const [source, setSource] = useState(""); const [sourceOptions, setSourceOptions] = useState< { city: string; code: string; }[] >([]); const [destination, setDestination] = useState(""); const [destinationOptions, setDestinationOptions] = useState< { city: string; code: string; }[] >([]); const [flightDate, setFlightDate] = useState(() => { const today = new Date(); return today.toISOString().split("T")[0]; }); const handleSourceChange = (query: string) => { const matchingCities = Object.entries(cityAirportCode) .filter(([, city]) => city.toLowerCase().includes(query.toLowerCase())) .map(([code, city]) => ({ code, city })) .splice(0, 5); setSourceOptions(matchingCities); }; const destinationChange = (query: string) => { const matchingCities = Object.entries(cityAirportCode) .filter(([, city]) => city.toLowerCase().includes(query.toLowerCase())) .map(([code, city]) => ({ code, city })) .splice(0, 5); setDestinationOptions(matchingCities); }; const startScraping = async () => { if (source && destination && flightDate) { const data = await axios.get(`${USER_API_ROUTES.FLIGHT_SCRAPE}?source=${source}&destination=${destination}&date=${flightDate}`); if (data.data.id) { setLoadingJobId(data.data.id); setScraping(true); setScrapingType("flight"); } } }; useEffect(() => { if (loadingJobId) { const checkIfJobCompleted = async () => { try { const response = await axios.get(`${USER_API_ROUTES.FLIGHT_SCRAPE_STATUS}?jobId=${loadingJobId}`); if (response.data.status) { set ScrappedFlights(response.data.flights); clearInterval(jobIntervalRef.current); setScraping(false); setScrapingType(undefined); router.push(`/flights?data=${flightDate}`); } } catch (error) { console.log(error); } }; jobIntervalRef.current = setInterval(checkIfJobCompleted, 3000); } return () => clearInterval(jobIntervalRef.current); }, [loadingJobId]); return ( <div className="h-[90vh] flex items-center justify-center"> <div className="absolute left-0 top-0 h-[100vh] w-[100vw] max-w-[100vw] overflow-hidden overflow-x-hidden"> <Image src="/flight-search.png" fill alt="Search" /> </div> <div className="absolute h-[50vh] w-[60vw] flex flex-col gap-5"> {/* UI and functionality for flight search */} </div> </div> ); }; export default SearchFlights; ``` ### 步驟9:航班搜尋頁面UI ![航班搜尋頁面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54bkhpea27fkzg4vlur1.png) ### 顯示航班搜尋結果 成功抓取飛行資料後,下一個關鍵步驟是以使用者友善的方式將這些結果呈現給使用者。 Next.js 應用程式中的 Flights 元件就是為此目的而設計的。 ``` "use client"; import { useAppStore } from "@/store"; import { USER_API_ROUTES } from "@/utils/api-routes"; import { Button } from "@nextui-org/react"; import axios from "axios"; import Image from "next/image"; import { useRouter, useSearchParams } from "next/navigation"; import React from "react"; import { FaChevronLeft } from "react-icons/fa"; import { MdOutlineFlight } from "react-icons/md"; const Flights = () => { const router = useRouter(); const searchParams = useSearchParams(); const date = searchParams.get("date"); const { scrappedFlights, userInfo } = useAppStore(); const getRandomNumber = () => Math.floor(Math.random() * 41); const bookFLight = async (flightId: number) => {}; return ( <div className="m-10 px-[20vw] min-h-[80vh]"> <Button className="my-5" variant="shadow" color="primary" size="lg" onClick={() => router.push("/search-flights")} > <FaChevronLeft /> Go Back </Button> <div className="flex-col flex gap-5"> {scrappedFlights.length === 0 && ( <div className="flex items-center justify-center py-5 px-10 mt-10 rounded-lg text-red-500 bg-red-100 font-medium"> No Flights found. </div> )} {scrappedFlights.map((flight: any) => { const seatsLeft = getRandomNumber(); return ( <div key={flight.id} className="grid grid-cols-12 border bg-gray-200 rounded-xl font-medium drop-shadow-md" > <div className="col-span-9 bg-white rounded-l-xl p-10 flex flex-col gap-5"> <div className="grid grid-cols-4 gap-4"> <div className="flex flex-col gap-3 font-medium"> <div> <div className="relative w-20 h-16"> <Image src={flight.logo} alt="airline name" fill /> </div> </div> <div>{flight.name}</div> </div> <div className="col-span-3 flex justify-between"> <div className="flex flex-col gap-2"> <div className="text-blue-600">From</div> <div> <span className="text-3xl"> <strong>{flight.departureTime}</strong> </span> </div> <div>{flight.from}</div> </div> <div className="flex flex-col items-center justify-center gap-2"> <div className="bg-violet-100 w-max p-3 text-4xl text-blue-600 rounded-full"> <MdOutlineFlight /> </div> <div> <span className="text-lg"> <strong>Non-stop</strong> </span> </div> <div>{flight.duration}</div> </div> <div className="flex flex-col gap-2"> <div className="text-blue-600">To</div> <div> <span className="text-3xl"> <strong>{flight.arrivalTime}</strong> </span> </div> <div>{flight.to}</div> </div> </div> </div> <div className="flex justify-center gap-10 bg-violet-100 p-3 rounded-lg"> <div className="flex"> <span>Airplane  </span> <span className="text-blue-600 font-semibold"> Boeing 787 </span> </div> <div className="flex"> <span>Travel Class:  </span> <span className="text-blue-600 font-semibold">Economy</span> </div> </div> <div className="flex justify-between font-medium"> <div> Refundable <span className="text-blue-600"> $5 ecash</span> </div> <div className={`${ seatsLeft > 20 ? "text-green-500" : "text-red-500" }`} > Only {seatsLeft} Seats Left </div> <div className="cursor-pointer">Flight Details</div> </div> </div> <div className="col-span-3 bg-violet-100 rounded-r-xl h-full flex flex-col items-center justify-center gap-5"> <div> <div> <span className="line-through font-light"> ${flight.price + 140} </span> </div> <div className="flex items-center gap-2"> <span className="text-5xl font-bold">${flight.price}</span> <span className="text-blue-600">20% OFF</span> </div> </div> <Button variant="ghost" radius="full" size="lg" color="primary" onClick={() => { if (userInfo) bookFLight(flight.id); }} > {userInfo ? "Book Now" : "Login to Book"} </Button> </div> </div> ); })} </div> </div> ); }; export default Flights; ``` #### 航班搜尋結果 ![航班搜尋結果](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxufusoyrf6hgtrrcmsw.png) ### 探索完整的指南和程式碼庫 上面共享的部分和程式碼片段僅代表使用 Next.js 建立強大的航班資料抓取和搜尋應用程式所需的完整功能和程式碼的一小部分。為了掌握這個專案的全部內容,包括高級功能、優化和最佳實踐,我邀請您更深入地研究我的線上綜合資源。 #### 在 YouTube 上觀看詳細說明 有關引導您完成此應用程式的開發過程、編碼細微差別和功能的逐步影片指南,請觀看我的 YouTube 影片。本教程旨在讓您更深入地了解這些概念,讓您按照自己的步調進行操作並獲得對 Next.js 應用程式開發的寶貴見解。 https://www.youtube.com/watch?v=ZWVhk0fxHM0 #### 在 GitHub 上探索完整程式碼 如果您渴望探索完整的程式碼,請造訪我的 GitHub 儲存庫。在那裡,您將找到完整的程式碼庫,包括讓該應用程式在您自己的電腦上執行所需的所有元件、實用程式和設定說明。 https://github.com/koolkishan/nextjs-travel-planner ### 結論 使用 Next.js 建立飛行資料抓取和搜尋工具等綜合應用程式展示了現代 Web 開發工具和框架的強大功能和多功能性。無論您是希望提高技能的經驗豐富的開發人員,還是渴望深入 Web 開發的初學者,這些資源都是為您的旅程量身定制的。在 YouTube 上觀看詳細教程,在 GitHub 上探索完整程式碼,並加入對話以增強您的開發專業知識並為充滿活力的開發者社群做出貢獻。 --- 原文出處:https://dev.to/kishansheth/nextjs-14-booking-app-with-live-data-scraping-using-scraping-browser-610

Rust 中的 Laravel?我這樣做是有原因的。

大家都怎麼啦! 過去幾個月我一直在研究 Rust,並且總是試圖接近 Laravel 環境中的實際堆疊。 對於我來說,作為一名 PHP 開發人員,跳入 Rust 確實是一項艱鉅的任務,因為我以前從未接觸過函數式編程,但是我找到了一種方法讓這變得「更容易」。 銹據我所知 ----- 整個生態系統由不同的套件組成,您應該根據需要加入它,這與 Laravel 不同,Laravel 圍繞框架有一個非常強大的環境。 所以我的第一印像是我必須學習如何使用基礎包: - 多滕維 - 時空 - 時間 - Uuid - 等等。 但是當涉及到 Web 開發(主要是 API)時,您必須從眾多現有框架中選擇一個。喜歡: - Actix(目前使用) - 阿克蘇姆(評估中) - Rocket(人們總是告訴我不要使用它,仍然不知道為什麼) 而且它們都沒有 Laravel 那種固執己見的“結構”,所以我決定建立我的。 Rust 中的 Laravel --------------- 我為什麼要談 Laravel?因為它為我們提供的“MVC”結構對於使用 Rust Web 的小型專案來說足夠優雅。 當我使用固定的 Laravel 框架編寫 Rust 程式碼時,事情開始變得有意義。這是我正在談論的內容的結構: ``` ./src ├── app.rs ├── config.rs ├── http │   ├── controllers │   │   ├── leaderboard_controller.rs │   │   ├── mod.rs │   │   └── submissions_controller.rs │   ├── mod.rs │   └── requests │   ├── leaderboard_request.rs │   ├── mod.rs │   └── submission_request.rs ├── main.rs ├── models │   ├── leaderboard.rs │   ├── mod.rs │   └── submission.rs └── repositories ├── leaderboard_repository.rs ├── mod.rs └── submission_repository.rs ``` 該專案目前正在使用中: - [阿克泰克斯](https://actix.rs/docs/) - [卡律布狄斯 ORM](https://github.com/nodecosmos/charybdis) 你可以在這個[Pull Request](https://github.com/DanielHe4rt/leaderboard-rust/pull/1)中檢查我的混亂情況 問題是:在使用 Rust 時遵循這個想法會是一件好事嗎?簡單性和良好的維護結構是我在專案中一直追求的目標。 另外,我正在考慮寫一些關於我的流程如何從 PHP 遷移到 Rust 的系列文章,您有興趣閱讀類似的內容嗎? 希望在這裡看到您的想法,謝謝! --- 原文出處:https://dev.to/danielhe4rt/laravel-inside-rust-i-have-a-reason-for-that-ke3

為初學者到專家提供的 101 個 Bash 指令和提示

> **2019 年 9 月 25 日更新:**感謝[ラナ・kuaru](https://twitter.com/rana_kualu)的辛勤工作,本文現已提供日文版。請點擊下面的連結查看他們的工作。如果您知道本文被翻譯成其他語言,請告訴我,我會將其發佈在這裡。 [🇯🇵 閱讀日語](https://qiita.com/rana_kualu/items/7b62898d373901466f5c) > **2019 年 7 月 8 日更新:**我最近發現大約兩年前發佈在法語留言板上的[這篇非常相似的文章](https://bookmarks.ecyseo.net/?EAWvDw)。如果您有興趣學習一些 shell 命令——並且您*會說 français* ,那麼它是對我下面的文章的一個很好的補充。 直到大約一年前,我幾乎只在 macOS 和 Ubuntu 作業系統中工作。在這兩個作業系統上, `bash`是我的預設 shell。在過去的六、七年裡,我對`bash`工作原理有了大致的了解,並想為那些剛入門的人概述一些更常見/有用的命令。如果您認為您了解有關`bash`所有訊息,請無論如何看看下面的內容 - 我已經提供了一些提示和您可能忘記的標誌的提醒,這可以讓您的工作更輕鬆一些。 下面的命令或多或少以敘述風格排列,因此如果您剛開始使用`bash` ,您可以從頭到尾完成操作。事情到最後通常會變得不那麼常見並且變得更加困難。 <a name="toc"></a> 目錄 -- - [基礎](#the-basics) ``` - [First Commands, Navigating the Filesystem](#first-commands) ``` ``` - [`pwd / ls / cd`](#pwd-ls-cd) ``` ``` - [`; / && / &`](#semicolon-andand-and) ``` ``` - [Getting Help](#getting-help) ``` ``` - [`-h`](#minus-h) ``` ``` - [`man`](#man) ``` ``` - [Viewing and Editing Files](#viewing-and-editing-files) ``` ``` - [`head / tail / cat / less`](#head-tail-cat-less) ``` ``` - [`nano / nedit`](#nano-nedit) ``` ``` - [Creating and Deleting Files and Directories](#creating-and-deleting-files) ``` ``` - [`touch`](#touch) ``` ``` - [`mkdir / rm / rmdir`](#mkdir-rm-rmdir) ``` ``` - [Moving and Copying Files, Making Links, Command History](#moving-and-copying-files) ``` ``` - [`mv / cp / ln`](#mv-cp-ln) ``` ``` - [Command History](#command-history) ``` ``` - [Directory Trees, Disk Usage, and Processes](#directory-trees-disk-usage-processes) ``` ``` - [`mkdir –p / tree`](#mkdir--p-tree) ``` ``` - [`df / du / ps`](#df-du-ps) ``` ``` - [Miscellaneous](#basic-misc) ``` ``` - [`passwd / logout / exit`](#passwd-logout-exit) ``` ``` - [`clear / *`](#clear-glob) ``` - [中間的](#intermediate) ``` - [Disk, Memory, and Processor Usage](#disk-memory-processor) ``` ``` - [`ncdu`](#ncdu) ``` ``` - [`top / htop`](#top-htop) ``` ``` - [REPLs and Software Versions](#REPLs-software-versions) ``` ``` - [REPLs](#REPLs) ``` ``` - [`-version / --version / -v`](#version) ``` ``` - [Environment Variables and Aliases](#env-vars-aliases) ``` ``` - [Environment Variables](#env-vars) ``` ``` - [Aliases](#aliases) ``` ``` - [Basic `bash` Scripting](#basic-bash-scripting) ``` ``` - [`bash` Scripts](#bash-scripts) ``` ``` - [Custom Prompt and `ls`](#custom-prompt-ls) ``` ``` - [Config Files](#config-files) ``` ``` - [Config Files / `.bashrc`](#config-bashrc) ``` ``` - [Types of Shells](#types-of-shells) ``` ``` - [Finding Things](#finding-things) ``` ``` - [`whereis / which / whatis`](#whereis-which-whatis) ``` ``` - [`locate / find`](#locate-find) ``` ``` - [Downloading Things](#downloading-things) ``` ``` - [`ping / wget / curl`](#ping-wget-curl) ``` ``` - [`apt / gunzip / tar / gzip`](#apt-gunzip-tar-gzip) ``` ``` - [Redirecting Input and Output](#redirecting-io) ``` ``` - [`| / > / < / echo / printf`](#pipe-gt-lt-echo-printf) ``` ``` - [`0 / 1 / 2 / tee`](#std-tee) ``` - [先進的](#advanced) ``` - [Superuser](#superuser) ``` ``` - [`sudo / su`](#sudo-su) ``` ``` - [`!!`](#click-click) ``` ``` - [File Permissions](#file-permissions) ``` ``` - [File Permissions](#file-permissions-sub) ``` ``` - [`chmod / chown`](#chmod-chown) ``` ``` - [User and Group Management](#users-groups) ``` ``` - [Users](#users) ``` ``` - [Groups](#groups) ``` ``` - [Text Processing](#text-processing) ``` ``` - [`uniq / sort / diff / cmp`](#uniq-sort-diff-cmp) ``` ``` - [`cut / sed`](#cut-sed) ``` ``` - [Pattern Matching](#pattern-matching) ``` ``` - [`grep`](#grep) ``` ``` - [`awk`](#awk) ``` ``` - [Copying Files Over `ssh`](#ssh) ``` ``` - [`ssh / scp`](#ssh-scp) ``` ``` - [`rsync`](#rsync) ``` ``` - [Long-Running Processes](#long-running-processes) ``` ``` - [`yes / nohup / ps / kill`](#yes-nohup-ps-kill) ``` ``` - [`cron / crontab / >>`](#cron) ``` ``` - [Miscellaneous](#advanced-misc) ``` ``` - [`pushd / popd`](#pushd-popd) ``` ``` - [`xdg-open`](#xdg-open) ``` ``` - [`xargs`](#xargs) ``` - [獎勵:有趣但大多無用的東西](#bonus) ``` - [`w / write / wall / lynx`](#w-write-wall-lynx) ``` ``` - [`nautilus / date / cal / bc`](#nautilus-date-cal-bc) ``` --- <a name="the-basics"></a> 基礎 == <a name="first-commands"></a> 第一個指令,瀏覽檔案系統 ------------ 現代檔案系統具有目錄(資料夾)樹,其中目錄要么是*根目錄*(沒有父目錄),要么是*子目錄*(包含在單一其他目錄中,我們稱之為“父目錄”)。向後遍歷檔案樹(從子目錄到父目錄)將始終到達根目錄。有些檔案系統有多個根目錄(如 Windows 的磁碟機: `C:\` 、 `A:\`等),但 Unix 和類別 Unix 系統只有一個名為`\`的根目錄。 <a name="pwd-ls-cd"></a> ### `pwd / ls / cd` [\[ 返回目錄 \]](#toc) 在檔案系統中工作時,使用者始終*在*某個目錄中工作,我們稱之為當前目錄或*工作目錄*。使用`pwd`列印使用者的工作目錄: ``` [ andrew@pc01 ~ ]$ pwd /home/andrew ``` 使用`ls`列出該目錄的內容(檔案和/或子目錄等): ``` [ andrew@pc01 ~ ]$ ls Git TEST jdoc test test.file ``` > **獎金:** > > 使用`ls -a`顯示隱藏(“點”)文件 > > 使用`ls -l`顯示文件詳細訊息 > > 組合多個標誌,如`ls -l -a` > > 有時您可以連結諸如`ls -la`之類的標誌,而不是`ls -l -a` 使用`cd`更改到不同的目錄(更改目錄): ``` [ andrew@pc01 ~ ]$ cd TEST/ [ andrew@pc01 TEST ]$ pwd /home/andrew/TEST [ andrew@pc01 TEST ]$ cd A [ andrew@pc01 A ]$ pwd /home/andrew/TEST/A ``` `cd ..`是「 `cd`到父目錄」的簡寫: ``` [ andrew@pc01 A ]$ cd .. [ andrew@pc01 TEST ]$ pwd /home/andrew/TEST ``` `cd ~`或只是`cd`是「 `cd`到我的主目錄」的簡寫(通常`/home/username`或類似的東西): ``` [ andrew@pc01 TEST ]$ cd [ andrew@pc01 ~ ]$ pwd /home/andrew ``` > **獎金:** > > `cd ~user`表示「 `cd`到`user`的主目錄 > > 您可以使用`cd ../..`等跳轉多個目錄等級。 > > 使用`cd -`返回到最近的目錄 > > `.`是「此目錄」的簡寫,因此`cd .`不會做太多事情 <a name="semicolon-andand-and"></a> ### `; / && / &` [\[ 返回目錄 \]](#toc) 我們在命令列中輸入的內容稱為*命令*,它們總是執行儲存在電腦上某處的一些機器碼。有時這個機器碼是一個內建的Linux命令,有時它是一個應用程式,有時它是你自己寫的一些程式碼。有時,我們會想依序執行一個指令。為此,我們可以使用`;` (分號): ``` [ andrew@pc01 ~ ]$ ls; pwd Git TEST jdoc test test.file /home/andrew ``` 上面的分號表示我首先 ( `ls` ) 列出工作目錄的內容,然後 ( `pwd` ) 列印其位置。連結命令的另一個有用工具是`&&` 。使用`&&`時,如果左側命令失敗,則右側命令將不會執行。 `;`和`&&`都可以在同一行中多次使用: ``` # whoops! I made a typo here! [ andrew@pc01 ~ ]$ cd /Giit/Parser && pwd && ls && cd -bash: cd: /Giit/Parser: No such file or directory # the first command passes now, so the following commands are run [ andrew@pc01 ~ ]$ cd Git/Parser/ && pwd && ls && cd /home/andrew/Git/Parser README.md doc.sh pom.xml resource run.sh shell.sh source src target ``` ....但是與`;` ,即使第一個命令失敗,第二個命令也會執行: ``` # pwd and ls still run, even though the cd command failed [ andrew@pc01 ~ ]$ cd /Giit/Parser ; pwd ; ls -bash: cd: /Giit/Parser: No such file or directory /home/andrew Git TEST jdoc test test.file ``` `&`看起來與`&&`類似,但實際上實現了完全不同的功能。通常,當您執行長時間執行的命令時,命令列將等待該命令完成,然後才允許您輸入另一個命令。在命令後面加上`&`可以防止這種情況發生,並允許您在舊命令仍在執行時執行新命令: ``` [ andrew@pc01 ~ ]$ cd Git/Parser && mvn package & cd [1] 9263 ``` > **額外的好處:**當我們在命令後使用`&`來「隱藏」它時,我們說該作業(或「進程」;這些術語或多或少可以互換)是「後台的」。若要查看目前正在執行的背景作業,請使用`jobs`指令: > ````bash \[ andrew@pc01 ~ \]$ 職位 \[1\]+ 執行 cd Git/Parser/ && mvn package & ``` <a name="getting-help"></a> ## Getting Help <a name="minus-h"></a> ### `-h` [[ Back to Table of Contents ]](#toc) Type `-h` or `--help` after almost any command to bring up a help menu for that command: ``` \[ andrew@pc01 ~ \]$ du --help 用法:你\[選項\]...\[檔案\]... 或: du \[選項\]... --files0-from=F 對目錄遞歸地總結文件集的磁碟使用情況。 長期權的強制性參數對於短期權也是強制性的。 -0, --null 以 NUL 結束每個輸出行,而不是換行符 -a, --all 計算所有檔案的寫入計數,而不僅僅是目錄 ``` --apparent-size print apparent sizes, rather than disk usage; although ``` ``` the apparent size is usually smaller, it may be ``` ``` larger due to holes in ('sparse') files, internal ``` ``` fragmentation, indirect blocks, and the like ``` -B, --block-size=SIZE 在列印前按 SIZE 縮放大小;例如, ``` '-BM' prints sizes in units of 1,048,576 bytes; ``` ``` see SIZE format below ``` … ``` <a name="man"></a> ### `man` [[ Back to Table of Contents ]](#toc) Type `man` before almost any command to bring up a manual for that command (quit `man` with `q`): ``` LS(1) 使用者指令 LS(1) 姓名 ``` ls - list directory contents ``` 概要 ``` ls [OPTION]... [FILE]... ``` 描述 ``` List information about the FILEs (the current directory by default). ``` ``` Sort entries alphabetically if none of -cftuvSUX nor --sort is speci- ``` ``` fied. ``` ``` Mandatory arguments to long options are mandatory for short options ``` ``` too. ``` … ``` <a name="viewing-and-editing-files"></a> ## Viewing and Editing Files <a name="head-tail-cat-less"></a> ### `head / tail / cat / less` [[ Back to Table of Contents ]](#toc) `head` outputs the first few lines of a file. The `-n` flag specifies the number of lines to show (the default is 10): ``` 列印前三行 ===== \[ andrew@pc01 ~ \]$ 頭 -n 3 c 這 文件 有 ``` `tail` outputs the last few lines of a file. You can get the last `n` lines (like above), or you can get the end of the file beginning from the `N`-th line with `tail -n +N`: ``` 從第 4 行開始列印文件末尾 ============== \[ andrew@pc01 ~ \]$ tail -n +4 c 確切地 六 線 ``` `cat` concatenates a list of files and sends them to the standard output stream (usually the terminal). `cat` can be used with just a single file, or multiple files, and is often used to quickly view them. (**Be warned**: if you use `cat` in this way, you may be accused of a [_Useless Use of Cat_ (UUOC)](http://bit.ly/2SPHE4V), but it's not that big of a deal, so don't worry too much about it.) ``` \[ andrew@pc01 ~ \]$ 貓 a 歸檔一個 \[ andrew@pc01 ~ \]$ 貓 ab 歸檔一個 文件b ``` `less` is another tool for quickly viewing a file -- it opens up a `vim`-like read-only window. (Yes, there is a command called `more`, but `less` -- unintuitively -- offers a superset of the functionality of `more` and is recommended over it.) Learn more (or less?) about [less](http://man7.org/linux/man-pages/man1/less.1.html) and [more](http://man7.org/linux/man-pages/man1/more.1.html) at their `man` pages. <a name="nano-nedit"></a> ### `nano / nedit` [[ Back to Table of Contents ]](#toc) `nano` is a minimalistic command-line text editor. It's a great editor for beginners or people who don't want to learn a million shortcuts. It was more than sufficient for me for the first few years of my coding career (I'm only now starting to look into more powerful editors, mainly because defining your own syntax highlighting in `nano` can be a bit of a pain.) `nedit` is a small graphical editor, it opens up an X Window and allows point-and-click editing, drag-and-drop, syntax highlighting and more. I use `nedit` sometimes when I want to make small changes to a script and re-run it over and over. Other common CLI (command-line interface) / GUI (graphical user interface) editors include `emacs`, `vi`, `vim`, `gedit`, Notepad++, Atom, and lots more. Some cool ones that I've played around with (and can endorse) include Micro, Light Table, and VS Code. All modern editors offer basic conveniences like search and replace, syntax highlighting, and so on. `vi(m)` and `emacs` have more features than `nano` and `nedit`, but they have a much steeper learning curve. Try a few different editors out and find one that works for you! <a name="creating-and-deleting-files"></a> ## Creating and Deleting Files and Directories <a name="touch"></a> ### `touch` [[ Back to Table of Contents ]](#toc) `touch` was created to modify file timestamps, but it can also be used to quickly create an empty file. You can create a new file by opening it with a text editor, like `nano`: ``` \[ andrew@pc01 前 \]$ ls \[ andrew@pc01 ex \]$ 奈米 a ``` _...editing file..._ ``` \[ andrew@pc01 前 \]$ ls A ``` ...or by simply using `touch`: ``` \[ andrew@pc01 ex \]$ touch b && ls ab ``` > **Bonus**: > > Background a process with \^z (Ctrl+z) > > ```bash > [ andrew@pc01 ex ]$ nano a > ``` > > _...editing file, then hit \^z..._ > > ```bash > Use fg to return to nano > > [1]+ Stopped nano a > [ andrew@pc01 ex ]$ fg > ``` > > _...editing file again..._ --- > **Double Bonus:** > > Kill the current (foreground) process by pressing \^c (Ctrl+c) while it’s running > > Kill a background process with `kill %N` where `N` is the job index shown by the `jobs` command <a name="mkdir-rm-rmdir"></a> ### `mkdir / rm / rmdir` [[ Back to Table of Contents ]](#toc) `mkdir` is used to create new, empty directories: ``` \[ andrew@pc01 ex \]$ ls && mkdir c && ls ab ABC ``` You can remove any file with `rm` -- but be careful, this is non-recoverable! ``` \[ andrew@pc01 ex \]$ rm a && ls 西元前 ``` You can add an _"are you sure?"_ prompt with the `-i` flag: ``` \[ andrew@pc01 前 \]$ rm -ib rm:刪除常規空文件“b”? y ``` Remove an empty directory with `rmdir`. If you `ls -a` in an empty directory, you should only see a reference to the directory itself (`.`) and a reference to its parent directory (`..`): ``` \[ andrew@pc01 ex \]$ rmdir c && ls -a 。 .. ``` `rmdir` removes empty directories only: ``` \[ andrew@pc01 ex \]$ cd .. && ls 測試/ \*.txt 0.txt 1.txt a a.txt bc \[ andrew@pc01 ~ \]$ rmdir 測試/ rmdir:無法刪除“test/”:目錄不為空 ``` ...but you can remove a directory -- and all of its contents -- with `rm -rf` (`-r` = recursive, `-f` = force): ``` \[ andrew@pc01 ~ \]$ rm –rf 測試 ``` <a name="moving-and-copying-files"></a> ## Moving and Copying Files, Making Links, Command History <a name="mv-cp-ln"></a> ### `mv / cp / ln` [[ Back to Table of Contents ]](#toc) `mv` moves / renames a file. You can `mv` a file to a new directory and keep the same file name or `mv` a file to a "new file" (rename it): ``` \[ andrew@pc01 ex \]$ ls && mv ae && ls A B C D BCDE ``` `cp` copies a file: ``` \[ andrew@pc01 ex \]$ cp e e2 && ls BCDE E2 ``` `ln` creates a hard link to a file: ``` ln 的第一個參數是 TARGET,第二個參數是 NEW LINK ================================= \[ andrew@pc01 ex \]$ ln bf && ls bcde e2 f ``` `ln -s` creates a soft link to a file: ``` \[ andrew@pc01 ex \]$ ln -sbg && ls BCDE E2 FG ``` Hard links reference the same actual bytes in memory which contain a file, while soft links refer to the original file name, which itself points to those bytes. [You can read more about soft vs. hard links here.](http://bit.ly/2D0W8cN) <a name="command-history"></a> ### Command History [[ Back to Table of Contents ]](#toc) `bash` has two big features to help you complete and re-run commands, the first is _tab completion_. Simply type the first part of a command, hit the \<tab\> key, and let the terminal guess what you're trying to do: ``` \[ andrew@pc01 目錄 \]$ ls 另一個長檔名 這是一個長檔名 一個新檔名 \[ andrew@pc01 目錄 \]$ ls t ``` _...hit the TAB key after typing `ls t` and the command is completed..._ ``` \[ andrew@pc01 dir \]$ ls 這是檔名 這是長檔名 ``` You may have to hit \<TAB\> multiple times if there's an ambiguity: ``` \[ andrew@pc01 目錄 \]$ ls a \[ andrew@pc01 目錄 \]$ ls an 一個新檔名另一個長檔名 ``` `bash` keeps a short history of the commands you've typed previously and lets you search through those commands by typing \^r (Ctrl+r): ``` \[ andrew@pc01 目錄 \] ``` _...hit \^r (Ctrl+r) to search the command history..._ ``` (反向搜尋)``: ``` _...type 'anew' and the last command containing this is found..._ ``` (reverse-i-search)`anew': 觸碰新檔名 ``` <a name="directory-trees-disk-usage-processes"></a> ## Directory Trees, Disk Usage, and Processes <a name="mkdir--p-tree"></a> ### `mkdir –p / tree` [[ Back to Table of Contents ]](#toc) `mkdir`, by default, only makes a single directory. This means that if, for instance, directory `d/e` doesn't exist, then `d/e/f` can't be made with `mkdir` by itself: ``` \[ andrew@pc01 ex \]$ ls && mkdir d/e/f ABC mkdir:無法建立目錄「d/e/f」:沒有這樣的檔案或目錄 ``` But if we pass the `-p` flag to `mkdir`, it will make all directories in the path if they don't already exist: ``` \[ andrew@pc01 ex \]$ mkdir -pd/e/f && ls A B C D ``` `tree` can help you better visualise a directory's structure by printing a nicely-formatted directory tree. By default, it prints the entire tree structure (beginning with the specified directory), but you can restrict it to a certain number of levels with the `-L` flag: ``` \[ andrew@pc01 前 \]$ 樹 -L 2 。 |-- 一個 |-- b |-- c `--d ``` `--e ``` 3個目錄,2個文件 ``` You can hide empty directories in `tree`'s output with `--prune`. Note that this also removes "recursively empty" directories, or directories which aren't empty _per se_, but which contain only other empty directories, or other recursively empty directories: ``` \[ andrew@pc01 ex \]$ 樹 --prune 。 |-- 一個 `--b ``` <a name="df-du-ps"></a> ### `df / du / ps` [[ Back to Table of Contents ]](#toc) `df` is used to show how much space is taken up by files for the disks or your system (hard drives, etc.). ``` \[ andrew@pc01 前 \]$ df -h 已使用的檔案系統大小 可用 使用% 安裝於 udev 126G 0 126G 0% /dev tmpfs 26G 2.0G 24G 8% /執行 /dev/mapper/ubuntu--vg-root 1.6T 1.3T 252G 84% / … ``` In the above command, `-h` doesn't mean "help", but "human-readable". Some commands use this convention to display file / disk sizes with `K` for kilobytes, `G` for gigabytes, and so on, instead of writing out a gigantic integer number of bytes. `du` shows file space usage for a particular directory and its subdirectories. If you want to know how much space is free on a given hard drive, use `df`; if you want to know how much space a directory is taking up, use `du`: ``` \[ andrew@pc01 ex \]$ 你 4 ./d/e/f 8./d/e 12 ./天 4./c 20 . ``` `du` takes a `--max-depth=N` flag, which only shows directories `N` levels down (or fewer) from the specified directory: ``` \[ andrew@pc01 ex \]$ du -h --max-深度=1 12K./天 4.0K./c 20K。 ``` `ps` shows all of the user's currently-running processes (aka. jobs): ``` \[ andrew@pc01 前 \]$ ps PID TTY 時間 CMD 16642 分/15 00:00:00 ps 25409 點/15 00:00:00 重擊 ``` <a name="basic-misc"></a> ## Miscellaneous <a name="passwd-logout-exit"></a> ### `passwd / logout / exit` [[ Back to Table of Contents ]](#toc) Change your account password with `passwd`. It will ask for your current password for verification, then ask you to enter the new password twice, so you don't make any typos: ``` \[ andrew@pc01 目錄 \]$ 密碼 更改安德魯的密碼。 (目前)UNIX 密碼: 輸入新的 UNIX 密碼: 重新輸入新的 UNIX 密碼: passwd:密碼更新成功 ``` `logout` exits a shell you’ve logged in to (where you have a user account): ``` \[ andrew@pc01 目錄 \]$ 註銷 ────────────────────────────────────────────────── ── ────────────────────────────── 會話已停止 ``` - Press <return> to exit tab ``` ``` - Press R to restart session ``` ``` - Press S to save terminal output to file ``` ``` `exit` exits any kind of shell: ``` \[ andrew@pc01 ~ \]$ 退出 登出 ────────────────────────────────────────────────── ── ────────────────────────────── 會話已停止 ``` - Press <return> to exit tab ``` ``` - Press R to restart session ``` ``` - Press S to save terminal output to file ``` ``` <a name="clear-glob"></a> ### `clear / *` [[ Back to Table of Contents ]](#toc) Run `clear` to move the current terminal line to the top of the screen. This command just adds blank lines below the current prompt line. It's good for clearing your workspace. Use the glob (`*`, aka. Kleene Star, aka. wildcard) when looking for files. Notice the difference between the following two commands: ``` \[ andrew@pc01 ~ \]$ ls Git/Parser/source/ PArrayUtils.java PFile.java PSQLFile.java PWatchman.java PDateTimeUtils.java PFixedWidthFile.java PStringUtils.java PXSVFile.java PDelimitedFile.java PNode.java PTextFile.java Parser.java \[ andrew@pc01 ~ \]$ ls Git/Parser/source/PD\* Git/Parser/source/PDateTimeUtils.java Git/Parser/source/PDelimitedFile.java ``` The glob can be used multiple times in a command and matches zero or more characers: ``` \[ andrew@pc01 ~ \]$ ls Git/Parser/source/P *D* m\* Git/Parser/source/PDateTimeUtils.java Git/Parser/source/PDelimitedFile.java ``` <a name="intermediate"></a> # Intermediate <a name="disk-memory-processor"></a> ## Disk, Memory, and Processor Usage <a name="ncdu"></a> ### `ncdu` [[ Back to Table of Contents ]](#toc) `ncdu` (NCurses Disk Usage) provides a navigable overview of file space usage, like an improved `du`. It opens a read-only `vim`-like window (press `q` to quit): ``` \[ andrew@pc01 ~ \]$ ncdu ncdu 1.11 ~ 使用箭頭鍵導航,按 ?求助 \--- /home/安德魯 ------------------------------------------- ------------------ 148.2 MiB \[##########\] /.m2 91.5 MiB \[######\] /.sbt 79.8 MiB \[######\] /.cache 64.9 MiB \[####\] /.ivy2 40.6 MiB \[##\] /.sdkman 30.2 MiB \[##\] /.local 27.4 MiB \[#\] /.mozilla 24.4 MiB \[#\] /.nanobackups 10.2 MiB \[ \] .confout3.txt ``` 8.4 MiB [ ] /.config ``` ``` 5.9 MiB [ ] /.nbi ``` ``` 5.8 MiB [ ] /.oh-my-zsh ``` ``` 4.3 MiB [ ] /Git ``` ``` 3.7 MiB [ ] /.myshell ``` ``` 1.7 MiB [ ] /jdoc ``` ``` 1.5 MiB [ ] .confout2.txt ``` ``` 1.5 MiB [ ] /.netbeans ``` ``` 1.1 MiB [ ] /.jenv ``` 564.0 KiB \[ \] /.rstudio-desktop 磁碟使用總量:552.7 MiB 表觀大小:523.6 MiB 專案:14618 ``` <a name="top-htop"></a> ### `top / htop` [[ Back to Table of Contents ]](#toc) `top` displays all currently-running processes and their owners, memory usage, and more. `htop` is an improved, interactive `top`. (Note: you can pass the `-u username` flag to restrict the displayed processes to only those owner by `username`.) ``` \[ andrew@pc01 ~ \]$ htop 1 \[ 0.0%\] 9 \[ 0.0%\] 17 \[ 0.0%\] 25 \[ 0.0%\] 2 \[ 0.0%\] 10 \[ 0.0%\] 18 \[ 0.0%\] 26 \[ 0.0%\] 3 \[ 0.0%\] 11 \[ 0.0%\] 19 \[ 0.0%\] 27 \[ 0.0%\] 4 \[ 0.0%\] 12 \[ 0.0%\] 20 \[ 0.0%\] 28 \[ 0.0%\] 5 \[ 0.0%\] 13 \[ 0.0%\] 21 \[| 1.3%\] 29 \[ 0.0%\] 6 \[ 0.0%\] 14 \[ 0.0%\] 22 \[ 0.0%\] 30 \[| 0.6%\] 7 \[ 0.0%\] 15 \[ 0.0%\] 23 \[ 0.0%\] 31 \[ 0.0%\] 8 \[ 0.0%\] 16 \[ 0.0%\] 24 \[ 0.0%\] 32 \[ 0.0%\] Mem\[|||||||||||||||||||1.42G/252G\] 任務:188、366 個; 1 執行 交換電壓\[| 2.47G/256G\]平均負載:0.00 0.00 0.00 ``` Uptime: 432 days(!), 00:03:55 ``` PID USER PRI NI VIRT RES SHR S CPU% MEM% TIME+ 指令 9389 安德魯 20 0 23344 3848 2848 R 1.3 0.0 0:00.10 htop 10103 根 20 0 3216M 17896 2444 S 0.7 0.0 5h48:56 /usr/bin/dockerd ``` 1 root 20 0 181M 4604 2972 S 0.0 0.0 15:29.66 /lib/systemd/syst ``` 533 根 20 0 44676 6908 6716 S 0.0 0.0 11:19.77 /lib/systemd/syst 546 根 20 0 244M 0 0 S 0.0 0.0 0:01.39 /sbin/lvmetad -f 1526 根 20 0 329M 2252 1916 S 0.0 0.0 0:00.00 /usr/sbin/ModemMa 1544 根 20 0 329M 2252 1916 S 0.0 0.0 0:00.06 /usr/sbin/ModemMa F1Help F2Setup F3SearchF4FilterF5Tree F6SortByF7Nice -F8Nice +F9Kill F10Quit ``` <a name="REPLs-software-versions"></a> ## REPLs and Software Versions <a name="REPLs"></a> ### REPLs [[ Back to Table of Contents ]](#toc) A **REPL** is a Read-Evaluate-Print Loop, similar to the command line, but usually used for particular programming languages. You can open the Python REPL with the `python` command (and quit with the `quit()` function): ``` \[ andrew@pc01 ~ \]$ python Python 3.5.2(默認,2018 年 11 月 12 日,13:43:14)... > > > 辭職() ``` Open the R REPL with the `R` command (and quit with the `q()` function): ``` \[ andrew@pc01 ~ \]$ R R版3.5.2(2018-12-20)--「蛋殼冰屋」... > q() 儲存工作區影像? \[是/否/c\]: 否 ``` Open the Scala REPL with the `scala` command (and quit with the `:quit` command): ``` \[ andrew@pc01 ~ \]$ scala 歡迎使用 Scala 2.11.12 ... 斯卡拉>:退出 ``` Open the Java REPL with the `jshell` command (and quit with the `/exit` command): ``` \[ andrew@pc01 ~ \]$ jshell |歡迎使用 JShell——版本 11.0.1 ... jshell> /退出 ``` Alternatively, you can exit any of these REPLs with \^d (Ctrl+d). \^d is the EOF (end of file) marker on Unix and signifies the end of input. <a name="version"></a> ### `-version / --version / -v` [[ Back to Table of Contents ]](#toc) Most commands and programs have a `-version` or `--version` flag which gives the software version of that command or program. Most applications make this information easily available: ``` \[ andrew@pc01 ~ \]$ ls --version ls (GNU coreutils) 8.25 ... \[ andrew@pc01 ~ \]$ ncdu -版本 NCDU 1.11 \[ andrew@pc01 ~ \]$ python --version Python 3.5.2 ``` ...but some are less intuitive: ``` \[ andrew@pc01 ~ \]$ sbt scalaVersion … \[資訊\]2.12.4 ``` Note that some programs use `-v` as a version flag, while others use `-v` to mean "verbose", which will run the application while printing lots of diagnostic or debugging information: ``` SCP(1) BSD 通用指令手冊 SCP(1) 姓名 ``` scp -- secure copy (remote file copy program) ``` … -v 詳細模式。導致 scp 和 ssh(1) 列印偵錯訊息 ``` about their progress. This is helpful in debugging connection, ``` ``` authentication, and configuration problems. ``` … ``` <a name="env-vars-aliases"></a> ## Environment Variables and Aliases <a name="env-vars"></a> ### Environment Variables [[ Back to Table of Contents ]](#toc) **Environment variables** (sometimes shortened to "env vars") are persistent variables that can be created and used within your `bash` shell. They are defined with an equals sign (`=`) and used with a dollar sign (`$`). You can see all currently-defined env vars with `printenv`: ``` \[ andrew@pc01 ~ \]$ printenv SPARK\_HOME=/usr/local/spark 術語=xterm … ``` Set a new environment variable with an `=` sign (don't put any spaces before or after the `=`, though!): ``` \[ andrew@pc01 ~ \]$ myvar=你好 ``` Print a specific env var to the terminal with `echo` and a preceding `$` sign: ``` \[ andrew@pc01 ~ \]$ echo $myvar 你好 ``` Environment variables which contain spaces or other whitespace should be surrounded by quotes (`"..."`). Note that reassigning a value to an env var overwrites it without warning: ``` \[ andrew@pc01 ~ \]$ myvar="你好,世界!" && 回顯 $myvar 你好世界! ``` Env vars can also be defined using the `export` command. When defined this way, they will also be available to sub-processes (commands called from this shell): ``` \[ andrew@pc01 ~ \]$ export myvar="另一" && echo $myvar 另一個 ``` You can unset an environment variable by leaving the right-hand side of the `=` blank or by using the `unset` command: ``` \[ andrew@pc01 ~ \]$ 取消設定 mynewvar \[ andrew@pc01 ~ \]$ echo $mynewvar ``` <a name="aliases"></a> ### Aliases [[ Back to Table of Contents ]](#toc) **Aliases** are similar to environment variables but are usually used in a different way -- to replace long commands with shorter ones: ``` \[ andrew@pc01 apidocs \]$ ls -l -a -h -t 總計 220K drwxr-xr-x 5 安德魯 安德魯 4.0K 12 月 21 日 12:37 。 -rw-r--r-- 1 安德魯 安德魯 9.9K 十二月 21 12:37 help-doc.html -rw-r--r-- 1 安德魯 安德魯 4.5K 12 月 21 日 12:37 script.js … \[ andrew@pc01 apidocs \]$ 別名 lc="ls -l -a -h -t" \[ andrew@pc01 apidocs \]$ lc 總計 220K drwxr-xr-x 5 安德魯 安德魯 4.0K 12 月 21 日 12:37 。 -rw-r--r-- 1 安德魯 安德魯 9.9K 十二月 21 12:37 help-doc.html -rw-r--r-- 1 安德魯 安德魯 4.5K 12 月 21 日 12:37 script.js … ``` You can remove an alias with `unalias`: ``` \[ andrew@pc01 apidocs \]$ unalias lc \[ andrew@pc01 apidocs \]$ lc 目前未安裝程式“lc”。 … ``` > **Bonus:** > > [Read about the subtle differences between environment variables and aliases here.](http://bit.ly/2TDG8Tx) > > [Some programs, like **git**, allow you to define aliases specifically for that software.](http://bit.ly/2TG8X1A) <a name="basic-bash-scripting"></a> ## Basic `bash` Scripting <a name="bash-scripts"></a> ### `bash` Scripts [[ Back to Table of Contents ]](#toc) `bash` scripts (usually ending in `.sh`) allow you to automate complicated processes, packaging them into reusable functions. A `bash` script can contain any number of normal shell commands: ``` \[ andrew@pc01 ~ \]$ echo "ls && touch file && ls" > ex.sh ``` A shell script can be executed with the `source` command or the `sh` command: ``` \[ andrew@pc01 ~ \]$ 源 ex.sh 桌面 Git TEST c ex.sh 專案測試 桌面 Git TEST c ex.sh 檔案專案測試 ``` Shell scripts can be made executable with the `chmod` command (more on this later): ``` \[ andrew@pc01 ~ \]$ echo "ls && touch file2 && ls" > ex2.sh \[ andrew@pc01 ~ \]$ chmod +x ex2.sh ``` An executable shell script can be run by preceding it with `./`: ``` \[ andrew@pc01 ~ \]$ ./ex2.sh 桌面 Git TEST c ex.sh ex2.sh 檔案專案測試 桌面 Git TEST c ex.sh ex2.sh 檔案 file2 專案測試 ``` Long lines of code can be split by ending a command with `\`: ``` \[ andrew@pc01 ~ \]$ echo "for i in {1..3}; do echo \\ > \\"歡迎\\$i次\\";完成” > ex3.sh ``` Bash scripts can contain loops, functions, and more! ``` \[ andrew@pc01 ~ \]$ 源 ex3.sh 歡迎1次 歡迎2次 歡迎3次 ``` <a name="custom-prompt-ls"></a> ### Custom Prompt and `ls` [[ Back to Table of Contents ]](#toc) Bash scripting can make your life a whole lot easier and more colourful. [Check out this great bash scripting cheat sheet.](https://devhints.io/bash) `$PS1` (Prompt String 1) is the environment variable that defines your main shell prompt ([learn about the other prompts here](http://bit.ly/2SPgsmT)): ``` \[ andrew@pc01 ~ \]$ printf "%q" $PS1 $'\\n\\\[\\E\[1m\\\]\\\[\\E\[30m\\\]\\A'$'\\\[\\E\[37m\\\]|\\\[\\E\[36m\\\]\\u\\\[\\E\[37m \\\]@\\\[\\E\[34m\\\]\\h'$'\\\[\\E\[32m\\\]\\W\\\[\\E\[37m\\\]|'$'\\\[\\E(B\\E\[m\\\] ' ``` You can change your default prompt with the `export` command: ``` \[ andrew@pc01 ~ \]$ export PS1="\\n此處指令> " 此處指令> echo $PS1 \\n此處指令> ``` ...[you can add colours, too!](http://bit.ly/2TMbEit): ``` 此處指令> export PS1="\\e\[1;31m\\n程式碼: \\e\[39m" (這應該是紅色的,但在 Markdown 中可能不會這樣顯示) =============================== 程式碼:回顯$PS1 \\e\[1;31m\\n程式碼: \\e\[39m ``` You can also change the colours shown by `ls` by editing the `$LS_COLORS` environment variable: ``` (同樣,這些顏色可能不會出現在 Markdown 中) =========================== 程式碼:ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 程式碼:匯出 LS\_COLORS='di=31:fi=0:ln=96:or=31:mi=31:ex=92' 程式碼:ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 ``` <a name="config-files"></a> ## Config Files <a name="config-bashrc"></a> ### Config Files / `.bashrc` [[ Back to Table of Contents ]](#toc) If you tried the commands in the last section and logged out and back in, you may have noticed that your changes disappeared. _config_ (configuration) files let you maintain settings for your shell or for a particular program every time you log in (or run that program). The main configuration file for a `bash` shell is the `~/.bashrc` file. Aliases, environment variables, and functions added to `~/.bashrc` will be available every time you log in. Commands in `~/.bashrc` will be run every time you log in. If you edit your `~/.bashrc` file, you can reload it without logging out by using the `source` command: ``` \[ andrew@pc01 ~ \]$ nano ~/.bashrc ``` _...add the line `echo “~/.bashrc loaded!”` to the top of the file_... ``` \[ andrew@pc01 ~ \]$ 源 ~/.bashrc ~/.bashrc 已載入! ``` _...log out and log back in..._ ``` 最後登入:2019 年 1 月 11 日星期五 10:29:07 從 111.11.11.111 ~/.bashrc 已加載! \[ 安德魯@pc01 ~ \] ``` <a name="types-of-shells"></a> ### Types of Shells [[ Back to Table of Contents ]](#toc) _Login_ shells are shells you log in to (where you have a username). _Interactive_ shells are shells which accept commands. Shells can be login and interactive, non-login and non-interactive, or any other combination. In addition to `~/.bashrc`, there are a few other scripts which are `sourced` by the shell automatically when you log in or log out. These are: - `/etc/profile` - `~/.bash_profile` - `~/.bash_login` - `~/.profile` - `~/.bash_logout` - `/etc/bash.bash_logout` Which of these scripts are sourced, and the order in which they're sourced, depend on the type of shell opened. See [the bash man page](https://linux.die.net/man/1/bash) and [these](http://bit.ly/2TGCwA8) Stack Overflow [posts](http://bit.ly/2TFHFsf) for more information. Note that `bash` scripts can `source` other scripts. For instance, in your `~/.bashrc`, you could include the line: ``` 來源~/.bashrc\_addl ``` ...which would also `source` that `.bashrc_addl` script. This file can contain its own aliases, functions, environment variables, and so on. It could, in turn, `source` other scripts, as well. (Be careful to avoid infinite loops of script-sourcing!) It may be helpful to split commands into different shell scripts based on functionality or machine type (Ubuntu vs. Red Hat vs. macOS), for example: - `~/.bash_ubuntu` -- configuration specific to Ubuntu-based machines - `~/.bashrc_styles` -- aesthetic settings, like `PS1` and `LS_COLORS` - `~/.bash_java` -- configuration specific to the Java language I try to keep separate `bash` files for aesthetic configurations and OS- or machine-specific code, and then I have one big `bash` file containing shortcuts, etc. that I use on every machine and every OS. Note that there are also _different shells_. `bash` is just one kind of shell (the "Bourne Again Shell"). Other common ones include `zsh`, `csh`, `fish`, and more. Play around with different shells and find one that's right for you, but be aware that this tutorial contains `bash` shell commands only and not everything listed here (maybe none of it) will be applicable to shells other than `bash`. <a name="finding-things"></a> ## Finding Things <a name="whereis-which-whatis"></a> ### `whereis / which / whatis` [[ Back to Table of Contents ]](#toc) `whereis` searches for "possibly useful" files related to a particular command. It will attempt to return the location of the binary (executable machine code), source (code source files), and `man` page for that command: ``` \[ andrew@pc01 ~ \]$ whereis ls ls: /bin/ls /usr/share/man/man1/ls.1.gz ``` `which` will only return the location of the binary (the command itself): ``` \[ andrew@pc01 ~ \]$ 其中 ls /bin/ls ``` `whatis` prints out the one-line description of a command from its `man` page: ``` \[ andrew@pc01 ~ \]$ 什麼是哪裡是哪個什麼是 whereis (1) - 尋找指令的二進位、原始檔和手冊頁文件 which (1) - 定位指令 Whatis (1) - 顯示一行手冊頁描述 ``` `which` is useful for finding the "original version" of a command which may be hidden by an alias: ``` \[ andrew@pc01 ~ \]$ 別名 ls="ls -l" “original” ls 已被上面定義的別名“隱藏” =========================== \[ andrew@pc01 ~ \]$ ls 總計 36 drwxr-xr-x 2 安德魯 andrew 4096 Jan 9 14:47 桌面 drwxr-xr-x 4 安德魯 安德魯 4096 十二月 6 10:43 Git … 但我們仍然可以使用返回的位置來呼叫「原始」ls ======================= \[ andrew@pc01 ~ \]$ /bin/ls 桌面 Git TEST c ex.sh ex2.sh ex3.sh 檔案 file2 專案測試 ``` <a name="locate-find"></a> ### `locate / find` [[ Back to Table of Contents ]](#toc) `locate` finds a file anywhere on the system by referring to a semi-regularly-updated cached list of files: ``` \[ andrew@pc01 ~ \]$ 找到 README.md /home/andrew/.config/micro/plugins/gotham-colors/README.md /home/andrew/.jenv/README.md /home/andrew/.myshell/README.md … ``` Because it's just searching a list, `locate` is usually faster than the alternative, `find`. `find` iterates through the file system to find the file you're looking for. Because it's actually looking at the files which _currently_ exist on the system, though, it will always return an up-to-date list of files, which is not necessarily true with `locate`. ``` \[ andrew@pc01 ~ \]$ find ~/ -iname "README.md" /home/andrew/.jenv/README.md /home/andrew/.config/micro/plugins/gotham-colors/README.md /home/andrew/.oh-my-zsh/plugins/ant/README.md … ``` `find` was written for the very first version of Unix in 1971, and is therefore much more widely available than `locate`, which was added to GNU in 1994. `find` has many more features than `locate`, and can search by file age, size, ownership, type, timestamp, permissions, depth within the file system; `find` can search using regular expressions, execute commands on files it finds, and more. When you need a fast (but possibly outdated) list of files, or you’re not sure what directory a particular file is in, use `locate`. When you need an accurate file list, maybe based on something other than the files’ names, and you need to do something with those files, use `find`. <a name="downloading-things"></a> ## Downloading Things <a name="ping-wget-curl"></a> ### `ping / wget / curl` [[ Back to Table of Contents ]](#toc) `ping` attempts to open a line of communication with a network host. Mainly, it's used to check whether or not your Internet connection is down: ``` \[ andrew@pc01 ~ \]$ ping google.com PING google.com (74.125.193.100) 56(84) 位元組資料。 使用 32 位元組資料 Ping 74.125.193.100: 來自 74.125.193.100 的回覆:位元組=32 時間<1ms TTL=64 … ``` `wget` is used to easily download a file from the Internet: ``` \[ andrew@pc01 ~ \]$ wget \\ > http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso ``` `curl` can be used just like `wget` (don’t forget the `--output` flag): ``` \[ andrew@pc01 ~ \]$ 捲曲 \\ > http://releases.ubuntu.com/18.10/ubuntu-18.10-desktop-amd64.iso \\ > \--輸出ubuntu.iso ``` `curl` and `wget` have their own strengths and weaknesses. `curl` supports many more protocols and is more widely available than `wget`; `curl` can also send data, while `wget` can only receive data. `wget` can download files recursively, while `curl` cannot. In general, I use `wget` when I need to download things from the Internet. I don’t often need to send data using `curl`, but it’s good to be aware of it for the rare occasion that you do. <a name="apt-gunzip-tar-gzip"></a> ### `apt / gunzip / tar / gzip` [[ Back to Table of Contents ]](#toc) Debian-descended Linux distributions have a fantastic package management tool called `apt`. It can be used to install, upgrade, or delete software on your machine. To search `apt` for a particular piece of software, use `apt search`, and install it with `apt install`: ``` \[ andrew@pc01 ~ \]$ apt 搜尋漂白位 ...bleachbit/bionic、bionic 2.0-2 全部 從系統中刪除不需要的文件 您需要“sudo”來安裝軟體 ============== \[ andrew@pc01 ~ \]$ sudo apt installbleachbit ``` Linux software often comes packaged in `.tar.gz` ("tarball") files: ``` \[ andrew@pc01 ~ \]$ wget \\ > https://github.com/atom/atom/releases/download/v1.35.0-beta0/atom-amd64.tar.gz ``` ...these types of files can be unzipped with `gunzip`: ``` \[ andrew@pc01 ~ \]$gunzipatom-amd64.tar.gz && ls 原子 amd64.tar ``` A `.tar.gz` file will be `gunzip`-ped to a `.tar` file, which can be extracted to a directory of files using `tar -xf` (`-x` for "extract", `-f` to specify the file to "untar"): ``` \[ andrew@pc01 ~ \]$ tar -xfatom-amd64.tar && mv \\ 原子-beta-1.35.0-beta0-amd64 原子 && ls 原子atom-amd64.tar ``` To go in the reverse direction, you can create (`-c`) a tar file from a directory and zip it (or unzip it, as appropriate) with `-z`: ``` \[ andrew@pc01 ~ \]$ tar -zcf 壓縮.tar.gz 原子 && ls 原子atom-amd64.tar壓縮.tar.gz ``` `.tar` files can also be zipped with `gzip`: ``` \[ andrew@pc01 ~ \]$ gzipatom-amd64.tar && ls 原子 原子-amd64.tar.gz 壓縮.tar.gz ``` <a name="redirecting-io"></a> ## Redirecting Input and Output <a name="pipe-gt-lt-echo-printf"></a> ### `| / > / < / echo / printf` [[ Back to Table of Contents ]](#toc) By default, shell commands read their input from the standard input stream (aka. stdin or 0) and write to the standard output stream (aka. stdout or 1), unless there’s an error, which is written to the standard error stream (aka. stderr or 2). `echo` writes text to stdout by default, which in most cases will simply print it to the terminal: ``` \[ andrew@pc01 ~ \]$ 回顯“你好” 你好 ``` The pipe operator, `|`, redirects the output of the first command to the input of the second command: ``` 'wc'(字數)傳回檔案中的行數、字數、位元組數 ======================== \[ andrew@pc01 ~ \]$ echo "範例文件" |廁所 ``` 1 2 17 ``` ``` `>` redirects output from stdout to a particular location ``` \[ andrew@pc01 ~ \]$ echo "test" > 文件 && 頭文件 測試 ``` `printf` is an improved `echo`, allowing formatting and escape sequences: ``` \[ andrew@pc01 ~ \]$ printf "1\\n3\\n2" 1 3 2 ``` `<` gets input from a particular location, rather than stdin: ``` 'sort' 依字母/數字順序對檔案的行進行排序 ======================== \[ andrew@pc01 ~ \]$ sort <(printf "1\\n3\\n2") 1 2 3 ``` Rather than a [UUOC](#viewing-and-editing-files), the recommended way to send the contents of a file to a command is to use `<`. Note that this causes data to "flow" right-to-left on the command line, rather than (the perhaps more natural, for English-speakers) left-to-right: ``` \[ andrew@pc01 ~ \]$ printf "1\\n3\\n2" > 文件 && 排序 < 文件 1 2 3 ``` <a name="std-tee"></a> ### `0 / 1 / 2 / tee` [[ Back to Table of Contents ]](#toc) 0, 1, and 2 are the standard input, output, and error streams, respectively. Input and output streams can be redirected with the `|`, `>`, and `<` operators mentioned previously, but stdin, stdout, and stderr can also be manipulated directly using their numeric identifiers: Write to stdout or stderr with `>&1` or `>&2`: ``` \[ andrew@pc01 ~ \]$ 貓測試 回顯“標準輸出”>&1 回顯“標準錯誤”>&2 ``` By default, stdout and stderr both print output to the terminal: ``` \[ andrew@pc01 ~ \]$ ./測試 標準錯誤 標準輸出 ``` Redirect stdout to `/dev/null` (only print output sent to stderr): ``` \[ andrew@pc01 ~ \]$ ./test 1>/dev/null 標準錯誤 ``` Redirect stderr to `/dev/null` (only print output sent to stdout): ``` \[ andrew@pc01 ~ \]$ ./test 2>/dev/null 標準輸出 ``` Redirect all output to `/dev/null` (print nothing): ``` \[ andrew@pc01 ~ \]$ ./test &>/dev/null ``` Send output to stdout and any number of additional locations with `tee`: ``` \[ andrew@pc01 ~ \]$ ls && echo "測試" | tee 文件1 文件2 文件3 && ls 文件0 測試 文件0 文件1 文件2 文件3 ``` <a name="advanced"></a> # Advanced <a name="superuser"></a> ## Superuser <a name="sudo-su"></a> ### `sudo / su` [[ Back to Table of Contents ]](#toc) You can check what your username is with `whoami`: ``` \[ andrew@pc01 abc \]$ whoami 安德魯 ``` ...and run a command as another user with `sudo -u username` (you will need that user's password): ``` \[ andrew@pc01 abc \]$ sudo -u 測試觸摸 def && ls -l 總計 0 -rw-r--r-- 1 次測試 0 Jan 11 20:05 def ``` If `–u` is not provided, the default user is the superuser (usually called "root"), with unlimited permissions: ``` \[ andrew@pc01 abc \]$ sudo touch ghi && ls -l 總計 0 -rw-r--r-- 1 次測試 0 Jan 11 20:05 def -rw-r--r-- 1 root root 0 Jan 11 20:14 ghi ``` Use `su` to become another user temporarily (and `exit` to switch back): ``` \[ andrew@pc01 abc \]$ su 測試 密碼: test@pc01:/home/andrew/abc$ whoami 測試 test@pc01:/home/andrew/abc$ 退出 出口 \[ andrew@pc01 abc \]$ whoami 安德魯 ``` [Learn more about the differences between `sudo` and `su` here.](http://bit.ly/2SKQH77) <a name="click-click"></a> ### `!!` [[ Back to Table of Contents ]](#toc) The superuser (usually "root") is the only person who can install software, create users, and so on. Sometimes it's easy to forget that, and you may get an error: ``` \[ andrew@pc01 ~ \]$ apt 安裝 ruby E:無法開啟鎖定檔案 /var/lib/dpkg/lock-frontend - 開啟(13:權限被拒絕) E: 無法取得 dpkg 前端鎖定 (/var/lib/dpkg/lock-frontend),您是 root 嗎? ``` You could retype the command and add `sudo` at the front of it (run it as the superuser): ``` \[ andrew@pc01 ~ \]$ sudo apt install ruby 正在閱讀包裝清單... ``` Or, you could use the `!!` shortcut, which retains the previous command: ``` \[ andrew@pc01 ~ \]$ apt 安裝 ruby E:無法開啟鎖定檔案 /var/lib/dpkg/lock-frontend - 開啟(13:權限被拒絕) E: 無法取得 dpkg 前端鎖定 (/var/lib/dpkg/lock-frontend),您是 root 嗎? \[ andrew@pc01 ~ \]$ sudo !! sudo apt 安裝 ruby 正在閱讀包裝清單... ``` By default, running a command with `sudo` (and correctly entering the password) allows the user to run superuser commands for the next 15 minutes. Once those 15 minutes are up, the user will again be prompted to enter the superuser password if they try to run a restricted command. <a name="file-permissions"></a> ## File Permissions <a name="file-permissions-sub"></a> ### File Permissions [[ Back to Table of Contents ]](#toc) Files may be able to be read (`r`), written to (`w`), and/or executed (`x`) by different users or groups of users, or not at all. File permissions can be seen with the `ls -l` command and are represented by 10 characters: ``` \[ andrew@pc01 ~ \]$ ls -lh 總計 8 drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -rwxr-xr-x 1 安德魯 安德魯 40 Jan 11 16:16 測試 -rw-r--r-- 1 安德魯 安德魯 0 一月 11 16:34 tist ``` The first character of each line represents the type of file, (`d` = directory, `l` = link, `-` = regular file, and so on); then there are three groups of three characters which represent the permissions held by the user (u) who owns the file, the permissions held by the group (g) which owns the file, and the permissions held any other (o) users. (The number which follows this string of characters is the number of links in the file system to that file (4 or 1 above).) `r` means that person / those people have read permission, `w` is write permission, `x` is execute permission. If a directory is “executable”, that means it can be opened and its contents can be listed. These three permissions are often represented with a single three-digit number, where, if `x` is enabled, the number is incremented by 1, if `w` is enabled, the number is incremented by 2, and if `r` is enabled, the number is incremented by 4. Note that these are equivalent to binary digits (`r-x` -> `101` -> `5`, for example). So the above three files have permissions of 755, 755, and 644, respectively. The next two strings in each list are the name of the owner (`andrew`, in this case) and the group of the owner (also `andrew`, in this case). Then comes the size of the file, its most recent modification time, and its name. The `–h` flag makes the output human readable (i.e. printing `4.0K` instead of `4096` bytes). <a name="chmod-chown"></a> ### `chmod / chown` [[ Back to Table of Contents ]](#toc) File permissions can be modified with `chmod` by setting the access bits: ``` \[ andrew@pc01 ~ \]$ chmod 777 測試 && chmod 000 tit && ls -lh 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -rwxrwxrwx 1 安德魯 安德魯 40 Jan 11 16:16 測試 \---------- 1 安德魯 安德魯 0 一月 11 16:34 tist ``` ...or by adding (`+`) or removing (`-`) `r`, `w`, and `x` permissions with flags: ``` \[ andrew@pc01 ~ \]$ chmod +rwx Tist && chmod -w 測試 && ls -lh chmod:測試:新權限是 r-xrwxrwx,而不是 r-xr-xr-x 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 -r-xrwxrwx 1 安德魯 安德魯 40 Jan 11 16:16 測試 -rwxr-xr-x 1 安德魯 安德魯 0 一月 11 16:34 tist ``` The user who owns a file can be changed with `chown`: ``` \[ andrew@pc01 ~ \]$ sudo chown 碼頭測試 ``` The group which owns a file can be changed with `chgrp`: ``` \[ andrew@pc01 ~ \]$ sudo chgrp hadoop tit && ls -lh 總計 8.0K drwxr-xr-x 4 安德魯 安德魯 4.0K 1 月 4 日 19:37 品嚐 \-----w--w- 1 瑪麗娜·安德魯 2011 年 1 月 40 日 16:16 測試 -rwxr-xr-x 1 安德魯 hadoop 0 一月 11 16:34 tist ``` <a name="users-groups"></a> ## User and Group Management <a name="users"></a> ### Users [[ Back to Table of Contents ]](#toc) `users` shows all users currently logged in. Note that a user can be logged in multiple times if -- for instance -- they're connected via multiple `ssh` sessions. ``` \[ andrew@pc01 ~ \]$ 用戶 安德魯·科林·科林·科林·科林·科林·克里希納·克里希納 ``` To see all users (even those not logged in), check `/etc/passwd`. (**WARNING**: do not modify this file! You can corrupt your user accounts and make it impossible to log in to your system.) ``` \[ andrew@pc01 ~ \]$ alias au="cut -d: -f1 /etc/passwd \\ > |排序| uniq”&& au \_易於 一個廣告 安德魯... ``` Add a user with `useradd`: ``` \[ andrew@pc01 ~ \]$ sudo useradd aardvark && au \_易於 土豚 一個廣告... ``` Delete a user with `userdel`: ``` \[ andrew@pc01 ~ \]$ sudo userdel aardvark && au \_易於 一個廣告 安德魯... ``` [Change a user’s default shell, username, password, or group membership with `usermod`.](http://bit.ly/2D4upIg) <a name="groups"></a> ### Groups [[ Back to Table of Contents ]](#toc) `groups` shows all of the groups of which the current user is a member: ``` \[ andrew@pc01 ~ \]$ 組 andrew adm cdrom sudo dial plugdev lpadmin sambashare hadoop ``` To see all groups on the system, check `/etc/group`. (**DO NOT MODIFY** this file unless you know what you are doing.) ``` \[ andrew@pc01 ~ \]$ alias ag=“cut -d: -f1 /etc/group \\ > |排序”&& ag 管理員 一個廣告 安德魯... ``` Add a group with `groupadd`: ``` \[ andrew@pc01 ~ \]$ sudo groupadd aardvark && ag 土豚 管理員 一個廣告... ``` Delete a group with `groupdel`: ``` \[ andrew@pc01 ~ \]$ sudo groupdel aardvark && ag 管理員 一個廣告 安德魯... ``` [Change a group’s name, ID number, or password with `groupmod`.](https://linux.die.net/man/8/groupmod) <a name="text-processing"></a> ## Text Processing <a name="uniq-sort-diff-cmp"></a> ### `uniq / sort / diff / cmp` [[ Back to Table of Contents ]](#toc) `uniq` can print unique lines (default) or repeated lines: ``` \[ andrew@pc01 man \]$ printf "1\\n2\\n2" > a && \\ > printf "1\\n3\\n2" > b \[ andrew@pc01 人 \]$ uniq a 1 2 ``` `sort` will sort lines alphabetically / numerically: ``` \[ andrew@pc01 man \]$ 排序 b 1 2 3 ``` `diff` will report which lines differ between two files: ``` \[ andrew@pc01 人 \]$ diff ab 2c2 < 2 --- > 3 ``` `cmp` reports which bytes differ between two files: ``` \[andrew@pc01 人\]$ cmp ab ab 不同:字元 3,第 2 行 ``` <a name="cut-sed"></a> ### `cut / sed` [[ Back to Table of Contents ]](#toc) `cut` is usually used to cut a line into sections on some delimiter (good for CSV processing). `-d` specifies the delimiter and `-f` specifies the field index to print (starting with 1 for the first field): ``` \[ andrew@pc01 人 \]$ printf "137.99.234.23" > c \[ andrew@pc01 man \]$ cut -d'.' c-f1 137 ``` `sed` is commonly used to replace a string with another string in a file: ``` \[ andrew@pc01 man \]$ echo "舊" | sed s/舊/新/ 新的 ``` ...but `sed` is an extremely powerful utility, and cannot be properly summarised here. It’s actually Turing-complete, so it can do anything that any other programming language can do. `sed` can find and replace based on regular expressions, selectively print lines of a file which match or contain a certain pattern, edit text files in-place and non-interactively, and much more. A few good tutorials on `sed` include: - [https://www.tutorialspoint.com/sed/](https://www.tutorialspoint.com/sed/) - [http://www.grymoire.com/Unix/Sed.html](http://www.grymoire.com/Unix/Sed.html) - [https://www.computerhope.com/unix/used.htm](https://www.computerhope.com/unix/used.htm) <a name="pattern-matching"></a> ## Pattern Matching <a name="grep"></a> ### `grep` [[ Back to Table of Contents ]](#toc) The name `grep` comes from `g`/`re`/`p` (search `g`lobally for a `r`egular `e`xpression and `p`rint it); it’s used for finding text in files. `grep` is used to find lines of a file which match some pattern: ``` \[ andrew@pc01 ~ \]$ grep -e " *.fi.* " /etc/profile /etc/profile:Bourne shell 的系統範圍 .profile 檔案 (sh(1)) =================================================== ``` # The file bash.bashrc already sets the default PS1. ``` ``` fi ``` ``` fi ``` … ``` ...or contain some word: ``` \[ andrew@pc01 ~ \]$ grep "andrew" /etc/passwd 安德魯:x:1000:1000:安德魯,,,:/home/andrew:/bin/bash ``` `grep` is usually the go-to choice for simply finding matching lines in a file, if you’re planning on allowing some other program to handle those lines (or if you just want to view them). `grep` allows for (`-E`) use of extended regular expressions, (`-F`) matching any one of multiple strings at once, and (`-r`) recursively searching files within a directory. These flags used to be implemented as separate commands (`egrep`, `fgrep`, and `rgrep`, respectively), but those commands are now deprecated. > **Bonus**: [see the origins of the names of a few famous `bash` commands](https://kb.iu.edu/d/abnd) <a name="awk"></a> ### `awk` [[ Back to Table of Contents ]](#toc) `awk` is a pattern-matching language built around reading and manipulating delimited data files, like CSV files. As a rule of thumb, `grep` is good for finding strings and patterns in files, `sed` is good for one-to-one replacement of strings in files, and `awk` is good for extracting strings and patterns from files and analysing them. As an example of what `awk` can do, here’s a file containing two columns of data: ``` \[ andrew@pc01 ~ \]$ printf "A 10\\nB 20\\nC 60" > 文件 ``` Loop over the lines, add the number to sum, increment count, print the average: ``` \[ andrew@pc01 ~ \]$ awk 'BEGIN {sum=0;計數=0; OFS=“”} {sum+=$2; count++} END {print "平均值:", sum/count}' 文件 平均:30 ``` `sed` and `awk` are both Turing-complete languages. There have been multiple books written about each of them. They can be extremely useful with pattern matching and text processing. I really don’t have enough space here to do either of them justice. Go read more about them! > **Bonus**: [learn about some of the differences between `sed`, `grep`, and `awk`](http://bit.ly/2AI3IaN) <a name="ssh"></a> ## Copying Files Over `ssh` <a name="ssh-scp"></a> ### `ssh / scp` [[ Back to Table of Contents ]](#toc) `ssh` is how Unix-based machines connect to each other over a network: ``` \[ andrew@pc01 ~ \]$ ssh –p安德魯@137.xxx.xxx.89 上次登入:2019 年 1 月 11 日星期五 12:30:52,來自 137.xxx.xxx.199 ``` Notice that my prompt has changed as I’m now on a different machine: ``` \[ andrew@pc02 ~ \]$ 退出 登出 與 137.xxx.xxx.89 的連線已關閉。 ``` Create a file on machine 1: ``` \[ andrew@pc01 ~ \]$ echo "你好" > 你好 ``` Copy it to machine 2 using `scp` (secure copy; note that `scp` uses `–P` for a port #, `ssh` uses `–p`) ``` \[ andrew@pc01 ~ \]$ scp –P你好安德魯@137.xxx.xxx.89:~ 你好 100% 0 0.0KB/秒 00:00 ``` `ssh` into machine 2: ``` \[ andrew@pc02 ~ \]$ ssh –p安德魯@137.xxx.xxx.89 上次登入:2019 年 1 月 11 日星期五 22:47:37,來自 137.xxx.xxx.79 ``` The file’s there! ``` \[ andrew@pc02 ~ \]$ ls 你好多xargs \[ andrew@pc02 ~ \]$ 貓你好 你好 ``` <a name="rsync"></a> ### `rsync` [[ Back to Table of Contents ]](#toc) `rsync` is a file-copying tool which minimises the amount of data copied by looking for deltas (changes) between files. Suppose we have two directories: `d`, with one file, and `s`, with two files: ``` \[ andrew@pc01 d \]$ ls && ls ../s f0 f0 f1 ``` Sync the directories (copying only missing data) with `rsync`: ``` \[ andrew@pc01 d \]$ rsync -off ../s/\* . 正在發送增量文件列表... ``` `d` now contains all files that `s` contains: ``` \[ andrew@pc01 d \]$ ls f0 f1 ``` `rsync` can be performed over `ssh` as well: ``` \[ andrew@pc02 r \]$ ls \[ andrew@pc02 r \]$ rsync -avz -e "ssh -p “ [email protected]:~/s/\* 。 接收增量檔案列表 f0 f1 發送 62 位元組 接收 150 位元組 141.33 位元組/秒 總大小為 0 加速率為 0.00 \[ andrew@pc02 r \]$ ls f0 f1 ``` <a name="long-running-processes"></a> ## Long-Running Processes <a name="yes-nohup-ps-kill"></a> ### `yes / nohup / ps / kill` [[ Back to Table of Contents ]](#toc) Sometimes, `ssh` connections can disconnect due to network or hardware problems. Any processes initialized through that connection will be “hung up” and terminate. Running a command with `nohup` insures that the command will not be hung up if the shell is closed or if the network connection fails. Run `yes` (continually outputs "y" until it’s killed) with `nohup`: ``` \[ andrew@pc01 ~ \]$ nohup 是 & \[1\]13173 ``` `ps` shows a list of the current user’s processes (note PID number 13173): ``` \[ andrew@pc01 ~ \]$ ps | sed -n '/是/p' 13173 分/10 00:00:12 是 ``` _...log out and log back into this shell..._ The process has disappeared from `ps`! ``` \[ andrew@pc01 ~ \]$ ps | sed -n '/是/p' ``` But it still appears in `top` and `htop` output: ``` \[ andrew@pc01 ~ \]$ 頂部 -bn 1 | sed -n '/是/p' 13173 安德魯 20 0 4372 704 636 D 25.0 0.0 0:35.99 是 ``` Kill this process with `-9` followed by its process ID (PID) number: ``` \[ andrew@pc01 ~ \]$ 殺死 -9 13173 ``` It no longer appears in `top`, because it’s been killed: ``` \[ andrew@pc01 ~ \]$ 頂部 -bn 1 | sed -n '/是/p' ``` <a name="cron"></a> ### `cron / crontab / >>` [[ Back to Table of Contents ]](#toc) `cron` provides an easy way of automating regular, scheduled tasks. You can edit your `cron` jobs with `crontab –e` (opens a text editor). Append the line: ``` - - - - - 日期 >> ~/datefile.txt ``` This will run the `date` command every minute, appending (with the `>>` operator) the output to a file: ``` \[ andrew@pc02 ~ \]$ head ~/datefile.txt 2019 年 1 月 12 日星期六 14:37:01 GMT 2019 年 1 月 12 日星期六