from flask import Flask, request, jsonify, render_template_string from sentence_transformers import SentenceTransformer, util import logging import sys import signal # 初始化 Flask 应用 app = Flask(__name__) # 配置日志,级别设为 INFO logging.basicConfig(level=logging.INFO) app.logger = logging.getLogger("CodeSearchAPI") # 预定义代码片段 CODE_SNIPPETS = [ "void printText(const std::string& text) { std::cout << text; }", "int sum(int a, int b) { return a + b; }", "int generateRandomNumber() { return rand(); }", "bool isEven(int num) { return num % 2 == 0; }", "size_t getStringLength(const std::string& str) { return str.length(); }", "std::string getCurrentDate() { time_t now = time(0); return ctime(&now); }", "bool fileExists(const std::string& filename) { std::ifstream file(filename); return file.good(); }", "std::string readFileContent(const std::string& filename) { std::ifstream file(filename); std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); return content; }", "void writeToFile(const std::string& filename, const std::string& content) { std::ofstream file(filename); file << content; }", "std::string getCurrentTime() { time_t now = time(0); return ctime(&now); }", "std::string toUpper(const std::string& str) { std::string result = str; std::transform(result.begin(), result.end(), result.begin(), ::toupper); return result; }", "std::string toLower(const std::string& str) { std::string result = str; std::transform(result.begin(), result.end(), result.begin(), ::tolower); return result; }", "std::string reverseString(const std::string& str) { std::string result = str; std::reverse(result.begin(), result.end()); return result; }", "size_t countListElements(const std::vector& list) { return list.size(); }", "int findMax(const std::vector& list) { return *std::max_element(list.begin(), list.end()); }", "int findMin(const std::vector& list) { return *std::min_element(list.begin(), list.end()); }", "void sortList(std::vector& list) { std::sort(list.begin(), list.end()); }", "std::vector mergeLists(const std::vector& list1, const std::vector& list2) { std::vector result = list1; result.insert(result.end(), list2.begin(), list2.end()); return result; }", "void removeElementFromList(std::vector& list, int element) { list.erase(std::remove(list.begin(), list.end(), element), list.end()); }", "bool isListEmpty(const std::vector& list) { return list.empty(); }", "size_t countCharInString(const std::string& str, char ch) { return std::count(str.begin(), str.end(), ch); }", "bool containsSubstring(const std::string& str, const std::string& substr) { return str.find(substr) != std::string::npos; }", "std::string numToString(int num) { return std::to_string(num); }", "int stringToNum(const std::string& str) { return std::stoi(str); }", "bool isNumeric(const std::string& str) { return !str.empty() && std::all_of(str.begin(), str.end(), ::isdigit); }", "int getIndexInList(const std::vector& list, int element) { auto it = std::find(list.begin(), list.end(), element); return it != list.end() ? std::distance(list.begin(), it) : -1; }", "void clearList(std::vector& list) { list.clear(); }", "void reverseList(std::vector& list) { std::reverse(list.begin(), list.end()); }", "std::vector removeDuplicatesFromList(const std::vector& list) { std::set s(list.begin(), list.end()); return std::vector(s.begin(), s.end()); }", "bool isInList(const std::vector& list, int value) { return std::find(list.begin(), list.end(), value) != list.end(); }", "std::map createDict() { return {}; }", "void addToDict(std::map& dict, const std::string& key, int value) { dict[key] = value; }", "void removeKeyFromDict(std::map& dict, const std::string& key) { dict.erase(key); }", "std::vector getDictKeys(const std::map& dict) { std::vector keys; for (const auto& pair : dict) keys.push_back(pair.first); return keys; }", "std::vector getDictValues(const std::map& dict) { std::vector values; for (const auto& pair : dict) values.push_back(pair.second); return values; }", "std::map mergeDicts(const std::map& dict1, const std::map& dict2) { std::map result = dict1; result.insert(dict2.begin(), dict2.end()); return result; }", "bool isDictEmpty(const std::map& dict) { return dict.empty(); }", "int getValueFromDict(const std::map& dict, const std::string& key) { return dict.at(key); }", "bool keyExistsInDict(const std::map& dict, const std::string& key) { return dict.find(key) != dict.end(); }", "void clearDict(std::map& dict) { dict.clear(); }", "size_t countFileLines(const std::string& filename) { std::ifstream file(filename); return std::count(std::istreambuf_iterator(file), std::istreambuf_iterator(), '\n'); }", "void writeListToFile(const std::string& filename, const std::vector& list) { std::ofstream file(filename); for (int elem : list) file << elem << std::endl; }", "std::vector readListFromFile(const std::string& filename) { std::ifstream file(filename); std::vector list; int elem; while (file >> elem) list.push_back(elem); return list; }", "size_t countWordsInFile(const std::string& filename) { std::ifstream file(filename); std::string word; size_t count = 0; while (file >> word) count++; return count; }", "bool isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }", "std::string formatTime(const std::string& format) { char buffer[80]; time_t now = time(0); strftime(buffer, sizeof(buffer), format.c_str(), localtime(&now)); return buffer; }", "int daysBetweenDates(const std::string& date1, const std::string& date2) { struct tm tm1 = {}, tm2 = {}; strptime(date1.c_str(), \"%Y-%m-%d\", &tm1); strptime(date2.c_str(), \"%Y-%m-%d\", &tm2); time_t time1 = mktime(&tm1), time2 = mktime(&tm2); return difftime(time2, time1) / (60 * 60 * 24); }", "std::string getCurrentWorkingDirectory() { char buffer[FILENAME_MAX]; getcwd(buffer, FILENAME_MAX); return buffer; }", "std::vector listFilesInDirectory(const std::string& path) { std::vector files; for (const auto& entry : std::filesystem::directory_iterator(path)) files.push_back(entry.path().filename().string()); return files; }", "void createDirectory(const std::string& path) { std::filesystem::create_directory(path); }", "void deleteDirectory(const std::string& path) { std::filesystem::remove_all(path); }", "bool isFile(const std::string& path) { return std::filesystem::is_regular_file(path); }", "bool isDirectory(const std::string& path) { return std::filesystem::is_directory(path); }", "size_t getFileSize(const std::string& filename) { return std::filesystem::file_size(filename); }", "void renameFile(const std::string& oldName, const std::string& newName) { std::filesystem::rename(oldName, newName); }", "void copyFile(const std::string& src, const std::string& dest) { std::filesystem::copy(src, dest); }", "void moveFile(const std::string& src, const std::string& dest) { std::filesystem::rename(src, dest); }", "void deleteFile(const std::string& filename) { std::filesystem::remove(filename); }", "std::string getEnvVariable(const std::string& var) { const char* value = std::getenv(var.c_str()); return value ? value : \"\"; }", "void setEnvVariable(const std::string& var, const std::string& value) { setenv(var.c_str(), value.c_str(), 1); }", "void openWebLink(const std::string& url) { std::string command = \"xdg-open \" + url; system(command.c_str()); }", "std::string sendGetRequest(const std::string& url) { std::string command = \"curl -s \" + url; std::string result; FILE* pipe = popen(command.c_str(), \"r\"); char buffer[128]; while (fgets(buffer, sizeof(buffer), pipe) != NULL) result += buffer; pclose(pipe); return result; }", "nlohmann::json parseJson(const std::string& jsonStr) { return nlohmann::json::parse(jsonStr); }", "void writeJsonToFile(const std::string& filename, const nlohmann::json& jsonData) { std::ofstream file(filename); file << jsonData.dump(4); }", "nlohmann::json readJsonFromFile(const std::string& filename) { std::ifstream file(filename); return nlohmann::json::parse(file); }", "std::string listToString(const std::vector& list) { std::string result; for (const auto& elem : list) result += elem; return result; }", "std::vector stringToList(const std::string& str) { std::vector list; std::stringstream ss(str); std::string item; while (std::getline(ss, item, ' ')) list.push_back(item); return list; }", "std::string joinListWithComma(const std::vector& list) { std::string result; for (size_t i = 0; i < list.size(); i++) { result += list[i]; if (i != list.size() - 1) result += \",\"; } return result; }", "std::string joinListWithNewline(const std::vector& list) { std::string result; for (const auto& elem : list) result += elem + \"\\n\"; return result; }", "std::vector splitStringBySpace(const std::string& str) { std::vector tokens; std::stringstream ss(str); std::string token; while (ss >> token) tokens.push_back(token); return tokens; }", "std::vector splitStringByDelimiter(const std::string& str, char delimiter) { std::vector tokens; std::stringstream ss(str); std::string token; while (std::getline(ss, token, delimiter)) tokens.push_back(token); return tokens; }", "std::vector splitStringToChars(const std::string& str) { return std::vector(str.begin(), str.end()); }", "std::string replaceInString(const std::string& str, const std::string& oldStr, const std::string& newStr) { std::string result = str; size_t pos = 0; while ((pos = result.find(oldStr, pos)) != std::string::npos) { result.replace(pos, oldStr.length(), newStr); pos += newStr.length(); } return result; }", "std::string removeSpaces(const std::string& str) { std::string result = str; result.erase(std::remove(result.begin(), result.end(), ' '), result.end()); return result; }", "std::string removePunctuation(const std::string& str) { std::string result = str; result.erase(std::remove_if(result.begin(), result.end(), ::ispunct), result.end()); return result; }", "bool isStringEmpty(const std::string& str) { return str.empty(); }", "bool isPalindrome(const std::string& str) { std::string reversed = str; std::reverse(reversed.begin(), reversed.end()); return str == reversed; }", "void writeToCsv(const std::string& filename, const std::vector>& data) { std::ofstream file(filename); for (const auto& row : data) { for (size_t i = 0; i < row.size(); i++) { file << row[i]; if (i != row.size() - 1) file << \",\"; } file << \"\\n\"; } }", "std::vector> readFromCsv(const std::string& filename) { std::vector> data; std::ifstream file(filename); std::string line; while (std::getline(file, line)) { std::vector row; std::stringstream ss(line); std::string cell; while (std::getline(ss, cell, ',')) row.push_back(cell); data.push_back(row); } return data; }", "size_t countCsvLines(const std::string& filename) { std::ifstream file(filename); return std::count(std::istreambuf_iterator(file), std::istreambuf_iterator(), '\n'); }", "void shuffleList(std::vector& list) { std::shuffle(list.begin(), list.end(), std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count())); }", "int pickRandomElement(const std::vector& list) { return list[rand() % list.size()]; }", "std::vector pickRandomElements(const std::vector& list, size_t count) { std::vector result = list; std::shuffle(result.begin(), result.end(), std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count())); result.resize(count); return result; }", "int rollDice() { return rand() % 6 + 1; }", "std::string flipCoin() { return rand() % 2 == 0 ? \"Heads\" : \"Tails\"; }", "std::string generateRandomPassword(size_t length) { const std::string chars = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\"; std::string password; for (size_t i = 0; i < length; i++) password += chars[rand() % chars.length()]; return password; }", "std::string generateRandomColor() { const std::string hexChars = \"0123456789ABCDEF\"; std::string color = \"#\"; for (int i = 0; i < 6; i++) color += hexChars[rand() % hexChars.length()]; return color; }", "std::string generateUniqueId() { return std::to_string(std::chrono::system_clock::now().time_since_epoch().count()); }", "class MyClass {};", "MyClass createClassInstance() { return MyClass(); }", "class MyClass { public: void myMethod() {} };", "class MyClass { public: int myProperty; };", "class ChildClass : public MyClass {};", "class ChildClass : public MyClass { public: void myMethod() override {} };", "class MyClass { public: static void myClassMethod() {} };", "class MyClass { public: static void myStaticMethod() {} };", "template bool isType(const T& obj, const std::type_info& type) { return typeid(obj) == type; }", "template auto getProperty(const T& obj, const std::string& prop) { return obj.*prop; }", "template void setProperty(T& obj, const std::string& prop, const auto& value) { obj.*prop = value; }", "template void deleteProperty(T& obj, const std::string& prop) { obj.*prop = nullptr; }", "void handleException() { try { throw std::runtime_error(\"Error occurred\"); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; }}", "void throwCustomException() { throw std::runtime_error(\"Custom error\"); }", "void getExceptionInfo() { try { throw std::runtime_error(\"Error occurred\"); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; }}", "void logError(const std::string& message) { std::cerr << \"Error: \" << message << std::endl; }", "class Timer { public: Timer() : start(std::chrono::high_resolution_clock::now()) {} double elapsed() { return std::chrono::duration(std::chrono::high_resolution_clock::now() - start).count(); } private: std::chrono::time_point start; };", "double getRuntime() { static Timer timer; return timer.elapsed(); }", "void printProgressBar(int progress, int total) { float percentage = static_cast(progress) / total; int barWidth = 50; std::cout << \"[\"; int pos = barWidth * percentage; for (int i = 0; i < barWidth; ++i) { if (i < pos) std::cout << \"=\"; else if (i == pos) std::cout << \">\"; else std::cout << \" \"; } std::cout << \"] \" << int(percentage * 100.0) << \" %\\r\"; std::cout.flush(); }", "void delay(int milliseconds) { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); }", "auto lambda = [](int x) { return x * x; };", "std::vector mapFunc(const std::vector& vec, std::function func) { std::vector result; for (int x : vec) result.push_back(func(x)); return result; }", "std::vector filterFunc(const std::vector& vec, std::function func) { std::vector result; for (int x : vec) if (func(x)) result.push_back(x); return result; }", "int reduceFunc(const std::vector& vec, std::function func, int init) { int result = init; for (int x : vec) result = func(result, x); return result; }", "std::vector listComprehension(const std::vector& vec) { std::vector result; for (int x : vec) if (x % 2 == 0) result.push_back(x); return result; }", "std::map dictComprehension(const std::vector& vec) { std::map result; for (int x : vec) result[x] = x * x; return result; }", "std::set setComprehension(const std::vector& vec) { std::set result; for (int x : vec) if (x % 2 == 0) result.insert(x); return result; }", "std::set setIntersection(const std::set& set1, const std::set& set2) { std::set result; std::set_intersection(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(result, result.begin())); return result; }", "std::set setUnion(const std::set& set1, const std::set& set2) { std::set result; std::set_union(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(result, result.begin())); return result; }", "std::set setDifference(const std::set& set1, const std::set& set2) { std::set result; std::set_difference(set1.begin(), set1.end(), set2.begin(), set2.end(), std::inserter(result, result.begin())); return result; }", "std::vector removeNullValues(const std::vector& vec) { std::vector result; for (int x : vec) if (x != 0) result.push_back(x); return result; }", "bool tryOpenFile(const std::string& filename) { std::ifstream file(filename); return file.is_open(); }", "template bool checkType(const T& var) { return typeid(var).name() == typeid(T).name(); }", "bool strToBool(const std::string& str) { return str == \"true\" || str == \"1\"; }", "void ifCondition(int x) { if (x > 0) std::cout << \"Positive\" << std::endl; }", "void whileLoop(int x) { while (x-- > 0) std::cout << x << std::endl; }", "void forLoopList(const std::vector& vec) { for (int x : vec) std::cout << x << std::endl; }", "void forLoopDict(const std::map& dict) { for (const auto& pair : dict) std::cout << pair.first << \": \" << pair.second << std::endl; }", "void forLoopString(const std::string& str) { for (char c : str) std::cout << c << std::endl; }", "void breakLoop() { for (int i = 0; i < 10; ++i) { if (i == 5) break; std::cout << i << std::endl; } }", "void continueLoop() { for (int i = 0; i < 10; ++i) { if (i == 5) continue; std::cout << i << std::endl; } }", "void defineFunction() { std::cout << \"Function defined\" << std::endl; }", "void functionWithDefault(int x = 10) { std::cout << x << std::endl; }", "std::pair returnMultipleValues() { return {1, 2}; }", "template void variadicFunction(Args... args) { (std::cout << ... << args) << std::endl; }", "void keywordArguments(int x, int y) { std::cout << x << \", \" << y << std::endl; }", "void logFunctionTime(std::function func) { Timer timer; func(); std::cout << \"Time elapsed: \" << timer.elapsed() << \"s\" << std::endl; }", "template void decorator(Func func) { std::cout << \"Before\" << std::endl; func(); std::cout << \"After\" << std::endl; }", "template auto cacheFunction(Func func) { static std::map cache; return [func](const std::string& key) { if (cache.find(key) == cache.end()) cache[key] = func(); return cache[key]; }; }", "class Generator { public: Generator() : value(0) {} int next() { return value++; } private: int value; };", "int yieldValue() { static int value = 0; return value++; }", "int getNextValue() { static int value = 0; return value++; }", "class Iterator { public: Iterator(const std::vector& vec) : vec(vec), index(0) {} int next() { return vec[index++]; } bool hasNext() { return index < vec.size(); } private: std::vector vec; int index; };", "void manualIterate(const std::vector& vec) { Iterator it(vec); while (it.hasNext()) std::cout << it.next() << std::endl; }", "void enumerateList(const std::vector& vec) { for (int i = 0; i < vec.size(); ++i) std::cout << i << \": \" << vec[i] << std::endl; }", "std::vector> zipLists(const std::vector& vec1, const std::vector& vec2) { std::vector> result; for (int i = 0; i < std::min(vec1.size(), vec2.size()); ++i) result.emplace_back(vec1[i], vec2[i]); return result; }", "std::map listsToDict(const std::vector& keys, const std::vector& values) { std::map result; for (int i = 0; i < std::min(keys.size(), values.size()); ++i) result[keys[i]] = values[i]; return result; }", "bool listsEqual(const std::vector& vec1, const std::vector& vec2) { return vec1 == vec2; }", "bool dictsEqual(const std::map& dict1, const std::map& dict2) { return dict1 == dict2; }", "bool setsEqual(const std::set& set1, const std::set& set2) { return set1 == set2; }", "std::vector removeDuplicatesList(const std::vector& vec) { std::set s(vec.begin(), vec.end()); return std::vector(s.begin(), s.end()); }", "void clearSet(std::set& s) { s.clear(); }", "bool isSetEmpty(const std::set& s) { return s.empty(); }", "void addToSet(std::set& s, int value) { s.insert(value); }", "void removeFromSet(std::set& s, int value) { s.erase(value); }", "bool setContains(const std::set& s, int value) { return s.find(value) != s.end(); }", "int setSize(const std::set& s) { return s.size(); }", "bool setsIntersect(const std::set& set1, const std::set& set2) { return !setIntersection(set1, set2).empty(); }", "bool isSubset(const std::vector& vec1, const std::vector& vec2) { std::set s1(vec1.begin(), vec1.end()), s2(vec2.begin(), vec2.end()); return std::includes(s2.begin(), s2.end(), s1.begin(), s1.end()); }", "bool isSubstring(const std::string& str, const std::string& substr) { return str.find(substr) != std::string::npos; }", "char firstChar(const std::string& str) { return str.empty() ? '\\0' : str[0]; }", "char lastChar(const std::string& str) { return str.empty() ? '\\0' : str.back(); }", "bool isTextFile(const std::string& filename) { std::ifstream file(filename); char c; while (file.get(c)) if (!std::isprint(c) && !std::isspace(c)) return false; return true; }", "bool isImageFile(const std::string& filename) { std::string ext = filename.substr(filename.find_last_of(\".\") + 1); return ext == \"jpg\" || ext == \"png\" || ext == \"gif\"; }", "double roundNumber(double num) { return std::round(num); }", "double ceilNumber(double num) { return std::ceil(num); }", "double floorNumber(double num) { return std::floor(num); }", "std::string formatDecimal(double num, int precision) { std::ostringstream oss; oss << std::fixed << std::setprecision(precision) << num; return oss.str(); }", "std::string generateRandomString(int length) { static const char alphanum[] = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"; std::string result; for (int i = 0; i < length; ++i) result += alphanum[rand() % (sizeof(alphanum) - 1)]; return result; }", "bool pathExists(const std::string& path) { std::ifstream file(path); return file.good(); }", "void traverseDirectory(const std::string& path) { for (const auto& entry : std::filesystem::directory_iterator(path)) std::cout << entry.path() << std::endl; }", "std::string getFileExtension(const std::string& filename) { return filename.substr(filename.find_last_of(\".\") + 1); }", "std::string getFileName(const std::string& path) { return path.substr(path.find_last_of(\"/\\\") + 1); }", "std::string getFullPath(const std::string& path) { return std::filesystem::absolute(path).string(); }", "std::string getPythonVersion() { return \"C++ does not have Python version\"; }", "std::string getSystemPlatform() { #ifdef _WIN32 return \"Windows\"; #elif __linux__ return \"Linux\"; #elif __APPLE__ return \"macOS\"; #else return \"Unknown\"; #endif }", "int getCPUCores() { return std::thread::hardware_concurrency(); }", "size_t getMemorySize() { return sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE); }", "std::string getDiskUsage() { struct statvfs stats; if (statvfs(\"/\", &stats) == 0) return std::to_string(stats.f_bsize * stats.f_bfree); return \"Unknown\"; }", "std::string getIPAddress() { struct ifaddrs* ifAddrStruct = nullptr; getifaddrs(&ifAddrStruct); std::string result; for (struct ifaddrs* ifa = ifAddrStruct; ifa != nullptr; ifa = ifa->ifa_next) { if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) { result = inet_ntoa(((struct sockaddr_in*)ifa->ifa_addr)->sin_addr); break; } } if (ifAddrStruct) freeifaddrs(ifAddrStruct); return result; }", "bool isConnectedToInternet() { return system(\"ping -c 1 google.com\") == 0; }", "void downloadFile(const std::string& url, const std::string& filename) { std::string command = \"curl -o \" + filename + \" \" + url; system(command.c_str()); }", "void uploadFile(const std::string& filename) { std::cout << \"File uploaded: \" << filename << std::endl; }", "void sendPostRequest(const std::string& url, const std::string& data) { std::string command = \"curl -X POST -d '\" + data + \"' \" + url; system(command.c_str()); }", "void sendRequestWithParams(const std::string& url, const std::map& params) { std::string command = \"curl -X GET \"; for (const auto& pair : params) command += \"-d \" + pair.first + \"=\" + pair.second + \" \"; command += url; system(command.c_str()); }", "void setRequestHeader(const std::string& url, const std::map& headers) { std::string command = \"curl -X GET \"; for (const auto& pair : headers) command += \"-H '\" + pair.first + \": \" + pair.second + \"' \"; command += url; system(command.c_str()); }", "void parseHTML(const std::string& html) { std::regex pattern(\"<[^>]*>\"); std::smatch matches; std::string result = std::regex_replace(html, pattern, \"\"); std::cout << result << std::endl; }", "std::string extractTitle(const std::string& html) { std::regex pattern(\"(.*?)\"); std::smatch matches; if (std::regex_search(html, matches, pattern)) return matches[1]; return \"\"; }", "std::vector extractLinks(const std::string& html) { std::regex pattern(\"\", std::regex_constants::icase); std::smatch matches; std::vector result; for (std::sregex_iterator it(html.begin(), html.end(), pattern), end; it != end; ++it) result.push_back((*it)[1]); return result; }", "void downloadImages(const std::string& html, const std::string& path) { std::regex pattern(\"]+src=\\\"(.*?)\\\"[^>]*>\", std::regex_constants::icase); std::smatch matches; for (std::sregex_iterator it(html.begin(), html.end(), pattern), end; it != end; ++it) downloadFile((*it)[1], path + \"/\" + getFileName((*it)[1])); }", "std::map countWordFrequency(const std::string& text) { std::map result; std::istringstream iss(text); std::string word; while (iss >> word) result[word]++; return result; }", "void simulateLogin(const std::string& url, const std::string& username, const std::string& password) { std::string command = \"curl -X POST -d 'username=\" + username + \"&password=\" + password + \"' \" + url; system(command.c_str()); }", "std::string htmlToText(const std::string& html) { std::regex pattern(\"<[^>]*>\"); return std::regex_replace(html, pattern, \"\"); }", "std::vector extractEmails(const std::string& text) { std::regex pattern(\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\"); std::smatch matches; std::vector result; for (std::sregex_iterator it(text.begin(), text.end(), pattern), end; it != end; ++it) result.push_back((*it)[0]); return result; }", "std::vector extractPhoneNumbers(const std::string& text) { std::regex pattern(\"\\\\+?\\\\d{1,4}[-.\\\\s]?\\\\d{1,4}[-.\\\\s]?\\\\d{1,9}\"); std::smatch matches; std::vector result; for (std::sregex_iterator it(text.begin(), text.end(), pattern), end; it != end; ++it) result.push_back((*it)[0]); return result; }", "std::vector findAllNumbers(const std::string& text) { std::regex pattern(\"\\\\d+\"); std::smatch matches; std::vector result; for (std::sregex_iterator it(text.begin(), text.end(), pattern), end; it != end; ++it) result.push_back((*it)[0]); return result; }", "std::string regexReplace(const std::string& text, const std::string& pattern, const std::string& replacement) { return std::regex_replace(text, std::regex(pattern), replacement); }", "bool matchesRegex(const std::string& text, const std::string& pattern) { return std::regex_match(text, std::regex(pattern)); }", "std::string removeHtmlTags(const std::string& html) { std::regex pattern(\"<[^>]*>\"); return std::regex_replace(html, pattern, \"\"); }", "std::string encodeHtmlEntities(const std::string& html) { std::string result; for (char c : html) { switch (c) { case '<': result += \"<\"; break; case '>': result += \">\"; break; case '&': result += \"&\"; break; case '\"': result += \""\"; break; case '\'': result += \"'\"; break; default: result += c; } } return result; }", "std::string decodeHtmlEntities(const std::string& html) { std::string result = html; result = std::regex_replace(result, std::regex(\"<\"), \"<\"); result = std::regex_replace(result, std::regex(\">\"), \">\"); result = std::regex_replace(result, std::regex(\"&\"), \"&\"); result = std::regex_replace(result, std::regex(\""\"), \"\\\"\"); result = std::regex_replace(result, std::regex(\"'\"), \"'\"); return result; }", "void createSimpleGUI() { Gtk::Window window; window.set_title(\"Simple GUI\"); window.set_default_size(200, 200); Gtk::Button button(\"Click Me\"); button.signal_clicked().connect([]() { std::cout << \"Button clicked\" << std::endl; }); window.add(button); window.show_all(); Gtk::Main::run(window); }", "void addButtonToWindow() { GtkWidget *button = gtk_button_new_with_label(\"Button\"); gtk_window_add(GTK_WINDOW(window), button); }", "void handleButtonClick() { g_signal_connect(button, \"clicked\", G_CALLBACK([]() { std::cout << \"Button clicked!\" << std::endl; }), NULL); }", "void showPopup() { GtkWidget *dialog = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, \"Popup Message\"); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); }", "std::string getTextBoxInput() { const gchar *text = gtk_entry_get_text(GTK_ENTRY(entry)); return std::string(text); }", "void setWindowTitle(const std::string& title) { gtk_window_set_title(GTK_WINDOW(window), title.c_str()); }", "void setWindowSize(int width, int height) { gtk_window_set_default_size(GTK_WINDOW(window), width, height); }", "void centerWindow() { gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); }", "void useMenuBar() { GtkWidget *menu_bar = gtk_menu_bar_new(); gtk_container_add(GTK_CONTAINER(window), menu_bar); }", "void createDropdown() { GtkWidget *combo = gtk_combo_box_text_new(); gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo), \"Option 1\"); gtk_container_add(GTK_CONTAINER(window), combo); }", "void useRadioButton() { GtkWidget *radio1 = gtk_radio_button_new_with_label(NULL, \"Option 1\"); gtk_container_add(GTK_CONTAINER(window), radio1); }", "void useCheckbox() { GtkWidget *check = gtk_check_button_new_with_label(\"Checkbox\"); gtk_container_add(GTK_CONTAINER(window), check); }", "void displayImage(const std::string& filePath) { GtkWidget *image = gtk_image_new_from_file(filePath.c_str()); gtk_container_add(GTK_CONTAINER(window), image); }", "void playAudio(const std::string& filePath) { system((\"mpg123 \" + filePath).c_str()); }", "void playVideo(const std::string& filePath) { system((\"vlc \" + filePath).c_str()); }", "int getCurrentPlaybackTime() { return 0; }", "void captureScreen() { system(\"import -window root screenshot.png\"); }", "void recordScreen(int duration) { system((\"ffmpeg -f x11grab -video_size 1920x1080 -i :0.0 -t \" + std::to_string(duration) + \" output.mp4\").c_str()); }", "std::pair getMousePosition() { return {0, 0}; }", "void simulateKeyboardInput(const std::string& input) { system((\"xdotool type \" + input).c_str()); }", "void simulateMouseClick(int x, int y) { system((\"xdotool mousemove \" + std::to_string(x) + \" \" + std::to_string(y) + \" click 1\").c_str()); }", "time_t getCurrentTimestamp() { return time(nullptr); }", "std::string timestampToDate(time_t timestamp) { char buffer[80]; strftime(buffer, 80, \"%Y-%m-%d\", localtime(×tamp)); return buffer; }", "time_t dateToTimestamp(const std::string& date) { struct tm tm; strptime(date.c_str(), \"%Y-%m-%d\", &tm); return mktime(&tm); }", "std::string getCurrentWeekday() { time_t now = time(nullptr); char buffer[80]; strftime(buffer, 80, \"%A\", localtime(&now)); return buffer; }", "int getDaysInMonth(int year, int month) { if (month == 2) return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28; else if (month == 4 || month == 6 || month == 9 || month == 11) return 30; else return 31; }", "std::string getFirstDayOfYear(int year) { char buffer[80]; strftime(buffer, 80, \"%Y-01-01\", localtime(&(time_t){0})); return buffer; }", "std::string getLastDayOfYear(int year) { char buffer[80]; strftime(buffer, 80, \"%Y-12-31\", localtime(&(time_t){0})); return buffer; }", "std::string getFirstDayOfMonth(int year, int month) { char buffer[80]; strftime(buffer, 80, \"%Y-%m-01\", localtime(&(time_t){0})); return buffer; }", "std::string getLastDayOfMonth(int year, int month) { int days = getDaysInMonth(year, month); char buffer[80]; snprintf(buffer, 80, \"%04d-%02d-%02d\", year, month, days); return buffer; }", "bool isWeekday() { time_t now = time(nullptr); struct tm* tm = localtime(&now); return tm->tm_wday >= 1 && tm->tm_wday <= 5; }", "bool isWeekend() { time_t now = time(nullptr); struct tm* tm = localtime(&now); return tm->tm_wday == 0 || tm->tm_wday == 6; }", "int getCurrentHour() { time_t now = time(nullptr); return localtime(&now)->tm_hour; }", "int getCurrentMinute() { time_t now = time(nullptr); return localtime(&now)->tm_min; }", "int getCurrentSecond() { time_t now = time(nullptr); return localtime(&now)->tm_sec; }", "void delay(int seconds) { sleep(seconds); }", "long getMillisecondTimestamp() { auto now = std::chrono::system_clock::now(); return std::chrono::duration_cast(now.time_since_epoch()).count(); }", "std::string formatTime(const std::string& format) { time_t now = time(nullptr); char buffer[80]; strftime(buffer, 80, format.c_str(), localtime(&now)); return buffer; }", "time_t parseTime(const std::string& timeStr, const std::string& format) { struct tm tm; strptime(timeStr.c_str(), format.c_str(), &tm); return mktime(&tm); }", "void createThread(void (*func)()) { std::thread t(func); t.detach(); }", "void pauseThread() { std::this_thread::sleep_for(std::chrono::seconds(1)); }", "void runFunctionInThread(void (*func)()) { std::thread t(func); t.join(); }", "std::string getCurrentThreadName() { return \"\"; }", "void setThreadAsDaemon() { }", "void synchronizeThreads() { std::mutex mtx; mtx.lock(); mtx.unlock(); }", "void createProcess() { if (fork() == 0) { exit(0); } }", "int getProcessPID() { return getpid(); }", "bool isProcessAlive(int pid) { return kill(pid, 0) == 0; }", "void runFunctionInProcess(void (*func)()) { if (fork() == 0) { func(); exit(0); } }", "void useQueueForThreadCommunication() { std::queue q; q.push(1); q.pop(); }", "void usePipeForCommunication() { int fd[2]; pipe(fd); }", "void limitCPUUsage() { }", "void runShellCommand(const std::string& command) { system(command.c_str()); }", "std::string getCommandOutput(const std::string& command) { std::string result; FILE* pipe = popen(command.c_str(), \"r\"); if (pipe) { char buffer[128]; while (fgets(buffer, sizeof(buffer), pipe) != nullptr) { result += buffer; } pclose(pipe); } return result; }", "int getCommandStatusCode(const std::string& command) { return system(command.c_str()); }", "bool isCommandSuccessful(const std::string& command) { return system(command.c_str()) == 0; }", "std::string getCurrentScriptPath() { return \"\"; }", "std::vector getCommandLineArgs(int argc, char* argv[]) { return std::vector(argv, argv + argc); }", "void useArgparse(int argc, char* argv[]) { }", "void generateCommandHelp() { }", "void listPythonModules() { }", "void installPythonPackage(const std::string& package) { system((\"pip install \" + package).c_str()); }", "void uninstallPythonPackage(const std::string& package) { system((\"pip uninstall \" + package).c_str()); }", "std::string getPackageVersion(const std::string& package) { return \"\"; }", "void useVirtualEnvironment() { system(\"python3 -m venv venv\"); }", "void listInstalledPackages() { system(\"pip list\"); }", "void upgradePythonPackage(const std::string& package) { system((\"pip install --upgrade \" + package).c_str()); }", "void connectToLocalDatabase() { sqlite3 *db; sqlite3_open(\":memory:\", &db); }", "void executeSQLQuery(const std::string& query) { sqlite3 *db; sqlite3_exec(db, query.c_str(), 0, 0, 0); }", "void insertRecord() { sqlite3 *db; sqlite3_exec(db, \"INSERT INTO table VALUES (1, 'value')\", 0, 0, 0); }", "void deleteRecord() { sqlite3 *db; sqlite3_exec(db, \"DELETE FROM table WHERE id = 1\", 0, 0, 0); }", "void updateRecord() { sqlite3 *db; sqlite3_exec(db, \"UPDATE table SET column = 'new_value' WHERE id = 1\", 0, 0, 0); }", "void queryMultipleRecords() { sqlite3 *db; sqlite3_exec(db, \"SELECT * FROM table\", 0, 0, 0); }", "void useParameterizedQuery() { sqlite3 *db; sqlite3_stmt *stmt; sqlite3_prepare_v2(db, \"SELECT * FROM table WHERE id = ?\", -1, &stmt, 0); }", "void closeDatabaseConnection() { sqlite3 *db; sqlite3_close(db); }", "void createTable() { sqlite3 *db; sqlite3_exec(db, \"CREATE TABLE table (id INT, column TEXT)\", 0, 0, 0); }", "void deleteTable() { sqlite3 *db; sqlite3_exec(db, \"DROP TABLE table\", 0, 0, 0); }", "bool tableExists() { return false; }", "void getAllTables() { sqlite3 *db; sqlite3_exec(db, \"SELECT name FROM sqlite_master WHERE type = 'table'\", 0, 0, 0); }", "void useORMInsert() { sqlite3 *db; sqlite3_exec(db, \"INSERT INTO table VALUES (1, 'value')\", 0, 0, 0); }", "void useORMQuery() { sqlite3 *db; sqlite3_exec(db, \"SELECT * FROM table\", 0, 0, 0); }", "void useORMDelete() { sqlite3 *db; sqlite3_exec(db, \"DELETE FROM table WHERE id = 1\", 0, 0, 0); }", "void useORMUpdate() { sqlite3 *db; sqlite3_exec(db, \"UPDATE table SET column = 'new_value' WHERE id = 1\", 0, 0, 0); }", "void defineModelClass() { struct Model { int id; std::string value; }; }", "void implementModelInheritance() { struct Base { int id; }; struct Derived : Base { std::string value; }; }", "void setPrimaryKeyField() { struct Model { int id; std::string value; }; }", "void setUniqueConstraint() { struct Model { int id; std::string value; }; }", "void setFieldDefaultValue() { struct Model { int id = 0; std::string value = \"default\"; }; }", "void exportToCSV() { std::ofstream file(\"data.csv\"); file << \"id,value\\n1,example\"; file.close(); }", "void exportToExcel() { std::ofstream file(\"data.xls\"); file << \"id\tvalue\n1\texample\"; file.close(); }", "void exportToJSON() { std::ofstream file(\"data.json\"); file << \"{\\\"id\\\":1,\\\"value\\\":\\\"example\\\"}\"; file.close(); }", "void readExcelData() { std::ifstream file(\"data.xls\"); std::string line; while (std::getline(file, line)) { std::cout << line << std::endl; } }", "void mergeExcelFiles() { std::ofstream merged(\"merged.xls\"); std::ifstream file1(\"data1.xls\"); std::ifstream file2(\"data2.xls\"); merged << file1.rdbuf() << file2.rdbuf(); }", "void addSheetToExcel() { std::ofstream file(\"data.xls\", std::ios::app); file << \"\\nNew Sheet\"; }", "void copyExcelStyle() { std::ifstream src(\"source.xls\"); std::ofstream dst(\"destination.xls\"); dst << src.rdbuf(); }", "void setExcelCellColor() { std::ofstream file(\"data.xls\", std::ios::app); file << \"\\nCell Color: Red\"; }", "void setExcelFontStyle() { std::ofstream file(\"data.xls\", std::ios::app); file << \"\\nFont Style: Bold\"; }", "void readExcelCellContent() { std::ifstream file(\"data.xls\"); std::string line; std::getline(file, line); std::cout << line << std::endl; }", "void writeExcelCellContent() { std::ofstream file(\"data.xls\", std::ios::app); file << \"\\nNew Content\"; }", "void getImageDimensions(const std::string& filePath) { std::ifstream file(filePath, std::ios::binary); file.seekg(16); int width, height; file.read((char*)&width, 4); file.read((char*)&height, 4); std::cout << \"Width: \" << width << \", Height: \" << height << std::endl; }", "void resizeImage(const std::string& filePath, int width, int height) { std::string command = \"convert \" + filePath + \" -resize \" + std::to_string(width) + \"x\" + std::to_string(height) + \" \" + filePath; system(command.c_str()); }" ] # 全局服务状态 service_ready = False # 优雅关闭处理 def handle_shutdown(signum, frame): app.logger.info("收到终止信号,开始关闭...") sys.exit(0) signal.signal(signal.SIGTERM, handle_shutdown) signal.signal(signal.SIGINT, handle_shutdown) # 初始化模型和预计算编码 try: app.logger.info("开始加载模型...") model = SentenceTransformer( "flax-sentence-embeddings/st-codesearch-distilroberta-base", cache_folder="/model-cache" ) # 预计算代码片段的编码(强制使用 CPU) code_emb = model.encode(CODE_SNIPPETS, convert_to_tensor=True, device="cpu") service_ready = True app.logger.info("服务初始化完成") except Exception as e: app.logger.error("初始化失败: %s", str(e)) raise # Hugging Face 健康检查端点,必须响应根路径 @app.route('/') def hf_health_check(): # 如果请求接受 HTML,则返回一个简单的 HTML 页面(包含测试链接) if request.accept_mimetypes.accept_html: html = """

