Spaces:
Running
Running
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 = [ | |
"#include <stdio.h>\nvoid print_text() { printf(\"Hello, World!\"); }", | |
"#include <stdio.h>\nint sum(int a, int b) { return a + b; }", | |
"#include <stdlib.h>\n#include <time.h>\nint generate_random() { srand(time(NULL)); return rand(); }", | |
"#include <stdio.h>\nint is_even(int num) { return num % 2 == 0; }", | |
"#include <string.h>\nint string_length(char *str) { return strlen(str); }", | |
"#include <time.h>\nvoid get_current_date() { time_t t = time(NULL); printf(\"%s\", ctime(&t)); }", | |
"#include <stdio.h>\nint file_exists(char *filename) { FILE *file = fopen(filename, \"r\"); if (file) { fclose(file); return 1; } return 0; }", | |
"#include <stdio.h>\nvoid read_file(char *filename) { FILE *file = fopen(filename, \"r\"); char ch; while ((ch = fgetc(file)) != EOF) { putchar(ch); } fclose(file); }", | |
"#include <stdio.h>\nvoid write_file(char *filename, char *content) { FILE *file = fopen(filename, \"w\"); fprintf(file, \"%s\", content); fclose(file); }", | |
"#include <time.h>\nvoid get_current_time() { time_t t = time(NULL); printf(\"%s\", ctime(&t)); }", | |
"#include <ctype.h>\nvoid to_upper(char *str) { for (int i = 0; str[i]; i++) { str[i] = toupper(str[i]); } }", | |
"#include <ctype.h>\nvoid to_lower(char *str) { for (int i = 0; str[i]; i++) { str[i] = tolower(str[i]); } }", | |
"#include <string.h>\nvoid reverse_string(char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { char temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; } }", | |
"#include <stdio.h>\nint list_length(int *arr, int size) { return size; }", | |
"#include <limits.h>\nint list_max(int *arr, int size) { int max = INT_MIN; for (int i = 0; i < size; i++) { if (arr[i] > max) max = arr[i]; } return max; }", | |
"#include <limits.h>\nint list_min(int *arr, int size) { int min = INT_MAX; for (int i = 0; i < size; i++) { if (arr[i] < min) min = arr[i]; } return min; }", | |
"#include <stdlib.h>\nvoid sort_list(int *arr, int size) { qsort(arr, size, sizeof(int), (int (*)(const void *, const void *))strcmp); }", | |
"#include <stdio.h>\nvoid merge_lists(int *arr1, int size1, int *arr2, int size2, int *result) { memcpy(result, arr1, size1 * sizeof(int)); memcpy(result + size1, arr2, size2 * sizeof(int)); }", | |
"#include <stdio.h>\nvoid remove_element(int *arr, int *size, int index) { for (int i = index; i < *size - 1; i++) { arr[i] = arr[i + 1]; } (*size)--; }", | |
"#include <stdio.h>\nint is_list_empty(int *arr, int size) { return size == 0; }", | |
"#include <string.h>\nint count_char(char *str, char ch) { int count = 0; for (int i = 0; str[i]; i++) { if (str[i] == ch) count++; } return count; }", | |
"#include <string.h>\nint contains_substring(char *str, char *sub) { return strstr(str, sub) != NULL; }", | |
"#include <stdlib.h>\nvoid int_to_string(int num, char *str) { sprintf(str, \"%d\", num); }", | |
"#include <stdlib.h>\nint string_to_int(char *str) { return atoi(str); }", | |
"#include <ctype.h>\nint is_numeric(char *str) { for (int i = 0; str[i]; i++) { if (!isdigit(str[i])) return 0; } return 1; }", | |
"#include <stdio.h>\nint find_index(int *arr, int size, int value) { for (int i = 0; i < size; i++) { if (arr[i] == value) return i; } return -1; }", | |
"#include <stdio.h>\nvoid clear_list(int *arr, int *size) { *size = 0; }", | |
"#include <stdio.h>\nvoid reverse_list(int *arr, int size) { for (int i = 0; i < size / 2; i++) { int temp = arr[i]; arr[i] = arr[size - i - 1]; arr[size - i - 1] = temp; } }", | |
"#include <stdio.h>\nvoid remove_duplicates(int *arr, int *size) { for (int i = 0; i < *size; i++) { for (int j = i + 1; j < *size; j++) { if (arr[i] == arr[j]) { remove_element(arr, size, j); j--; } } } }", | |
"#include <stdio.h>\nint is_in_list(int *arr, int size, int value) { for (int i = 0; i < size; i++) { if (arr[i] == value) return 1; } return 0; }", | |
"#include <stdio.h>\nvoid create_dict() { }", | |
"#include <stdio.h>\nvoid add_to_dict() { }", | |
"#include <stdio.h>\nvoid delete_from_dict() { }", | |
"#include <stdio.h>\nvoid get_dict_keys() { }", | |
"#include <stdio.h>\nvoid get_dict_values() { }", | |
"#include <stdio.h>\nvoid merge_dicts() { }", | |
"#include <stdio.h>\nint is_dict_empty() { return 1; }", | |
"#include <stdio.h>\nvoid get_dict_value() { }", | |
"#include <stdio.h>\nint key_in_dict() { return 1; }", | |
"#include <stdio.h>\nvoid clear_dict() { }", | |
"#include <stdio.h>\nint count_file_lines(char *filename) { FILE *file = fopen(filename, \"r\"); int count = 0; char ch; while ((ch = fgetc(file)) != EOF) { if (ch == '\\n') count++; } fclose(file); return count; }", | |
"#include <stdio.h>\nvoid write_list_to_file(char *filename, int *arr, int size) { FILE *file = fopen(filename, \"w\"); for (int i = 0; i < size; i++) { fprintf(file, \"%d\\n\", arr[i]); } fclose(file); }", | |
"#include <stdio.h>\nvoid read_list_from_file(char *filename, int *arr, int *size) { FILE *file = fopen(filename, \"r\"); *size = 0; while (fscanf(file, \"%d\", &arr[*size]) != EOF) { (*size)++; } fclose(file); }", | |
"#include <stdio.h>\nint count_file_words(char *filename) { FILE *file = fopen(filename, \"r\"); int count = 0; char ch; while ((ch = fgetc(file)) != EOF) { if (ch == ' ') count++; } fclose(file); return count + 1; }", | |
"#include <stdio.h>\nint is_leap_year(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }", | |
"#include <time.h>\nvoid format_time() { time_t t = time(NULL); struct tm *tm = localtime(&t); char buffer[80]; strftime(buffer, 80, \"%Y-%m-%d %H:%M:%S\", tm); printf(\"%s\", buffer); }", | |
"#include <time.h>\nint days_between_dates(struct tm *date1, struct tm *date2) { return (int)(difftime(mktime(date1), mktime(date2)) / (60 * 60 * 24)); }", | |
"#include <unistd.h>\nvoid get_current_directory() { char cwd[1024]; getcwd(cwd, sizeof(cwd)); printf(\"%s\", cwd); }", | |
"#include <dirent.h>\nvoid list_directory_files(char *path) { DIR *dir = opendir(path); struct dirent *entry; while ((entry = readdir(dir)) != NULL) { printf(\"%s\\n\", entry->d_name); } closedir(dir); }", | |
"#include <sys/stat.h>\nvoid create_directory(char *path) { mkdir(path, 0777); }", | |
"#include <unistd.h>\nvoid delete_directory(char *path) { rmdir(path); }", | |
"#include <sys/stat.h>\nint is_file(char *path) { struct stat path_stat; stat(path, &path_stat); return S_ISREG(path_stat.st_mode); }", | |
"#include <sys/stat.h>\nint is_directory(char *path) { struct stat path_stat; stat(path, &path_stat); return S_ISDIR(path_stat.st_mode); }", | |
"#include <sys/stat.h>\nlong get_file_size(char *filename) { struct stat st; stat(filename, &st); return st.st_size; }", | |
"#include <stdio.h>\nvoid rename_file(char *old_name, char *new_name) { rename(old_name, new_name); }", | |
"#include <stdio.h>\nvoid copy_file(char *src, char *dest) { FILE *fsrc = fopen(src, \"rb\"); FILE *fdest = fopen(dest, \"wb\"); char ch; while ((ch = fgetc(fsrc)) != EOF) { fputc(ch, fdest); } fclose(fsrc); fclose(fdest); }", | |
"#include <stdio.h>\nvoid move_file(char *src, char *dest) { rename(src, dest); }", | |
"#include <stdio.h>\nvoid delete_file(char *filename) { remove(filename); }", | |
"#include <stdlib.h>\nvoid get_env_var(char *var) { printf(\"%s\", getenv(var)); }", | |
"#include <stdlib.h>\nvoid set_env_var(char *var, char *value) { setenv(var, value, 1); }", | |
"#include <stdio.h>\nvoid open_url(char *url) { char command[256]; sprintf(command, \"xdg-open %s\", url); system(command); }", | |
"#include <stdio.h>\n#include <curl/curl.h>\nvoid send_get_request(char *url) { CURL *curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_perform(curl); curl_easy_cleanup(curl); } }", | |
"#include <stdio.h>\n#include <json-c/json.h>\nvoid parse_json(char *json_str) { json_object *jobj = json_tokener_parse(json_str); printf(\"%s\", json_object_to_json_string(jobj)); }", | |
"#include <stdio.h>\n#include <json-c/json.h>\nvoid write_json_to_file(char *filename, json_object *jobj) { FILE *file = fopen(filename, \"w\"); fprintf(file, \"%s\", json_object_to_json_string(jobj)); fclose(file); }", | |
"#include <stdio.h>\n#include <json-c/json.h>\nvoid read_json_from_file(char *filename) { FILE *file = fopen(filename, \"r\"); char buffer[1024]; fread(buffer, 1, sizeof(buffer), file); fclose(file); json_object *jobj = json_tokener_parse(buffer); printf(\"%s\", json_object_to_json_string(jobj)); }", | |
"#include <stdio.h>\nvoid list_to_string(int *arr, int size, char *str) { for (int i = 0; i < size; i++) { sprintf(str + strlen(str), \"%d \", arr[i]); } }", | |
"#include <stdio.h>\nvoid string_to_list(char *str, int *arr, int *size) { *size = 0; char *token = strtok(str, \" \"); while (token != NULL) { arr[*size] = atoi(token); (*size)++; token = strtok(NULL, \" \"); } }", | |
"#include <stdio.h>\nvoid join_with_comma(int *arr, int size, char *str) { for (int i = 0; i < size; i++) { sprintf(str + strlen(str), \"%d,\", arr[i]); } str[strlen(str) - 1] = '\\0'; }", | |
"#include <stdio.h>\nvoid join_with_newline(int *arr, int size, char *str) { for (int i = 0; i < size; i++) { sprintf(str + strlen(str), \"%d\\n\", arr[i]); } }", | |
"#include <stdio.h>\nvoid split_by_space(char *str, char **arr, int *size) { *size = 0; char *token = strtok(str, \" \"); while (token != NULL) { arr[*size] = token; (*size)++; token = strtok(NULL, \" \"); } }", | |
"#include <stdio.h>\nvoid split_by_delimiter(char *str, char *delimiter, char **arr, int *size) { *size = 0; char *token = strtok(str, delimiter); while (token != NULL) { arr[*size] = token; (*size)++; token = strtok(NULL, delimiter); } }", | |
"#include <stdio.h>\nvoid split_to_chars(char *str, char *arr) { for (int i = 0; str[i]; i++) { arr[i] = str[i]; } }", | |
"#include <stdio.h>\nvoid replace_string(char *str, char *old, char *new) { char *pos = strstr(str, old); if (pos) { memmove(pos + strlen(new), pos + strlen(old), strlen(pos + strlen(old)) + 1); memcpy(pos, new, strlen(new)); } }", | |
"#include <stdio.h>\nvoid remove_spaces(char *str) { int count = 0; for (int i = 0; str[i]; i++) { if (str[i] != ' ') str[count++] = str[i]; } str[count] = '\\0'; }", | |
"#include <ctype.h>\nvoid remove_punctuation(char *str) { int count = 0; for (int i = 0; str[i]; i++) { if (!ispunct(str[i])) str[count++] = str[i]; } str[count] = '\\0'; }", | |
"#include <stdio.h>\nint is_string_empty(char *str) { return strlen(str) == 0; }", | |
"#include <stdio.h>\nint is_palindrome(char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { if (str[i] != str[len - i - 1]) return 0; } return 1; }", | |
"#include <stdio.h>\nvoid write_csv(char *filename, int *arr, int size) { FILE *file = fopen(filename, \"w\"); for (int i = 0; i < size; i++) { fprintf(file, \"%d,\", arr[i]); } fclose(file); }", | |
"#include <stdio.h>\nvoid read_csv(char *filename, int *arr, int *size) { FILE *file = fopen(filename, \"r\"); *size = 0; while (fscanf(file, \"%d,\", &arr[*size]) != EOF) { (*size)++; } fclose(file); }", | |
"#include <stdio.h>\nint count_csv_lines(char *filename) { FILE *file = fopen(filename, \"r\"); int count = 0; char ch; while ((ch = fgetc(file)) != EOF) { if (ch == '\\n') count++; } fclose(file); return count; }", | |
"#include <stdlib.h>\nvoid shuffle_list(int *arr, int size) { for (int i = 0; i < size; i++) { int j = rand() % size; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }", | |
"#include <stdlib.h>\nint random_element(int *arr, int size) { return arr[rand() % size]; }", | |
"#include <stdlib.h>\nvoid random_elements(int *arr, int size, int *result, int count) { for (int i = 0; i < count; i++) { result[i] = arr[rand() % size]; } }", | |
"#include <stdlib.h>\nint roll_dice() { return rand() % 6 + 1; }", | |
"#include <stdlib.h>\nint flip_coin() { return rand() % 2; }", | |
"#include <stdlib.h>\nvoid generate_password(char *password, int length) { for (int i = 0; i < length; i++) { password[i] = rand() % 94 + 33; } password[length] = '\\0'; }", | |
"#include <stdlib.h>\nvoid generate_color(char *color) { sprintf(color, \"#%06X\", rand() % 0xFFFFFF); }", | |
"#include <stdlib.h>\nvoid generate_uuid(char *uuid) { sprintf(uuid, \"%04x%04x-%04x-%04x-%04x-%04x%04x%04x\", rand() % 0xFFFF, rand() % 0xFFFF, rand() % 0xFFFF, rand() % 0xFFFF, rand() % 0xFFFF, rand() % 0xFFFF, rand() % 0xFFFF, rand() % 0xFFFF); }", | |
"""typedef struct { | |
int id; | |
char name[50]; | |
} MyClass;""", | |
"""MyClass create_instance(int id, char *name) { | |
MyClass instance; | |
instance.id = id; | |
strcpy(instance.name, name); | |
return instance; | |
}""", | |
"""void my_method(MyClass *obj) { | |
printf("Method called with ID: %d, Name: %s\\n", obj->id, obj->name); | |
}""", | |
"""typedef struct { | |
int id; | |
char name[50]; | |
} MyClass;""", | |
"""typedef struct { | |
MyClass base; | |
int additionalField; | |
} DerivedClass;""", | |
"""void overridden_method(DerivedClass *obj) { | |
printf("Overridden method called with additional field: %d\\n", obj->additionalField); | |
}""", | |
"""void class_method() { | |
printf("Class method called\\n"); | |
}""", | |
"""void static_method() { | |
printf("Static method called\\n"); | |
}""", | |
"""int is_type(MyClass *obj, const char *type) { | |
return strcmp(type, "MyClass") == 0; | |
}""", | |
"""int get_property(MyClass *obj, const char *property) { | |
if (strcmp(property, "id") == 0) return obj->id; | |
if (strcmp(property, "name") == 0) return (int)obj->name; | |
return -1; | |
}""", | |
"""void set_property(MyClass *obj, const char *property, int value) { | |
if (strcmp(property, "id") == 0) obj->id = value; | |
}""", | |
"""void delete_property(MyClass *obj, const char *property) { | |
if (strcmp(property, "id") == 0) obj->id = 0; | |
}""", | |
"#include <setjmp.h>\njmp_buf env;\n#define TRY if (setjmp(env) == 0)\n#define CATCH else", | |
"#define THROW longjmp(env, 1)", | |
"#include <stdio.h>\n#define GET_EXCEPTION_INFO fprintf(stderr, \"Exception occurred\\n\")", | |
"#include <stdio.h>\n#define LOG_ERROR(msg) fprintf(stderr, \"ERROR: %s\\n\", msg)", | |
"#include <time.h>\nclock_t start_timer() { return clock(); }", | |
"double get_elapsed_time(clock_t start) { return (double)(clock() - start) / CLOCKS_PER_SEC; }", | |
"#include <stdio.h>\nvoid print_progress_bar(int progress, int total) { printf(\"[%.*s%*s] %d%%\\r\", progress * 20 / total, \"==================\", 20 - progress * 20 / total, \"\", progress * 100 / total); fflush(stdout); }", | |
"#include <unistd.h>\nvoid delay(unsigned int seconds) { sleep(seconds); }", | |
"#define LAMBDA(return_type, body) ({ return_type __fn__ body __fn__; })", | |
"#include <stdlib.h>\nint* map(int* arr, size_t size, int (*func)(int)) { int* result = malloc(size * sizeof(int)); for (size_t i = 0; i < size; i++) result[i] = func(arr[i]); return result; }", | |
"#include <stdlib.h>\nint* filter(int* arr, size_t size, int (*func)(int), size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) if (func(arr[i])) result[(*result_size)++] = arr[i]; return result; }", | |
"#include <stdlib.h>\nint reduce(int* arr, size_t size, int (*func)(int, int), int initial) { int result = initial; for (size_t i = 0; i < size; i++) result = func(result, arr[i]); return result; }", | |
"#include <stdlib.h>\nint* list_comprehension(int* arr, size_t size, int (*func)(int), size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) result[(*result_size)++] = func(arr[i]); return result; }", | |
"#include <stdlib.h>\nint* dict_comprehension(int* keys, int* values, size_t size, int (*func)(int, int), size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) result[(*result_size)++] = func(keys[i], values[i]); return result; }", | |
"#include <stdlib.h>\nint* set_comprehension(int* arr, size_t size, int (*func)(int), size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) result[(*result_size)++] = func(arr[i]); return result; }", | |
"#include <stdlib.h>\nint* set_intersection(int* set1, int* set2, size_t size1, size_t size2, size_t* result_size) { int* result = malloc((size1 < size2 ? size1 : size2) * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size1; i++) for (size_t j = 0; j < size2; j++) if (set1[i] == set2[j]) result[(*result_size)++] = set1[i]; return result; }", | |
"#include <stdlib.h>\nint* set_union(int* set1, int* set2, size_t size1, size_t size2, size_t* result_size) { int* result = malloc((size1 + size2) * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size1; i++) result[(*result_size)++] = set1[i]; for (size_t j = 0; j < size2; j++) { int found = 0; for (size_t i = 0; i < size1; i++) if (set2[j] == set1[i]) { found = 1; break; } if (!found) result[(*result_size)++] = set2[j]; } return result; }", | |
"#include <stdlib.h>\nint* set_difference(int* set1, int* set2, size_t size1, size_t size2, size_t* result_size) { int* result = malloc(size1 * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size1; i++) { int found = 0; for (size_t j = 0; j < size2; j++) if (set1[i] == set2[j]) { found = 1; break; } if (!found) result[(*result_size)++] = set1[i]; } return result; }", | |
"#include <stdlib.h>\nint* remove_none_values(int* arr, size_t size, size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) if (arr[i] != 0) result[(*result_size)++] = arr[i]; return result; }", | |
"#include <stdio.h>\n#define TRY_OPEN_FILE(file) if ((file = fopen(\"filename\", \"r\")) == NULL) { perror(\"Error opening file\"); } else", | |
"#include <stdio.h>\n#define CHECK_TYPE(var, type) _Generic((var), type: 1, default: 0)", | |
"#include <stdbool.h>\nbool str_to_bool(const char* str) { return strcmp(str, \"true\") == 0 || strcmp(str, \"1\") == 0; }", | |
"#define IF(condition) if (condition)", | |
"#define WHILE(condition) while (condition)", | |
"#define FOR_LIST(list, size, i) for (size_t i = 0; i < size; i++)", | |
"#define FOR_DICT(dict, size, i) for (size_t i = 0; i < size; i++)", | |
"#define FOR_STRING(str, i) for (size_t i = 0; i < strlen(str); i++)", | |
"#define BREAK break", | |
"#define CONTINUE continue", | |
"#define DEFINE_FUNC(name, return_type, ...) return_type name(__VA_ARGS__)", | |
"#define DEFAULT_ARG(arg, value) arg = value", | |
"#define RETURN_MULTIPLE(...) { __VA_ARGS__ }", | |
"#define VARARGS(...) __VA_ARGS__", | |
"#define KEYWORD_ARGS(...) __VA_ARGS__", | |
"#include <time.h>\n#define TIME_FUNC(func, ...) { clock_t start = clock(); func(__VA_ARGS__); printf(\"Time: %f\\n\", (double)(clock() - start) / CLOCKS_PER_SEC); }", | |
"#define DECORATE(func, decorator) decorator(func)", | |
"#include <stdlib.h>\n#define CACHE_FUNC(func, ...) { static int cached_result = 0; if (!cached_result) cached_result = func(__VA_ARGS__); return cached_result; }", | |
"#define CREATE_GENERATOR(name, type) type name() { static type state = 0; return state++; }", | |
"#define YIELD(value) return value", | |
"#define NEXT(generator) generator()", | |
"#define CREATE_ITERATOR(name, type) type name() { static type state = 0; return state++; }", | |
"#define MANUAL_ITERATE(iterator) iterator()", | |
"#define ENUMERATE(list, size, i) for (size_t i = 0; i < size; i++)", | |
"#include <stdlib.h>\nint* zip(int* list1, int* list2, size_t size, size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) result[(*result_size)++] = list1[i] + list2[i]; return result; }", | |
"#include <stdlib.h>\nint* list_to_dict(int* keys, int* values, size_t size, size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) result[(*result_size)++] = values[i]; return result; }", | |
"#define EQUAL_LISTS(list1, list2, size) memcmp(list1, list2, size) == 0", | |
"#define EQUAL_DICTS(dict1, dict2, size) memcmp(dict1, dict2, size) == 0", | |
"#define EQUAL_SETS(set1, set2, size) memcmp(set1, set2, size) == 0", | |
"#include <stdlib.h>\nint* set_unique(int* set, size_t size, size_t* result_size) { int* result = malloc(size * sizeof(int)); *result_size = 0; for (size_t i = 0; i < size; i++) { int found = 0; for (size_t j = 0; j < *result_size; j++) if (set[i] == result[j]) { found = 1; break; } if (!found) result[(*result_size)++] = set[i]; } return result; }", | |
"#define CLEAR_SET(set, size) memset(set, 0, size * sizeof(int))", | |
"#define IS_SET_EMPTY(set, size) size == 0", | |
"#define ADD_TO_SET(set, size, value) set[size++] = value", | |
"#define REMOVE_FROM_SET(set, size, value) { for (size_t i = 0; i < size; i++) if (set[i] == value) { set[i] = set[--size]; break; } }", | |
"#define SET_CONTAINS(set, size, value) ({ int found = 0; for (size_t i = 0; i < size; i++) if (set[i] == value) { found = 1; break; } found; })", | |
"#define SET_SIZE(set, size) size", | |
"#define SETS_INTERSECT(set1, set2, size1, size2) ({ int found = 0; for (size_t i = 0; i < size1; i++) for (size_t j = 0; j < size2; j++) if (set1[i] == set2[j]) { found = 1; break; } found; })", | |
"#define IS_SUBSET(list1, list2, size1, size2) ({ int found = 1; for (size_t i = 0; i < size1; i++) { int match = 0; for (size_t j = 0; j < size2; j++) if (list1[i] == list2[j]) { match = 1; break; } if (!match) { found = 0; break; } } found; })", | |
"#define IS_SUBSTRING(str, substr) strstr(str, substr) != NULL", | |
"#define FIRST_CHAR(str) str[0]", | |
"#define LAST_CHAR(str) str[strlen(str) - 1]", | |
"#include <stdio.h>\n#define IS_TEXT_FILE(file) fgetc(file) != EOF", | |
"#include <stdio.h>\n#define IS_IMAGE_FILE(file) fgetc(file) != EOF", | |
"#include <math.h>\n#define ROUND(num) round(num)", | |
"#include <math.h>\n#define CEIL(num) ceil(num)", | |
"#include <math.h>\n#define FLOOR(num) floor(num)", | |
"#include <stdio.h>\n#define FORMAT_DECIMAL(num, places) printf(\"%.*f\", places, num)", | |
"#include <stdlib.h>\n#define RANDOM_STRING(length) ({ char* str = malloc(length + 1); for (size_t i = 0; i < length; i++) str[i] = 'a' + rand() % 26; str[length] = '\\0'; str; })", | |
"#include <unistd.h>\n#define PATH_EXISTS(path) access(path, F_OK) == 0", | |
"#include <dirent.h>\n#define LIST_DIRECTORY(dir) ({ DIR* d = opendir(dir); struct dirent* entry; while ((entry = readdir(d)) != NULL) printf(\"%s\\n\", entry->d_name); closedir(d); })", | |
"#include <libgen.h>\n#define GET_EXTENSION(path) strrchr(path, '.')", | |
"#include <libgen.h>\n#define GET_FILENAME(path) basename(path)", | |
"#include <libgen.h>\n#define GET_FULL_PATH(path) realpath(path, NULL)", | |
"#include <Python.h>\n#define PYTHON_VERSION Py_GetVersion()", | |
"#include <sys/utsname.h>\n#define SYSTEM_INFO ({ struct utsname info; uname(&info); info.sysname; })", | |
"#include <unistd.h>\n#define CPU_CORES sysconf(_SC_NPROCESSORS_ONLN)", | |
"#include <sys/sysinfo.h>\n#define MEMORY_SIZE ({ struct sysinfo info; sysinfo(&info); info.totalram; })", | |
"#include <sys/statvfs.h>\n#define DISK_USAGE(path) ({ struct statvfs info; statvfs(path, &info); (info.f_blocks - info.f_bfree) * info.f_frsize; })", | |
"#include <ifaddrs.h>\n#define NETWORK_IP ({ struct ifaddrs* ifaddr; getifaddrs(&ifaddr); ifaddr->ifa_addr; })", | |
"#include <unistd.h>\n#define IS_CONNECTED system(\"ping -c 1 google.com\") == 0", | |
"#include <curl/curl.h>\n#define DOWNLOAD_FILE(url, file) ({ CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fopen(file, \"wb\")); curl_easy_perform(curl); curl_easy_cleanup(curl); })", | |
"#include <curl/curl.h>\n#define UPLOAD_FILE(url, file) ({ CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_READDATA, fopen(file, \"rb\")); curl_easy_perform(curl); curl_easy_cleanup(curl); })", | |
"#include <curl/curl.h>\n#define POST_REQUEST(url, data) ({ CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data); curl_easy_perform(curl); curl_easy_cleanup(curl); })", | |
"#include <curl/curl.h>\n#define SEND_REQUEST(url, params) ({ CURL* curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, params); curl_easy_perform(curl); curl_easy_cleanup(curl); })", | |
"#include <curl/curl.h>\n#define SET_HEADERS(curl, headers) curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers)", | |
"#include <libxml/HTMLparser.h>\n#define PARSE_HTML(html) ({ htmlDocPtr doc = htmlReadDoc((xmlChar*)html, NULL, NULL, HTML_PARSE_RECOVER | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING); doc; })", | |
"#include <libxml/HTMLparser.h>\n#define EXTRACT_TITLE(doc) ({ xmlChar* title = xmlNodeGetContent(xmlDocGetRootElement(doc)->children); title; })", | |
"#include <libxml/HTMLparser.h>\n#define EXTRACT_LINKS(doc) ({ xmlNodePtr cur = xmlDocGetRootElement(doc)->children; while (cur != NULL) { if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->name, (xmlChar*)\"a\") == 0) printf(\"%s\\n\", xmlGetProp(cur, (xmlChar*)\"href\")); cur = cur->next; } })", | |
"#include <libxml/HTMLparser.h>\n#define DOWNLOAD_IMAGES(doc) ({ xmlNodePtr cur = xmlDocGetRootElement(doc)->children; while (cur != NULL) { if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->name, (xmlChar*)\"img\") == 0) printf(\"%s\\n\", xmlGetProp(cur, (xmlChar*)\"src\")); cur = cur->next; } })", | |
"#include <libxml/HTMLparser.h>\n#define COUNT_WORDS(doc) ({ xmlNodePtr cur = xmlDocGetRootElement(doc)->children; int count = 0; while (cur != NULL) { if (cur->type == XML_TEXT_NODE) count += xmlStrlen(cur->content); cur = cur->next; } count; })", | |
"#include <libxml/HTMLparser.h>\n#define SIMULATE_LOGIN(doc, username, password) ({ xmlNodePtr cur = xmlDocGetRootElement(doc)->children; while (cur != NULL) { if (cur->type == XML_ELEMENT_NODE && xmlStrcmp(cur->name, (xmlChar*)\"form\") == 0) printf(\"%s\\n\", xmlGetProp(cur, (xmlChar*)\"action\")); cur = cur->next; } })", | |
"#include <libxml/HTMLparser.h>\n#define HTML_TO_TEXT(doc) ({ xmlChar* text = xmlNodeGetContent(xmlDocGetRootElement(doc)); text; })", | |
"#include <regex.h>\n#define EXTRACT_EMAIL(str) ({ regex_t regex; regcomp(®ex, \"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\", REG_EXTENDED); regmatch_t match; regexec(®ex, str, 1, &match, 0); strndup(str + match.rm_so, match.rm_eo - match.rm_so); })", | |
"#include <regex.h>\n#define EXTRACT_PHONE(str) ({ regex_t regex; regcomp(®ex, \"\\\\+?[0-9]{10,13}\", REG_EXTENDED); regmatch_t match; regexec(®ex, str, 1, &match, 0); strndup(str + match.rm_so, match.rm_eo - match.rm_so); })", | |
"#include <regex.h>\n#define FIND_ALL_NUMBERS(str) ({ regex_t regex; regcomp(®ex, \"[0-9]+\", REG_EXTENDED); regmatch_t match; char* result = str; while (regexec(®ex, result, 1, &match, 0) == 0) { printf(\"%s\\n\", strndup(result + match.rm_so, match.rm_eo - match.rm_so)); result += match.rm_eo; } })", | |
"#include <regex.h>\n#define REGEX_REPLACE(str, pattern, replacement) ({ regex_t regex; regcomp(®ex, pattern, REG_EXTENDED); regmatch_t match; char* result = str; while (regexec(®ex, result, 1, &match, 0) == 0) { printf(\"%s%s\", strndup(result, match.rm_so), replacement); result += match.rm_eo; } printf(\"%s\\n\", result); })", | |
"#include <regex.h>\n#define MATCH_REGEX(str, pattern) ({ regex_t regex; regcomp(®ex, pattern, REG_EXTENDED); regexec(®ex, str, 0, NULL, 0) == 0; })", | |
"#include <libxml/HTMLparser.h>\n#define REMOVE_HTML_TAGS(html) ({ xmlChar* text = xmlNodeGetContent(xmlDocGetRootElement(htmlReadDoc((xmlChar*)html, NULL, NULL, HTML_PARSE_RECOVER | HTML_PARSE_NOERROR | HTML_PARSE_NOWARNING))); text; })", | |
"#include <libxml/HTMLparser.h>\n#define HTML_ENCODE(str) ({ xmlChar* encoded = xmlEncodeEntitiesReentrant(NULL, (xmlChar*)str); encoded; })", | |
"#include <libxml/HTMLparser.h>\n#define HTML_DECODE(str) ({ xmlChar* decoded = xmlDecodeEntitiesReentrant(NULL, (xmlChar*)str, XML_SUBSTITUTE_REF); decoded; })", | |
"#include <gtk/gtk.h>\n#define CREATE_GUI_WINDOW() ({ gtk_init(NULL, NULL); GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_show_all(window); gtk_main(); })", | |
"void add_button_to_window(GtkWidget *window, const char *label) { GtkWidget *button = gtk_button_new_with_label(label); gtk_container_add(GTK_CONTAINER(window), button); }", | |
"void on_button_clicked(GtkWidget *widget, gpointer data) { g_print(\"Button clicked\\n\"); }", | |
"void show_message_dialog(GtkWidget *window, const char *message) { GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, message); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); }", | |
"const char *get_entry_text(GtkWidget *entry) { return gtk_entry_get_text(GTK_ENTRY(entry)); }", | |
"void set_window_title(GtkWidget *window, const char *title) { gtk_window_set_title(GTK_WINDOW(window), title); }", | |
"void set_window_size(GtkWidget *window, int width, int height) { gtk_window_set_default_size(GTK_WINDOW(window), width, height); }", | |
"void center_window(GtkWidget *window) { gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); }", | |
"GtkWidget *create_menu_bar() { return gtk_menu_bar_new(); }", | |
"GtkWidget *create_combo_box() { return gtk_combo_box_text_new(); }", | |
"GtkWidget *create_radio_button() { return gtk_radio_button_new(NULL); }", | |
"GtkWidget *create_check_button() { return gtk_check_button_new(); }", | |
"void show_image(GtkWidget *window, const char *file_path) { GtkWidget *image = gtk_image_new_from_file(file_path); gtk_container_add(GTK_CONTAINER(window), image); }", | |
"void play_audio(const char *file_path) { GstElement *pipeline = gst_parse_launch(\"playbin uri=file://\" file_path, NULL); gst_element_set_state(pipeline, GST_STATE_PLAYING); }", | |
"void play_video(const char *file_path) { GstElement *pipeline = gst_parse_launch(\"playbin uri=file://\" file_path, NULL); gst_element_set_state(pipeline, GST_STATE_PLAYING); }", | |
"gint64 get_current_play_time(GstElement *pipeline) { gint64 current_time; gst_element_query_position(pipeline, GST_FORMAT_TIME, ¤t_time); return current_time; }", | |
"void capture_screen() { Display *display = XOpenDisplay(NULL); Window root = DefaultRootWindow(display); XImage *image = XGetImage(display, root, 0, 0, DisplayWidth(display, 0), DisplayHeight(display, 0), AllPlanes, ZPixmap); XCloseDisplay(display); }", | |
"void record_screen(int duration) { /* Implementation for screen recording */ }", | |
"void get_mouse_position(int *x, int *y) { Display *display = XOpenDisplay(NULL); Window root = DefaultRootWindow(display); Window child; int root_x, root_y; XQueryPointer(display, root, &root, &child, x, y, &root_x, &root_y, NULL); XCloseDisplay(display); }", | |
"void simulate_keyboard_input(const char *text) { /* Implementation for keyboard input simulation */ }", | |
"void simulate_mouse_click(int x, int y) { /* Implementation for mouse click simulation */ }", | |
"time_t get_current_timestamp() { return time(NULL); }", | |
"char *timestamp_to_date(time_t timestamp) { return ctime(×tamp); }", | |
"time_t date_to_timestamp(const char *date) { struct tm tm; strptime(date, \"%Y-%m-%d %H:%M:%S\", &tm); return mktime(&tm); }", | |
"int get_current_weekday() { time_t now = time(NULL); struct tm *tm = localtime(&now); return tm->tm_wday; }", | |
"int get_days_in_month(int year, int month) { struct tm tm = {0, 0, 0, 0, month - 1, year - 1900}; return 31 - ((mktime(&tm) / 86400) % 31); }", | |
"time_t get_first_day_of_year(int year) { struct tm tm = {0, 0, 0, 1, 0, year - 1900}; return mktime(&tm); }", | |
"time_t get_last_day_of_year(int year) { struct tm tm = {0, 0, 0, 31, 11, year - 1900}; return mktime(&tm); }", | |
"time_t get_first_day_of_month(int year, int month) { struct tm tm = {0, 0, 0, 1, month - 1, year - 1900}; return mktime(&tm); }", | |
"time_t get_last_day_of_month(int year, int month) { struct tm tm = {0, 0, 0, 0, month, year - 1900}; tm.tm_mday -= 1; return mktime(&tm); }", | |
"int is_weekday(time_t timestamp) { struct tm *tm = localtime(×tamp); return tm->tm_wday >= 1 && tm->tm_wday <= 5; }", | |
"int is_weekend(time_t timestamp) { struct tm *tm = localtime(×tamp); return tm->tm_wday == 0 || tm->tm_wday == 6; }", | |
"int get_current_hour() { time_t now = time(NULL); struct tm *tm = localtime(&now); return tm->tm_hour; }", | |
"int get_current_minute() { time_t now = time(NULL); struct tm *tm = localtime(&now); return tm->tm_min; }", | |
"int get_current_second() { time_t now = time(NULL); struct tm *tm = localtime(&now); return tm->tm_sec; }", | |
"void sleep_one_second() { sleep(1); }", | |
"long get_millisecond_timestamp() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000 + tv.tv_usec / 1000; }", | |
"char *format_time(time_t timestamp, const char *format) { struct tm *tm = localtime(×tamp); static char buffer[80]; strftime(buffer, 80, format, tm); return buffer; }", | |
"time_t parse_time(const char *time_str, const char *format) { struct tm tm; strptime(time_str, format, &tm); return mktime(&tm); }", | |
"void *thread_function(void *arg) { /* Implementation for thread function */ return NULL; }", | |
"void create_thread() { pthread_t thread; pthread_create(&thread, NULL, thread_function, NULL); }", | |
"void pause_thread(pthread_t thread) { pthread_kill(thread, SIGSTOP); }", | |
"void run_function_in_thread(void *(*function)(void *), void *arg) { pthread_t thread; pthread_create(&thread, NULL, function, arg); }", | |
"char *get_current_thread_name() { static char name[16]; pthread_getname_np(pthread_self(), name, 16); return name; }", | |
"void set_thread_as_daemon(pthread_t thread) { pthread_detach(thread); }", | |
"pthread_mutex_t lock;", | |
"void lock_thread() { pthread_mutex_lock(&lock); }", | |
"void unlock_thread() { pthread_mutex_unlock(&lock); }", | |
"void create_process() { pid_t pid = fork(); if (pid == 0) { /* Child process */ } else { /* Parent process */ } }", | |
"pid_t get_process_pid() { return getpid(); }", | |
"int is_process_alive(pid_t pid) { return kill(pid, 0) == 0; }", | |
"void run_function_in_process(void (*function)()) { pid_t pid = fork(); if (pid == 0) { function(); exit(0); } }", | |
"void send_message_to_queue(int msgid, const void *msg, size_t size) { msgsnd(msgid, msg, size, 0); }", | |
"void receive_message_from_queue(int msgid, void *msg, size_t size, long type) { msgrcv(msgid, msg, size, type, 0); }", | |
"void pipe_communication() { int fd[2]; pipe(fd); if (fork() == 0) { close(fd[0]); write(fd[1], \"Hello\", 6); close(fd[1]); } else { close(fd[1]); char buffer[6]; read(fd[0], buffer, 6); close(fd[0]); } }", | |
"void limit_cpu_usage(int percentage) { /* Implementation for CPU usage limiting */ }", | |
"void run_shell_command(const char *command) { system(command); }", | |
"char *get_command_output(const char *command) { FILE *fp = popen(command, \"r\"); static char buffer[1024]; fgets(buffer, 1024, fp); pclose(fp); return buffer; }", | |
"int get_command_status_code(const char *command) { return system(command); }", | |
"int is_command_successful(const char *command) { return system(command) == 0; }", | |
"char *get_current_script_path() { static char path[1024]; readlink(\"/proc/self/exe\", path, 1024); return path; }", | |
"void parse_arguments(int argc, char *argv[]) { struct argp_option options[] = { {0} }; struct argp argp = {options, NULL, NULL, NULL}; argp_parse(&argp, argc, argv, 0, 0, NULL); }", | |
"void generate_help_document() { /* Implementation for help document generation */ }", | |
"void list_python_modules() { system(\"python -c 'import sys; print(sys.modules)'\"); }", | |
"void install_python_package(const char *package) { system(\"pip install \" package); }", | |
"void uninstall_python_package(const char *package) { system(\"pip uninstall \" package); }", | |
"char *get_package_version(const char *package) { FILE *fp = popen(\"pip show \" package, \"r\"); static char buffer[1024]; fgets(buffer, 1024, fp); pclose(fp); return buffer; }", | |
"void use_virtual_environment(const char *env) { setenv(\"VIRTUAL_ENV\", env, 1); }", | |
"void list_installed_packages() { system(\"pip list\"); }", | |
"void upgrade_python_package(const char *package) { system(\"pip install --upgrade \" package); }", | |
"void connect_to_database(const char *db_name) { sqlite3_open(db_name, &db); }", | |
"void execute_sql_query(const char *query) { sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void insert_record(const char *table, const char *values) { char query[1024]; sprintf(query, \"INSERT INTO %s VALUES (%s)\", table, values); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void delete_record(const char *table, const char *condition) { char query[1024]; sprintf(query, \"DELETE FROM %s WHERE %s\", table, condition); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void update_record(const char *table, const char *set_clause, const char *condition) { char query[1024]; sprintf(query, \"UPDATE %s SET %s WHERE %s\", table, set_clause, condition); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void select_records(const char *table, const char *condition) { char query[1024]; sprintf(query, \"SELECT * FROM %s WHERE %s\", table, condition); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void use_parameterized_query(const char *query, const char *params) { sqlite3_stmt *stmt; sqlite3_prepare_v2(db, query, -1, &stmt, NULL); sqlite3_bind_text(stmt, 1, params, -1, SQLITE_STATIC); sqlite3_step(stmt); sqlite3_finalize(stmt); }", | |
"void close_database_connection() { sqlite3_close(db); }", | |
"void create_table(const char *table, const char *columns) { char query[1024]; sprintf(query, \"CREATE TABLE %s (%s)\", table, columns); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void drop_table(const char *table) { char query[1024]; sprintf(query, \"DROP TABLE %s\", table); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"int is_table_exists(const char *table) { char query[1024]; sprintf(query, \"SELECT name FROM sqlite_master WHERE type='table' AND name='%s'\", table); sqlite3_stmt *stmt; sqlite3_prepare_v2(db, query, -1, &stmt, NULL); int result = sqlite3_step(stmt); sqlite3_finalize(stmt); return result == SQLITE_ROW; }", | |
"void list_all_tables() { sqlite3_exec(db, \"SELECT name FROM sqlite_master WHERE type='table'\", NULL, NULL, NULL); }", | |
"void orm_insert_data(const char *table, const char *values) { char query[1024]; sprintf(query, \"INSERT INTO %s VALUES (%s)\", table, values); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void orm_select_data(const char *table, const char *condition) { char query[1024]; sprintf(query, \"SELECT * FROM %s WHERE %s\", table, condition); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void orm_delete_data(const char *table, const char *condition) { char query[1024]; sprintf(query, \"DELETE FROM %s WHERE %s\", table, condition); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void orm_update_data(const char *table, const char *set_clause, const char *condition) { char query[1024]; sprintf(query, \"UPDATE %s SET %s WHERE %s\", table, set_clause, condition); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void define_model_class(const char *name, const char *fields) { /* Implementation for model class definition */ }", | |
"void implement_model_inheritance(const char *base_class, const char *derived_class) { /* Implementation for model inheritance */ }", | |
"void set_primary_key(const char *table, const char *field) { char query[1024]; sprintf(query, \"ALTER TABLE %s ADD PRIMARY KEY (%s)\", table, field); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void set_unique_constraint(const char *table, const char *field) { char query[1024]; sprintf(query, \"ALTER TABLE %s ADD UNIQUE (%s)\", table, field); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void set_field_default_value(const char *table, const char *field, const char *default_value) { char query[1024]; sprintf(query, \"ALTER TABLE %s ALTER COLUMN %s SET DEFAULT %s\", table, field, default_value); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void export_data_to_csv(const char *table, const char *file_path) { char query[1024]; sprintf(query, \".mode csv\\n.output %s\\nSELECT * FROM %s\", file_path, table); sqlite3_exec(db, query, NULL, NULL, NULL); }", | |
"void export_data_to_excel(const char *table, const char *file_path) { /* Implementation for Excel export */ }", | |
"void export_data_to_json(const char *table, const char *file_path) { /* Implementation for JSON export */ }", | |
"void read_excel_data(const char *file_path) { /* Implementation for Excel data reading */ }", | |
"void merge_excel_files(const char *file1, const char *file2, const char *output_file) { /* Implementation for Excel file merging */ }", | |
"void add_sheet_to_excel(const char *file_path, const char *sheet_name) { /* Implementation for adding sheet to Excel */ }", | |
"void copy_excel_sheet_style(const char *source_file, const char *target_file) { /* Implementation for copying Excel sheet style */ }", | |
"void set_excel_cell_color(const char *file_path, const char *sheet, int row, int col, const char *color) { /* Implementation for setting Excel cell color */ }", | |
"void set_excel_font_style(const char *file_path, const char *sheet, int row, int col, const char *style) { /* Implementation for setting Excel font style */ }", | |
"void read_excel_cell_content(const char *file_path, const char *sheet, int row, int col) { /* Implementation for reading Excel cell content */ }", | |
"void write_excel_cell_content(const char *file_path, const char *sheet, int row, int col, const char *content) { /* Implementation for writing Excel cell content */ }", | |
"void get_image_dimensions(const char *file_path, int *width, int *height) { /* Implementation for getting image dimensions */ }", | |
"void resize_image(const char *file_path, int new_width, int new_height) { /* Implementation for resizing image */ }" | |
] | |
# 全局服务状态 | |
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 健康检查端点,必须响应根路径 | |
def hf_health_check(): | |
# 如果请求接受 HTML,则返回一个简单的 HTML 页面(包含测试链接) | |
if request.accept_mimetypes.accept_html: | |
html = """ | |
<h2>CodeSearch API</h2> | |
<p>服务状态:{{ status }}</p> | |
<p>你可以在地址栏输入 /search?query=你的查询 来测试接口</p> | |
""" | |
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 请求 | |
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) | |