### Initial Lodash CLI Setup and NPM Package Build Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/lodash/release.md This snippet details the commands to set up the `lodash-cli` within the `lodash` project, install dependencies, and then use `lodash-cli` to build the core and modularized versions of `lodash` for an npm package. It includes cloning `lodash-cli` and copying necessary files. ```shell npm run build npm run doc npm i git clone --depth=10 --branch=master git@github.com:lodash-archive/lodash-cli.git ./node_modules/lodash-cli mkdir -p ./node_modules/lodash-cli/node_modules/lodash; cd $_; cp ../../../../lodash.js ./lodash.js; cp ../../../../package.json ./package.json cd ../../; npm i --production; cd ../../ node ./node_modules/lodash-cli/bin/lodash core exports=node -o ./npm-package/core.js node ./node_modules/lodash-cli/bin/lodash modularize exports=node -o ./npm-package cp lodash.js npm-package/lodash.js cp dist/lodash.min.js npm-package/lodash.min.js cp LICENSE npm-package/LICENSE ``` -------------------------------- ### Install bluebird-co and Bluebird Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Instructions to install the bluebird-co library and its peer dependency, Bluebird, using npm. These commands are essential setup steps before using the library. ```shell npm install bluebird-co ``` ```shell npm install bluebird@3 ``` -------------------------------- ### Example ES7 Async Function with Babel Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md A simple ES7 `async` function demonstrating how code looks when transformed by Babel 6 using `bluebird-co`. This snippet shows the clean syntax enabled by the Babel plugin. ```javascript async function fn() { //do stuff } fn().then(...); ``` -------------------------------- ### Install Lodash via npm Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/lodash/README.md Provides shell commands to install npm globally and then add Lodash as a project dependency using npm. ```shell $ npm i -g npm $ npm i --save lodash ``` -------------------------------- ### JavaScript Game Data Setup and Board Calculation Source: https://github.com/autox-community/autox/blob/master/app/src/main/assets/sample/Web扩展与游戏编程/game.html This snippet initializes the active game dictionary from a global `game_dicts` object, clears and repopulates a DOM element (assumed to be a select or dropdown) with keys from `game_dicts`, and then calculates `unit_number`, `r_max`, and `r` which are likely used for determining game board size and content distribution. It assumes the existence of `$` for DOM manipulation and `table_m`, `table_n` for initial board dimensions. ```JavaScript game_dict = game_dicts[Object.keys(game_dicts)[0]]; $("game_dict").innerHTML = ""; Object.keys(game_dicts).forEach(item => { $("game_dict").add(new Option(item, item)); }); unit_number = table_m * table_n; if (unit_number % 2 == 1) unit_number -= 1; r_max = Math.ceil(Object.keys(game_dict).length * 2 / (unit_number)); r = Math.floor(Math.random() * r_max); memory_cards(); ``` -------------------------------- ### Await Multiple Asynchronous Operations in a JavaScript Array Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md This example illustrates how to use 'await' with an array containing a mix of asynchronous function calls, promises, and literal values. This pattern allows for concurrent execution and collection of results from multiple async operations, useful for scenarios where order of results is not critical but all must complete. ```javascript async function() { let res = await [asyncFunc1(), asyncFunc2(), somePromise, 42]; } ``` -------------------------------- ### Create Bluebird Coroutine with CommonJS Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md An example of defining and using a Bluebird coroutine with `bluebird-co` in a CommonJS environment. It demonstrates yielding multiple promises and arrays, showcasing the library's ability to handle complex asynchronous flows. ```javascript var Promise = require('bluebird'); var fs = Promise.promisifyAll(require('fs')); var myAsyncFunction = Promise.coroutine(function*() { var results = yield [Promise.delay( 10 ).return( 42 ), fs.readFileAsync( 'index.js', 'utf-8' ), [1, Promise.resolve( 12 )]]; console.log(results); //[42, "somefile contents", [1, 12]] }); myAsyncFunction().then(...); ``` -------------------------------- ### Create Bluebird Coroutine with ES7 Async/Await Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md An example of defining and using an ES7 `async` function with `bluebird-co` in an ES module environment. This snippet showcases the use of `await` with multiple promises and arrays, providing a modern approach to asynchronous operations. ```javascript import Promise from 'bluebird'; import {readFile} from 'fs'; let readFileAsync = Promise.promisify(readFile); async function myAsyncFunction() { let results = await [Promise.delay( 10 ).return( 42 ), readFileAsync( 'index.js', 'utf-8' ), [1, Promise.resolve( 12 )]]; console.log(results); //[42, "somefile contents", [1, 12]] } myAsyncFunction().then(...); ``` -------------------------------- ### JavaScript: Define Custom Yield Handler for bluebird-co Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Demonstrates how to register a custom yield handler with `bluebird-co` using `coroutine.addYieldHandler`. This example illustrates how to automatically invoke a `fetch()` method on a custom `MyModel` instance when it is yielded, allowing it to be treated as a promise. ```javascript import {coroutine} from 'bluebird-co'; class MyModel { async fetch() { //do stuff return data; } } coroutine.addYieldHandler(function(value) { if(value instanceof MyModel) { return value.fetch(); } }); async function test() { let model = new MyModel(); let data = await model; //calls model.fetch() and waits on it. } ``` -------------------------------- ### Synchronously Iterate ES6 Set Values Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md Demonstrates how to iterate over the values of an ES6 `Set` using its `values()` method and the standard iterator protocol. The example shows synchronous traversal of set elements, printing each value until the iterator is exhausted. ```javascript let mySet = new Set([1, 2, 3, 4]); let values = mySet.values(); let cur = values.next(); //Prints out 1 2 3 4 while(!cur.done) { console.log(cur.value); cur = values.next(); } ``` -------------------------------- ### APIDOC: bluebird-co.execute(gfn, ...args) and JavaScript Usage Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Executes a GeneratorFunction or Generator object, returning a Promise. This function is intended as a direct replacement for `tj/co`'s `co` function, allowing generators to be run with provided arguments. The JavaScript example demonstrates its usage for executing a simple generator. ```APIDOC .execute(gfn : GeneratorFunction|Generator, ...args : any[]) -> Promise alias: .co(gfn : GeneratorFunction|Generator, ...args : any[]) -> Promise ``` ```javascript //import {co} from 'bluebird-co'; var co = require('bluebird-co').co; function* do_stuff(num) { return num; } co(do_stuff, 10).then(function(result){ console.log(result); //10 }); ``` -------------------------------- ### Run Lodash Build and Core Generation Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/lodash/release.md This snippet executes the standard `npm` build and documentation generation scripts for `lodash`, followed by a command to generate the core `lodash` file using the `lodash-cli`. ```shell npm run build npm run doc node ../lodash-cli/bin/lodash core -o ./dist/lodash.core.js ``` -------------------------------- ### Handle Promises with Async/Await in JavaScript Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md This snippet demonstrates the basic usage of 'async/await' to resolve a simple promise. It shows how to await a 'Promise.resolve()' call and log its result, illustrating the most straightforward yieldable type. ```javascript async function() { let res = await Promise.resolve(1); console.log(res); //1 } ``` -------------------------------- ### Clone Lodash Repositories for Development Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/lodash/release.md These commands are used to clone the main `lodash` and `lodash-cli` repositories from GitHub, which are prerequisites for the build and release process. ```shell git clone https://github.com/lodash/lodash.git git clone https://github.com/bnjmnt4n/lodash-cli.git ``` -------------------------------- ### JavaScript: Initialize Memory Card Game Board Source: https://github.com/autox-community/autox/blob/master/app/src/main/assets/sample/Web扩展与游戏编程/game.html This function dynamically creates the HTML table structure for the memory card game board. It calculates the number of units, populates dropdown options for game rounds, clears existing content, and then constructs a table with cells containing image and text elements for each card. It also attaches event listeners to each card for the flip action and calls `cards_shuffle()` to populate the board. ```javascript function memory_cards() { unit_number = table_m * table_n; if (unit_number % 2 == 1) unit_number -= 1 r_max = Math.ceil(Object.keys(game_dict).length * 2 / (unit_number)); $("r").innerHTML = "" $("r").add(new Option(r.toString(), r)); for (var i = 0; i < r_max; i++) { if (i != r) $("r").add(new Option(i.toString(), i)); } const br = document.createElement("br"); $("div2").innerHTML = ""; var table = document.createElement("table"); table.id = "table0" table.align = "center"; table.style = "overflow:visible;height:96px;width: 80%;border-collapse:collapse;border-spacing:0;border: 3px solid #000000;table-layout:fixed;word-break:break-all;" for (var i = 0; i < table_m; i++) { var tr = document.createElement("tr"); for (var j = 0; j < table_n; j++) { var td = document.createElement("td"); td.id = "td_" + (i * table_n + j); td.style.height = "96px"; td.style.overflow = "unset"; var card_img = document.createElement("img"); card_img.id = "card_" + (i * table_n + j); card_img.src = base64_poker_back; card_img.style = "width:100%;height:auto;"; card_img.addEventListener("mousedown", function () { flip_card(Number(this.id.split("_")[1]), id_0); id_0 = Number(this.id.split("_")[1]); }); var card_txt = document.createElement("div"); card_txt.id = "card_txt_" + (i * table_n + j); card_txt.style = "display:none;width:100%;height:100%;text-align:center;vertical-align:middle;overflow:scroll;"; card_txt.innerHTML = ""; card_txt.align = "center"; td.appendChild(card_txt); td.appendChild(card_img); tr.appendChild(td); } table.appendChild(tr); } $("div2").appendChild(table); td_height = Math.min($("card_0").clientHeight, Math.floor((Number(document.body.clientHeight) - Number($("div1").offsetHeight)) / table_m)); cards_shuffle(); } ``` -------------------------------- ### Organize Built Lodash Files and Modularize Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/lodash/release.md After the build process, these commands create a temporary directory, copy the generated `lodash` files into it, and then use `lodash-cli` to modularize the project. Finally, it copies the modularized and core files back to their intended locations. ```shell mkdir ../lodash-temp cp lodash.js dist/lodash.min.js dist/lodash.core.js dist/lodash.core.min.js ../lodash-temp/ node ../lodash-cli/bin/lodash modularize exports=node -o . cp ../lodash-temp/lodash.core.js core.js cp ../lodash-temp/lodash.core.min.js core.min.js cp ../lodash-temp/lodash.js lodash.js cp ../lodash-temp/lodash.min.js lodash.min.js ``` -------------------------------- ### Use bluebird-co as tj/co Drop-in Replacement Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Demonstrates how `bluebird-co` can be imported and used as a direct replacement for `tj/co`. It provides the familiar `co` and `co.wrap` functionalities, allowing for easy migration or interoperability. ```javascript import {co} from 'bluebird-co'; co(...); co.wrap(...); ``` -------------------------------- ### Configure Babel 6 for Async/Await with bluebird-co Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Illustrates how to configure Babel 6's `transform-async-to-module-method` plugin to use `bluebird-co` for `async/await` transformation. This configuration is placed in the `.babelrc` file to direct Babel's behavior. ```javascript { "plugins": [ ["transform-async-to-module-method", { "module": "bluebird-co", "method": "coroutine" }] ] } ``` -------------------------------- ### Integrate PaddleLite and OpenCV Libraries Source: https://github.com/autox-community/autox/blob/master/paddleocr/src/main/cpp/CMakeLists.txt Configures the paths for PaddleLite and OpenCV SDKs, includes their respective header directories, and finds the OpenCV package required for the build. ```CMake set(PaddleLite_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../PaddleLite") include_directories(${PaddleLite_DIR}/cxx/include) set(OpenCV_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../OpenCV/sdk/native/jni") message(STATUS "opencv dir: ${OpenCV_DIR}") find_package(OpenCV REQUIRED) message(STATUS "OpenCV libraries: ${OpenCV_LIBS}") include_directories(${OpenCV_INCLUDE_DIRS}) ``` -------------------------------- ### Automatically Bootstrap bluebird-co Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Demonstrates the simplest way to integrate bluebird-co by requiring it. This action automatically adds its yield handler to Bluebird, making it ready for use without further configuration. ```javascript require('bluebird-co'); ``` -------------------------------- ### Define Native Library and Import PaddleLite Shared Library Source: https://github.com/autox-community/autox/blob/master/paddleocr/src/main/cpp/CMakeLists.txt Defines the main 'Native' shared library from collected source files, locates the Android 'log' NDK library, and imports a prebuilt PaddleLite shared library, setting its imported location. ```CMake add_library( # Sets the name of the library. Native # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ${SOURCES}) find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that you want CMake to locate. log) add_library( # Sets the name of the library. paddle_light_api_shared # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). IMPORTED) set_target_properties( # Specifies the target library. paddle_light_api_shared # Specifies the parameter you want to define. PROPERTIES IMPORTED_LOCATION ${PaddleLite_DIR}/cxx/libs/${ANDROID_ABI}/libpaddle_light_api_shared.so # Provides the path to the library you want to import. ) ``` -------------------------------- ### Link External and System Libraries to Native Target Source: https://github.com/autox-community/autox/blob/master/paddleocr/src/main/cpp/CMakeLists.txt Specifies all libraries that CMake should link to the 'Native' target library, including PaddleLite, OpenCV, Android system libraries (GLESv2, EGL, jnigraphics), and the log library. ```CMake target_link_libraries( # Specifies the target library. Native paddle_light_api_shared ${OpenCV_LIBS} GLESv2 EGL jnigraphics ${log-lib} ) ``` -------------------------------- ### Core Utility Methods for MlKitOcrResult in Kotlin Source: https://github.com/autox-community/autox/blob/master/app/src/main/assets/sample/GoogleMLKit/API.md This snippet provides a collection of essential methods for the `MlKitOcrResult` class, designed to facilitate common operations on OCR data structures. It includes functions for recursive searching (`find`), filtering (`filter`), converting the hierarchical structure into a flat list (`toArray`), and sorting the results, both in-place (`sort`) and by returning a new sorted instance (`sorted`). These methods are crucial for navigating and processing complex OCR output. ```kotlin //kotlin //递归查找 fun find(predicate: (MlKitOcrResult) -> Boolean): MlKitOcrResult? //递归查找,level:层级 fun find(level: Int, predicate: (MlKitOcrResult) -> Boolean): MlKitOcrResult? //递归过滤 fun filter(predicate: (MlKitOcrResult) -> Boolean): List //递归过滤,level:层级 fun filter(level: Int, predicate: (MlKitOcrResult) -> Boolean): List //转数组,level:层级 fun toArray(level: Int): List //转数组 fun toArray(): List //对对象本身排序 fun sort() //排序,返回新对象 fun sorted(): GoogleMLKitOcrResult } ``` -------------------------------- ### JavaScript: Shuffle Game Cards Source: https://github.com/autox-community/autox/blob/master/app/src/main/assets/sample/Web扩展与游戏编程/game.html This function initializes and shuffles the cards for the memory game. It resets the flip counter, populates the `card` and `card_pair` arrays based on the `game_dict` and game board dimensions, ensuring pairs are created. Finally, it shuffles the cards randomly and sets their initial display to the backside image. ```javascript function cards_shuffle() { $("flip_times").innerHTML = 0; card = []; card_pair = []; unit_number = table_m * table_n; if (unit_number % 2 == 1) unit_number -= 1 for ( var i = r * unit_number; i < unit_number * (r + 1); i++ ) { if ($("game_dict").value == "POKER") { if (i % 2 == 0) card.push(Object.values(game_dict)[Math.floor(i / 2) % (Object.keys(game_dict).length)]); if (i % 2 == 1) card.push(Object.values(game_dict)[Math.floor(i / 2) % (Object.keys(game_dict).length)]); } else { if (i % 2 == 0) card.push(Object.keys(game_dict)[Math.floor(i / 2) % (Object.keys(game_dict).length)]); if (i % 2 == 1) card.push(game_dict[Object.keys(game_dict)[Math.floor(i / 2) % (Object.keys(game_dict).length)]]); } } for (var i = 1; i <= (unit_number) / 2; i++) { card_pair.push(i, i); } while ((card.length < table_m * table_n) || (card_pair.length < table_m * table_n)) { card.push("") card_pair.push(-4); } for (var i = 0; i < table_m * table_n; i++) { $("card_" + i).src = base64_poker_back; $("card_" + i).style = "display:block;width:100%;height:auto;" $("card_txt_" + i).style = "display:none;width:100%;height:100%;text-align:center;vertical-align:middle;overflow:scroll;" $("td_" + i).style = "height:" + td_height + "px;" // $("card_txt_" + i).innerHTML = ""; var a = Math.floor(Math.random() * table_m * table_n); var b = Math.floor(Math.random() * table_m * table_n); var temp = card[a]; card[a] = card[b]; card[b] = temp; var temp = card_pair[a]; card_pair[a] = card_pair[b]; card_pair[b] = temp; } } ``` -------------------------------- ### JavaScript Thunk Implementation and Usage Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md Demonstrates a basic thunk function that returns a value asynchronously via a callback, and its usage within an `async` function using `await` to retrieve the resolved value. This pattern is common in older asynchronous JavaScript paradigms. ```javascript function get(value) { return function(done) { done(null, value); //single argument } } async function() { let value = await get(10); console.log(value); //10 } ``` -------------------------------- ### Configure Minimum CMake Version and Source Collection Source: https://github.com/autox-community/autox/blob/master/paddleocr/src/main/cpp/CMakeLists.txt Sets the minimum required CMake version for the project and collects all source files in the current directory to be included in the native library build. ```CMake cmake_minimum_required(VERSION 3.4.1) aux_source_directory(. SOURCES) ``` -------------------------------- ### JavaScript: Game Dictionary Configuration Source: https://github.com/autox-community/autox/blob/master/app/src/main/assets/sample/Web扩展与游戏编程/game.html This JavaScript object, `game_dicts`, serves as a configuration for different game types. Currently, it defines the 'POKER' game, mapping card names (e.g., '大王') to their corresponding base64 encoded image data. This structure allows for easy expansion with other game themes and their associated assets. ```javascript var game_dicts = { "POKER": { "大王": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEcAAABgCAYAAABPGW+RAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAAAlwSFlzAAAK7wAACu8BfXaKSAAAG9JJREFUeF7tnHvMZVV5xgfaJkRpSkcYa22RsRImoogYUykyCigXccSxSNRaNAq1bWIDGGovgqkMYqnOcGmMiWKhNd4A5RK8EAyMGi+MEwVEo0DNIJ8FrV8JOF8jbVbX713rWftd66y9z/mw/kVPsrP3OWefvdd61vM+72WtffZYM7yCO36sH+7hAQj//xoQiMAUooTd/7UUVlb+M+3Dsp3FcfW5vv8l97ruavalbb/kvVdzHQFUgAkRmqWlXeHSD78v3HX3tyNEywNosWGrufgYsP8X1/hVDFrbrgGcDAKMAZTjTtwYduzYEd+tFPbAKDWKYy6mfdvY9nv/fuYa7jqP5nq+HVP3Xe15BRw1GHC+c8/O8JbTXp+Zs1KBMAVI2+lH+36UcS2Lf8XvCzgwBFO67c4vm1kBzgPL359hjoGT7d6zah5z+H7GRFfJxHlgG2varcPuip3OAqS3IoADJxg4gPLGN/+R7f/j4fuSOK/8rDafkRFrTaJthG7e3c/rhDe9jhn" } } ``` -------------------------------- ### Copy Dependent Shared Libraries Post-Build Source: https://github.com/autox-community/autox/blob/master/paddleocr/src/main/cpp/CMakeLists.txt Defines custom post-build commands to copy various PaddleLite and HIAI shared libraries from their source directories to the build output directory, ensuring they are available for the Android package. ```CMake add_custom_command( TARGET Native POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PaddleLite_DIR}/cxx/libs/${ANDROID_ABI}/libc++_shared.so ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libc++_shared.so) add_custom_command( TARGET Native POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PaddleLite_DIR}/cxx/libs/${ANDROID_ABI}/libpaddle_light_api_shared.so ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libpaddle_light_api_shared.so) add_custom_command( TARGET Native POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PaddleLite_DIR}/cxx/libs/${ANDROID_ABI}/libhiai.so ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libhiai.so) add_custom_command( TARGET Native POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PaddleLite_DIR}/cxx/libs/${ANDROID_ABI}/libhiai_ir.so ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libhiai_ir.so) add_custom_command( TARGET Native POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PaddleLite_DIR}/cxx/libs/${ANDROID_ABI}/libhiai_ir_build.so ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libhiai_ir_build.so) ``` -------------------------------- ### Define and Use JavaScript Generator Functions Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md Illustrates the creation of basic and complex JavaScript generator functions using the `function*` syntax. The `test` generator yields promises, while `complex_generator` demonstrates nested yields and handling of asynchronous values within a generator. These functions produce a sequence of values, potentially asynchronously. ```javascript function* test(iterations){ let i = 0; while(i++ < iterations) { yield Promise.resolve(i); } } async function() { await test(100); } //what even is this function* complex_generator( iterations ) { let test3 = new Array( iterations ); for( let i = 0; i < iterations; i++ ) { test3[i] = Promise.resolve( i ); } for( let i = 0; i < iterations; i++ ) { yield [yield Promise.resolve( i ), { test: yield Promise.resolve( i ), test2: Promise.resolve( i + 1 ), test3: test3 }]; } } ``` -------------------------------- ### APIDOC: bluebird-co.coroutine(gfn) Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Wraps a GeneratorFunction using Bluebird.coroutine, returning a new function. When the returned function is invoked, it executes the generator and returns a Promise. This method provides aliases like `.wrap` and `.co.wrap` for compatibility with `co.wrap`. ```APIDOC .coroutine(gfn : GeneratorFunction) -> Function alias: .wrap(gfn : GeneratorFunction) -> Function alias: .co.wrap(gfn : GeneratorFunction) -> Function ``` -------------------------------- ### Set C++ Compiler and Shared Linker Flags Source: https://github.com/autox-community/autox/blob/master/paddleocr/src/main/cpp/CMakeLists.txt Applies specific C++ compiler flags for optimization (fast-math, Ofast, Os) and visibility control, along with shared linker flags for garbage collection and relocation handling. ```CMake set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ffast-math -Ofast -Os" ) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility=hidden -fvisibility-inlines-hidden -fdata-sections -ffunction-sections" ) set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections -Wl,-z,nocopyreloc") ``` -------------------------------- ### JavaScript Asynchronous Error Handling Patterns Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md Illustrates different scenarios for handling errors in asynchronous JavaScript contexts, including top-level errors from awaiting an undefined value, nested errors within a generator function, and deep errors that occur after many iterations within a generator. ```javascript //Top level error async function() { await undefined; } //nested error async function() { await function*() { yield undefined; } } //deep error async function() { let i = 0; await function*() { if(i++ > 2000) throw new Error(); yield Promise.resolve(i); } } ``` -------------------------------- ### JavaScript: Card Flip Game Logic Source: https://github.com/autox-community/autox/blob/master/app/src/main/assets/sample/Web扩展与游戏编程/game.html This snippet contains the core logic executed when a card is flipped in the memory game. It checks for matches between the current card and a previously flipped card, updates game state (like `card_pair` values), manages card visibility (showing/hiding text), and handles game-over conditions such as exceeding the maximum number of flips. ```javascript if (id_0 >= 0) { if (id != id_0) { if (card_pair[id] === card_pair[id_0]) { try { auto0.invoke('mFunction', "✔"); } catch (e) { } card_pair[id] = "-1"; card_pair[id_0] = "-1"; card_txt_show(id); card_txt_show(id_0); } else { // try { auto0.invoke('mFunction', "✘"); } // catch (e) { } setTimeout("card_txt_hide(" + id + ")", Math.max(1000, (Math.min(5000, card[id].length * 100)))); card_txt_hide(id_0); } } else { setTimeout("card_txt_hide(" + id + ")", Math.max(1000, (card[id].length * 200))); } } else { setTimeout("card_txt_hide(" + id + ")", Math.max(1000, (card[id].length * 200))); } checkSuccess(); if (Number($("flip_times").innerHTML) > table_m * table_n * 3) { alert("超过最大翻牌次数" + (table_m * table_n * 3).toString() + ",将重新洗牌!") cards_shuffle(); } id_0 = id ``` -------------------------------- ### API: .isThenable(value) and .isPromise(value) Methods Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Checks if a given value is a 'thenable' (i.e., has a `.then` method), which is a common characteristic of Promises. The method `.isPromise(value)` is an alias for `.isThenable(value)`. ```APIDOC .isThenable(value: any): boolean alias: .isPromise(value: any): boolean ``` ```JavaScript function isThenable(value) { return value && typeof value.then === 'function'; } ``` -------------------------------- ### Generate ES Module Exports for Lodash Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/lodash/release.md This command specifically uses the `lodash-cli` to generate ES module (ECMAScript module) exports for the `lodash` library, outputting them to the current directory. ```shell node ../lodash-cli/bin/lodash modularize exports=es -o . ``` -------------------------------- ### Import Lodash modules in Node.js Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/lodash/README.md Illustrates different ways to import Lodash in Node.js, including the full build, core build, functional programming (FP) build, specific method categories, and cherry-picking individual methods for bundle size optimization. ```javascript // Load the full build. var _ = require('lodash'); // Load the core build. var _ = require('lodash/core'); // Load the FP build for immutable auto-curried iteratee-first data-last methods. var fp = require('lodash/fp'); // Load method categories. var array = require('lodash/array'); var object = require('lodash/fp/object'); // Cherry-pick methods for smaller browserify/rollup/webpack bundles. var at = require('lodash/at'); var curryN = require('lodash/fp/curryN'); ``` -------------------------------- ### Asynchronous Iteration of ES6 Set with bluebird-co Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md Illustrates how the `bluebird-co` library can automatically resolve asynchronous values (Promises) embedded within an ES6 `Set` during iteration. This simplifies handling data structures that contain a mix of synchronous and asynchronous elements, providing a resolved array of values. ```javascript let mySet = new Set( [Promise.resolve( 1 ), 2, [Promise.resolve( 3 ), 4], 5] ); async function() { let values = await mySet.values(); console.log(values); //[1, 2, [3, 4], 5] } ``` -------------------------------- ### Await Multiple Asynchronous Operations in a JavaScript Object Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/benchmark/README.md This snippet demonstrates how to 'await' an object whose properties are asynchronous function calls, promises, or literal values. This enables concurrent execution of multiple named async operations, collecting their results into an object, which is useful for structured data retrieval. ```javascript async function() { let res = await { a: asyncFunc1(), b: asyncFunc2(), c: somePromise, d: 42 }; } ``` -------------------------------- ### APIDOC: bluebird-co.addYieldHandler(fn) Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Enables the addition of custom logic for processing yielded values, similar to Bluebird's `addYieldHandler`. This function allows `bluebird-co` to handle custom types in conjunction with its built-in yieldable types, including nested structures. Note that built-in yield handlers cannot be overridden, and there are caveats regarding `Object` types in the prototype chain. ```APIDOC .addYieldHandler(fn : Function) alias: .coroutine.addYieldHandler(fn : Function) ``` -------------------------------- ### Manually Add bluebird-co Yield Handler Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Shows how to manually add bluebird-co's yield handler to Bluebird. This method provides more control over the integration process, allowing developers to explicitly manage when and how the handler is applied. ```javascript var Promise = require('bluebird'), bluebird_co = require('bluebird-co/manual'); Promise.coroutine.addYieldHandler(bluebird_co.toPromise); var fn = Promise.coroutine(function*(){ //do stuff }); fn().then(...); ``` -------------------------------- ### APIDOC: bluebird-co.toPromise(value) Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md The core function of `bluebird-co`, designed to convert various supported yieldable types into a Promise. If the given value cannot be transformed into a Promise, the original value is returned. It ensures that any nested Promises within the value are resolved before the final Promise resolves. ```APIDOC .toPromise(value : any) -> Promise | any ``` -------------------------------- ### Supported Yieldable Types for bluebird-co Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Lists the various data types that `bluebird-co`'s yield handler can process. This includes promises, arrays, objects, generators, iterables, and functions (thunks), along with custom types and nested combinations. ```APIDOC Promises Arrays Objects Generators and GeneratorFunctions Iterables (like new Set([1, 2, 3]).values()) Functions (as Thunks) Custom data types via .addYieldHandler(fn) Any combination or nesting of the above. ``` -------------------------------- ### API: .coroutine.yieldHandlers Property Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Exposes all custom yield handlers that have been added to bluebird-co. This property is an array of functions and is expected to be an array by bluebird-co. ```APIDOC .coroutine.yieldHandlers: Array ``` -------------------------------- ### API: .isGenerator(value) Method Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Determines if the provided value is a generator instance, specifically checking for the presence of `.next` and `.throw` methods. ```APIDOC .isGenerator(value: any): boolean ``` -------------------------------- ### JavaScript: Access bluebird-co Yield Handlers Array Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Shows how to directly access the internal array of registered yield handlers within `bluebird-co`. This can be useful for debugging, inspection, or programmatically removing previously added custom handlers. ```javascript console.log(coroutine.yieldHandlers); //array of functions ``` -------------------------------- ### API: .isGeneratorFunction(value) Method Source: https://github.com/autox-community/autox/blob/master/autojs/src/main/assets/modules/npm/bluebird-co/README.md Verifies if the given value is a JavaScript `GeneratorFunction`. ```APIDOC .isGeneratorFunction(value: any): boolean ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.