CodeSearch API

服务状态:{{ status }}

你可以在地址栏输入 /search?query=你的查询 来测试接口

""" status = "ready" if service_ready else "initializing" return render_template_string(html, status=status) # 否则返回 JSON 格式的健康检查 if service_ready: return jsonify({"status": "ready"}), 200 else: return jsonify({"status": "initializing"}), 503 # 搜索 API 端点,同时支持 GET 和 POST 请求 @app.route('/search', methods=['GET', 'POST']) def handle_search(): if not service_ready: app.logger.info("服务未就绪") return jsonify({"error": "服务正在初始化"}), 503 try: # 根据请求方法提取查询内容 if request.method == 'GET': query = request.args.get('query', '').strip() else: data = request.get_json() or {} query = data.get('query', '').strip() if not query: app.logger.info("收到空的查询请求") return jsonify({"error": "查询不能为空"}), 400 # 记录接收到的查询 app.logger.info("收到查询请求: %s", query) # 对查询进行编码,并进行语义搜索 query_emb = model.encode(query, convert_to_tensor=True, device="cpu") hits = util.semantic_search(query_emb, code_emb, top_k=1)[0] best = hits[0] result = { "code": CODE_SNIPPETS[best['corpus_id']], "score": round(float(best['score']), 4) } # 记录返回结果 app.logger.info("返回结果: %s", result) return jsonify(result) except Exception as e: app.logger.error("请求处理失败: %s", str(e)) return jsonify({"error": "服务器内部错误"}), 500 if __name__ == "__main__": # 本地测试用,Hugging Face Spaces 通常通过 gunicorn 启动 app.run(host='0.0.0.0', port=7860)