Spaces:
Running
Running
File size: 32,384 Bytes
2a39044 90f5392 892f484 7c08c7b 90f5392 2a39044 90f5392 2a39044 892f484 90f5392 79ce9cc 892f484 9284d6e e49c70f 1acad33 278dc1e e49fd82 e54550e 1d25027 892f484 7c08c7b 892f484 7c08c7b 2a39044 892f484 2a39044 79ce9cc 7c08c7b 79ce9cc 2a39044 7c08c7b 892f484 2a39044 892f484 2a39044 7c08c7b 2a39044 7c08c7b 79ce9cc 2a39044 c79e0ff 892f484 7c08c7b 2a39044 79ce9cc c79e0ff aacc39b 2a39044 c79e0ff 892f484 c79e0ff 892f484 2a39044 c79e0ff 2a39044 79ce9cc c79e0ff 79ce9cc c79e0ff 2a39044 c79e0ff 2a39044 aacc39b c79e0ff 892f484 90f5392 0db0051 2a39044 c79e0ff |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 |
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 = [
"System.out.println(\"Hello, World!\");",
"public static int sum(int a, int b) { return a + b; }",
"import java.util.Random; public static int generateRandomNumber() { return new Random().nextInt(); }",
"public static boolean isEven(int number) { return number % 2 == 0; }",
"public static int stringLength(String str) { return str.length(); }",
"import java.time.LocalDate; public static String getCurrentDate() { return LocalDate.now().toString(); }",
"import java.io.File; public static boolean fileExists(String path) { return new File(path).exists(); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static String readFileContent(String path) throws Exception { return new String(Files.readAllBytes(Paths.get(path))); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void writeToFile(String path, String content) throws Exception { Files.write(Paths.get(path), content.getBytes()); }",
"import java.time.LocalTime; public static String getCurrentTime() { return LocalTime.now().toString(); }",
"public static String toUpperCase(String str) { return str.toUpperCase(); }",
"public static String toLowerCase(String str) { return str.toLowerCase(); }",
"public static String reverseString(String str) { return new StringBuilder(str).reverse().toString(); }",
"public static int listSize(List<?> list) { return list.size(); }",
"public static int maxInList(List<Integer> list) { return Collections.max(list); }",
"public static int minInList(List<Integer> list) { return Collections.min(list); }",
"public static List<Integer> sortList(List<Integer> list) { Collections.sort(list); return list; }",
"public static List<?> mergeLists(List<?> list1, List<?> list2) { List<Object> merged = new ArrayList<>(list1); merged.addAll(list2); return merged; }",
"public static List<?> removeElement(List<?> list, Object element) { list.remove(element); return list; }",
"public static boolean isListEmpty(List<?> list) { return list.isEmpty(); }",
"public static int countCharInString(String str, char ch) { return (int) str.chars().filter(c -> c == ch).count(); }",
"public static boolean containsSubstring(String str, String sub) { return str.contains(sub); }",
"public static String intToString(int number) { return Integer.toString(number); }",
"public static int stringToInt(String str) { return Integer.parseInt(str); }",
"public static boolean isNumeric(String str) { return str.matches(\"-?\\\\d+(\\\\.\\\\d+)?\"); }",
"public static int indexOfElement(List<?> list, Object element) { return list.indexOf(element); }",
"public static void clearList(List<?> list) { list.clear(); }",
"public static List<?> reverseList(List<?> list) { Collections.reverse(list); return list; }",
"public static List<?> removeDuplicates(List<?> list) { return new ArrayList<>(new LinkedHashSet<>(list)); }",
"public static boolean isInList(List<?> list, Object element) { return list.contains(element); }",
"public static Map<?, ?> createDictionary() { return new HashMap<>(); }",
"public static void addToDictionary(Map<?, ?> map, Object key, Object value) { ((Map<Object, Object>) map).put(key, value); }",
"public static void removeFromDictionary(Map<?, ?> map, Object key) { map.remove(key); }",
"public static Set<?> getDictionaryKeys(Map<?, ?> map) { return map.keySet(); }",
"public static Collection<?> getDictionaryValues(Map<?, ?> map) { return map.values(); }",
"public static Map<?, ?> mergeDictionaries(Map<?, ?> map1, Map<?, ?> map2) { Map<Object, Object> merged = new HashMap<>(map1); merged.putAll(map2); return merged; }",
"public static boolean isDictionaryEmpty(Map<?, ?> map) { return map.isEmpty(); }",
"public static Object getDictionaryValue(Map<?, ?> map, Object key) { return map.get(key); }",
"public static boolean keyExistsInDictionary(Map<?, ?> map, Object key) { return map.containsKey(key); }",
"public static void clearDictionary(Map<?, ?> map) { map.clear(); }",
"public static int countFileLines(String path) throws Exception { return (int) Files.lines(Paths.get(path)).count(); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void writeListToFile(String path, List<?> list) throws Exception { Files.write(Paths.get(path), list.toString().getBytes()); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static List<?> readListFromFile(String path) throws Exception { return Arrays.asList(new String(Files.readAllBytes(Paths.get(path))).split(\",\")); }",
"public static int countWordsInFile(String path) throws Exception { return (int) Files.lines(Paths.get(path)).flatMap(line -> Arrays.stream(line.split(\"\\\\s+\"))).count(); }",
"public static boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); }",
"import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public static String formatDateTime(LocalDateTime dateTime, String pattern) { return dateTime.format(DateTimeFormatter.ofPattern(pattern)); }",
"import java.time.LocalDate; import java.time.temporal.ChronoUnit; public static long daysBetweenDates(LocalDate date1, LocalDate date2) { return ChronoUnit.DAYS.between(date1, date2); }",
"import java.nio.file.Paths; public static String getCurrentWorkingDirectory() { return Paths.get(\"\").toAbsolutePath().toString(); }",
"import java.io.File; public static List<String> listFilesInDirectory(String path) { return Arrays.stream(new File(path).listFiles()).map(File::getName).collect(Collectors.toList()); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void createDirectory(String path) throws Exception { Files.createDirectory(Paths.get(path)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void deleteDirectory(String path) throws Exception { Files.delete(Paths.get(path)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static boolean isFile(String path) { return Files.isRegularFile(Paths.get(path)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static boolean isDirectory(String path) { return Files.isDirectory(Paths.get(path)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static long getFileSize(String path) throws Exception { return Files.size(Paths.get(path)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void renameFile(String oldPath, String newPath) throws Exception { Files.move(Paths.get(oldPath), Paths.get(newPath)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void copyFile(String source, String destination) throws Exception { Files.copy(Paths.get(source), Paths.get(destination)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void moveFile(String source, String destination) throws Exception { Files.move(Paths.get(source), Paths.get(destination)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void deleteFile(String path) throws Exception { Files.delete(Paths.get(path)); }",
"public static String getEnvironmentVariable(String name) { return System.getenv(name); }",
"public static void setEnvironmentVariable(String name, String value) { System.setProperty(name, value); }",
"import java.awt.Desktop; import java.net.URI; public static void openWebLink(String url) throws Exception { Desktop.getDesktop().browse(new URI(url)); }",
"import java.net.HttpURLConnection; import java.net.URL; public static String sendGetRequest(String url) throws Exception { HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod(\"GET\"); return new String(con.getInputStream().readAllBytes()); }",
"import com.google.gson.JsonObject; import com.google.gson.JsonParser; public static JsonObject parseJson(String json) { return JsonParser.parseString(json).getAsJsonObject(); }",
"import com.google.gson.Gson; import java.nio.file.Files; import java.nio.file.Paths; public static void writeJsonToFile(String path, JsonObject json) throws Exception { Files.write(Paths.get(path), new Gson().toJson(json).getBytes()); }",
"import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.nio.file.Files; import java.nio.file.Paths; public static JsonObject readJsonFromFile(String path) throws Exception { return JsonParser.parseString(new String(Files.readAllBytes(Paths.get(path)))).getAsJsonObject(); }",
"public static String listToString(List<?> list) { return list.toString(); }",
"public static List<String> stringToList(String str) { return Arrays.asList(str.split(\",\")); }",
"public static String joinWithComma(List<?> list) { return String.join(\",\", list.stream().map(Object::toString).collect(Collectors.toList())); }",
"public static String joinWithNewline(List<?> list) { return String.join(\"\\n\", list.stream().map(Object::toString).collect(Collectors.toList())); }",
"public static List<String> splitBySpace(String str) { return Arrays.asList(str.split(\"\\\\s+\")); }",
"public static List<String> splitByDelimiter(String str, String delimiter) { return Arrays.asList(str.split(delimiter)); }",
"public static List<String> splitIntoCharacters(String str) { return Arrays.asList(str.split(\"\")); }",
"public static String replaceInString(String str, String target, String replacement) { return str.replace(target, replacement); }",
"public static String removeSpaces(String str) { return str.replaceAll(\"\\\\s\", \"\"); }",
"public static String removePunctuation(String str) { return str.replaceAll(\"[^a-zA-Z0-9]\", \"\"); }",
"public static boolean isStringEmpty(String str) { return str.isEmpty(); }",
"public static boolean isPalindrome(String str) { return str.equals(new StringBuilder(str).reverse().toString()); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static void writeTextToCsv(String path, List<String> lines) throws Exception { Files.write(Paths.get(path), lines); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static List<String> readCsvFile(String path) throws Exception { return Files.readAllLines(Paths.get(path)); }",
"import java.nio.file.Files; import java.nio.file.Paths; public static int countCsvLines(String path) throws Exception { return (int) Files.lines(Paths.get(path)).count(); }",
"public static List<?> shuffleList(List<?> list) { Collections.shuffle(list); return list; }",
"public static Object pickRandomElement(List<?> list) { return list.get(new Random().nextInt(list.size())); }",
"public static List<?> pickRandomElements(List<?> list, int count) { Collections.shuffle(list); return list.subList(0, count); }",
"public static int rollDice() { return new Random().nextInt(6) + 1; }",
"public static String flipCoin() { return new Random().nextBoolean() ? \"Heads\" : \"Tails\"; }",
"import java.util.Random; public static String generateRandomPassword(int length) { String chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(chars.charAt(new Random().nextInt(chars.length()))); } return sb.toString(); }",
"import java.util.Random; public static String generateRandomColor() { Random rand = new Random(); return String.format(\"#%06x\", rand.nextInt(0xFFFFFF)); }",
"import java.util.UUID; public static String generateUniqueId() { return UUID.randomUUID().toString(); }",
"public class MyClass {}",
"MyClass myObject = new MyClass();",
"public class MyClass { public void myMethod() {} }",
"public class MyClass { public String myAttribute; }",
"public class ChildClass extends ParentClass {}",
"public class ChildClass extends ParentClass { @Override public void myMethod() {} }",
"public class MyClass { public static void myClassMethod() {} }",
"public class MyClass { public static void myStaticMethod() {} }",
"public static boolean isInstanceOf(Object obj, Class<?> clazz) { return clazz.isInstance(obj); }",
"public static Object getAttribute(Object obj, String attribute) throws Exception { return obj.getClass().getDeclaredField(attribute).get(obj); }",
"public static void setAttribute(Object obj, String attribute, Object value) throws Exception { obj.getClass().getDeclaredField(attribute).set(obj, value); }",
"public static void deleteAttribute(Object obj, String attribute) throws Exception { obj.getClass().getDeclaredField(attribute).set(obj, null); }",
"try { int result = 10 / 0; } catch (Exception e) { System.out.println(e.getMessage()); }",
"throw new Exception('Custom exception');",
"String message = e.getMessage();",
"Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);",
"long startTime = System.currentTimeMillis();",
"long endTime = System.currentTimeMillis(); long duration = endTime - startTime;",
"for (int i = 0; i <= 100; i++) { System.out.print('\\rProgress: ' + i + '%'); }",
"Thread.sleep(1000);",
"Runnable r = () -> System.out.println('Lambda expression');",
"List<Integer> squared = Arrays.asList(1, 2, 3).stream().map(x -> x * x).collect(Collectors.toList());",
"List<Integer> evenNumbers = Arrays.asList(1, 2, 3, 4).stream().filter(x -> x % 2 == 0).collect(Collectors.toList());",
"int sum = Arrays.asList(1, 2, 3).stream().reduce(0, (a, b) -> a + b);",
"List<Integer> squares = Arrays.asList(1, 2, 3).stream().map(x -> x * x).collect(Collectors.toList());",
"Map<String, Integer> map = Arrays.asList('a', 'b').stream().collect(Collectors.toMap(Function.identity(), String::length));",
"Set<Integer> set = Arrays.asList(1, 2, 3).stream().collect(Collectors.toSet());",
"Set<Integer> intersection = new HashSet<>(set1); intersection.retainAll(set2);",
"Set<Integer> union = new HashSet<>(set1); union.addAll(set2);",
"Set<Integer> difference = new HashSet<>(set1); difference.removeAll(set2);",
"List<String> listWithoutNull = list.stream().filter(Objects::nonNull).collect(Collectors.toList());",
"try (BufferedReader br = new BufferedReader(new FileReader('file.txt'))) { } catch (IOException e) { }",
"if (variable instanceof Integer) { }",
"boolean bool = Boolean.parseBoolean('true');",
"if (condition) { }",
"while (condition) { }",
"for (String item : list) { }",
"for (Map.Entry<String, Integer> entry : map.entrySet()) { }",
"for (char c : 'string'.toCharArray()) { }",
"break;",
"continue;",
"void myFunction() { }",
"void myFunction(String param = 'default') { }",
"return new Object[] { value1, value2 };",
"void myFunction(String... args) { }",
"void myFunction(Map<String, String> kwargs) { }",
"long startTime = System.currentTimeMillis(); myFunction(); long endTime = System.currentTimeMillis(); long duration = endTime - startTime;",
"@Decorator public void myFunction() { }",
"Map<String, Object> cache = new HashMap<>();",
"Stream<Integer> stream = Stream.of(1, 2, 3);",
"yield return value;",
"int nextValue = generator.next();",
"Iterator<Integer> iterator = list.iterator();",
"while (iterator.hasNext()) { int next = iterator.next(); }",
"for (int i = 0; i < list.size(); i++) { System.out.println(i + ' ' + list.get(i)); }",
"List<String> combined = Stream.concat(list1.stream(), list2.stream()).collect(Collectors.toList());",
"Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < keys.size(); i++) { map.put(keys.get(i), values.get(i)); }",
"boolean equal = list1.equals(list2);",
"boolean equal = map1.equals(map2);",
"boolean equal = set1.equals(set2);",
"Set<Integer> uniqueSet = new HashSet<>(list);",
"set.clear();",
"boolean isEmpty = set.isEmpty();",
"set.add(element);",
"set.remove(element);",
"boolean contains = set.contains(element);",
"int size = set.size();",
"boolean hasIntersection = !Collections.disjoint(set1, set2);",
"boolean isSubset = set1.containsAll(set2);",
"boolean isSubstring = 'hello'.contains('ell');",
"char firstChar = 'hello'.charAt(0);",
"char lastChar = 'hello'.charAt('hello'.length() - 1);",
"boolean isTextFile = fileName.endsWith('.txt');",
"boolean isImageFile = fileName.endsWith('.jpg') || fileName.endsWith('.png');",
"long rounded = Math.round(3.14);",
"long ceil = (long) Math.ceil(3.14);",
"long floor = (long) Math.floor(3.14);",
"String formatted = String.format('%.2f', 3.14159);",
"String randomString = new Random().ints(10, 97, 123).mapToObj(i -> (char) i).collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();",
"boolean exists = new File('path').exists();",
"File[] files = new File('path').listFiles();",
"String extension = fileName.substring(fileName.lastIndexOf('.') + 1);",
"String fileName = new File('path').getName();",
"String fullPath = new File('path').getAbsolutePath();",
"String version = System.getProperty('java.version');",
"String os = System.getProperty('os.name');",
"int cores = Runtime.getRuntime().availableProcessors();",
"long memory = Runtime.getRuntime().totalMemory();",
"File file = new File('path'); long freeSpace = file.getFreeSpace();",
"String ip = InetAddress.getLocalHost().getHostAddress();",
"boolean isConnected = InetAddress.getByName('www.google.com').isReachable(1000);",
"URL url = new URL('http://example.com/file.txt'); try (InputStream in = url.openStream()) { Files.copy(in, Paths.get('file.txt'), StandardCopyOption.REPLACE_EXISTING); }",
"HttpURLConnection connection = (HttpURLConnection) new URL('http://example.com').openConnection(); connection.setRequestMethod('POST');",
"HttpURLConnection connection = (HttpURLConnection) new URL('http://example.com').openConnection(); connection.setRequestMethod('GET'); connection.setRequestProperty('User-Agent', 'Mozilla/5.0');",
"Document doc = Jsoup.connect('http://example.com').get();",
"String title = doc.title();",
"Elements links = doc.select('a[href]');",
"Elements images = doc.select('img[src]');",
"Map<String, Integer> wordFrequency = new HashMap<>(); for (String word : text.split(' ')) { wordFrequency.put(word, wordFrequency.getOrDefault(word, 0) + 1); }",
"Connection.Response loginForm = Jsoup.connect('http://example.com/login').method(Connection.Method.GET).execute(); Map<String, String> cookies = loginForm.cookies(); Document doc = Jsoup.connect('http://example.com/login').data('username', 'user', 'password', 'pass').cookies(cookies).post();",
"String text = Jsoup.parse(html).text();",
"Pattern pattern = Pattern.compile('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}'); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); }",
"Pattern pattern = Pattern.compile('\\d{3}-\\d{3}-\\d{4}'); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); }",
"Pattern pattern = Pattern.compile('\\d+'); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println(matcher.group()); }",
"String replaced = text.replaceAll('pattern', 'replacement');",
"boolean matches = Pattern.matches('pattern', text);",
"String text = html.replaceAll('<[^>]+>', '');",
"String encoded = StringEscapeUtils.escapeHtml4(html);",
"String decoded = StringEscapeUtils.unescapeHtml4(html);",
"JFrame frame = new JFrame('Simple GUI'); frame.setSize(300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true);",
"JFrame frame = new JFrame(); JButton button = new JButton(\"Click Me\"); frame.add(button);",
"button.addActionListener(e -> JOptionPane.showMessageDialog(frame, \"Button Clicked!\"));",
"String input = JOptionPane.showInputDialog(frame, \"Enter something:\");",
"frame.setTitle(\"My Window\");",
"frame.setSize(400, 300);",
"frame.setLocationRelativeTo(null);",
"JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu(\"File\"); menuBar.add(menu); frame.setJMenuBar(menuBar);",
"JComboBox<String> comboBox = new JComboBox<>(new String[]{\"Option 1\", \"Option 2\"}); frame.add(comboBox);",
"JRadioButton radioButton = new JRadioButton(\"Select Me\"); frame.add(radioButton);",
"JCheckBox checkBox = new JCheckBox(\"Check Me\"); frame.add(checkBox);",
"JLabel label = new JLabel(new ImageIcon(\"image.jpg\")); frame.add(label);",
"Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(new File(\"audio.wav\"))); clip.start();",
"JFrame videoFrame = new JFrame(); Player player = Manager.createRealizedPlayer(new File(\"video.mp4\").toURI().toURL()); player.start();",
"long currentTime = player.getTimeNanoseconds();",
"Robot robot = new Robot(); BufferedImage screenshot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));",
"Robot robot = new Robot(); robot.delay(5000); BufferedImage screenRecording = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));",
"PointerInfo pointerInfo = MouseInfo.getPointerInfo(); Point point = pointerInfo.getLocation();",
"Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_A); robot.keyRelease(KeyEvent.VK_A);",
"Robot robot = new Robot(); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);",
"long timestamp = System.currentTimeMillis();",
"Date date = new Date(timestamp);",
"long timestamp = date.getTime();",
"int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);",
"int daysInMonth = Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);",
"Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_YEAR, 1); Date firstDayOfYear = calendar.getTime();",
"Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_YEAR, calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); Date lastDayOfYear = calendar.getTime();",
"Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, 1); Date firstDayOfMonth = calendar.getTime();",
"Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); Date lastDayOfMonth = calendar.getTime();",
"int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); boolean isWeekday = dayOfWeek >= Calendar.MONDAY && dayOfWeek <= Calendar.FRIDAY;",
"int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); boolean isWeekend = dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY;",
"int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);",
"int minute = Calendar.getInstance().get(Calendar.MINUTE);",
"int second = Calendar.getInstance().get(Calendar.SECOND);",
"Thread.sleep(1000);",
"long millisTimestamp = System.currentTimeMillis();",
"SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\"); String formattedDate = sdf.format(new Date());",
"SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\"); Date date = sdf.parse(\"2023-10-01 12:00:00\");",
"Thread thread = new Thread(() -> {}); thread.start();",
"Thread.sleep(1000);",
"ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> {}); executor.submit(() -> {});",
"String threadName = Thread.currentThread().getName();",
"Thread thread = new Thread(() -> {}); thread.setDaemon(true); thread.start();",
"ReentrantLock lock = new ReentrantLock(); lock.lock(); try {} finally { lock.unlock(); }",
"Process process = Runtime.getRuntime().exec(\"notepad.exe\");",
"long pid = process.pid();",
"boolean isAlive = process.isAlive();",
"ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> {}); executor.submit(() -> {});",
"BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(); queue.put(1); int value = queue.take();",
"PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(in);",
"Thread.sleep(1000);",
"Process process = Runtime.getRuntime().exec(\"ls\");",
"BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = reader.readLine();",
"int exitCode = process.waitFor();",
"boolean isSuccess = exitCode == 0;",
"String scriptPath = new File(\"\").getAbsolutePath();",
"String[] args = new String[]{\"arg1\", \"arg2\"};",
"Parser parser = new Parser(); parser.parse(args);",
"parser.printHelp();",
"ModuleLayer layer = ModuleLayer.boot(); layer.modules().forEach(System.out::println);",
"Process process = Runtime.getRuntime().exec(\"pip install package\");",
"Process process = Runtime.getRuntime().exec(\"pip uninstall package\");",
"String version = Package.getPackage(\"package\").getImplementationVersion();",
"Process process = Runtime.getRuntime().exec(\"python -m venv venv\");",
"Process process = Runtime.getRuntime().exec(\"pip list\");",
"Process process = Runtime.getRuntime().exec(\"pip install --upgrade package\");",
"Connection conn = DriverManager.getConnection(\"jdbc:sqlite:sample.db\");",
"Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(\"SELECT * FROM table\");",
"PreparedStatement pstmt = conn.prepareStatement(\"INSERT INTO table (column) VALUES (?)\"); pstmt.setString(1, \"value\"); pstmt.executeUpdate();",
"PreparedStatement pstmt = conn.prepareStatement(\"DELETE FROM table WHERE id = ?\"); pstmt.setInt(1, 1); pstmt.executeUpdate();",
"PreparedStatement pstmt = conn.prepareStatement(\"UPDATE table SET column = ? WHERE id = ?\"); pstmt.setString(1, \"new_value\"); pstmt.setInt(2, 1); pstmt.executeUpdate();",
"PreparedStatement pstmt = conn.prepareStatement(\"SELECT * FROM table\"); ResultSet rs = pstmt.executeQuery();",
"PreparedStatement pstmt = conn.prepareStatement(\"SELECT * FROM table WHERE column = ?\"); pstmt.setString(1, \"value\"); ResultSet rs = pstmt.executeQuery();",
"conn.close();",
"Statement stmt = conn.createStatement(); stmt.execute(\"CREATE TABLE table (id INT, column VARCHAR(255))\");",
"Statement stmt = conn.createStatement(); stmt.execute(\"DROP TABLE table\");",
"DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs = metaData.getTables(null, null, \"table\", null); boolean exists = rs.next();",
"DatabaseMetaData metaData = conn.getMetaData(); ResultSet rs = metaData.getTables(null, null, null, new String[]{\"TABLE\"});",
"Session session = sessionFactory.openSession(); session.save(new Entity());",
"Session session = sessionFactory.openSession(); List<Entity> entities = session.createQuery(\"FROM Entity\").list();",
"Session session = sessionFactory.openSession(); session.delete(session.get(Entity.class, 1));",
"Session session = sessionFactory.openSession(); Entity entity = session.get(Entity.class, 1); entity.setColumn(\"new_value\"); session.update(entity);",
"class Entity { @Id @GeneratedValue private int id; private String column; }",
"class ChildEntity extends ParentEntity {}",
"class Entity { @Id @GeneratedValue private int id; }",
"class Entity { @Column(unique = true) private String column; }",
"class Entity { @Column(columnDefinition = \"VARCHAR(255) DEFAULT 'default_value'\") private String column; }",
"CSVWriter writer = new CSVWriter(new FileWriter(\"output.csv\")); writer.writeNext(new String[]{\"column1\", \"column2\"});",
"Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(\"Sheet1\"); FileOutputStream fileOut = new FileOutputStream(\"workbook.xlsx\"); workbook.write(fileOut);",
"Gson gson = new Gson(); String json = gson.toJson(new Entity());",
"Workbook workbook = WorkbookFactory.create(new File(\"workbook.xlsx\")); Sheet sheet = workbook.getSheetAt(0);",
"Workbook workbook1 = WorkbookFactory.create(new File(\"workbook1.xlsx\")); Workbook workbook2 = WorkbookFactory.create(new File(\"workbook2.xlsx\")); Sheet sheet = workbook1.createSheet(\"Merged\");",
"Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet(\"New Sheet\");",
"Sheet sheet1 = workbook.getSheetAt(0); Sheet sheet2 = workbook.createSheet(\"Copy\"); CellStyle style = sheet1.getRow(0).getCell(0).getCellStyle(); sheet2.getRow(0).getCell(0).setCellStyle(style);",
"CellStyle style = workbook.createCellStyle(); style.setFillForegroundColor(IndexedColors.RED.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND);",
"Font font = workbook.createFont(); font.setBold(true); CellStyle style = workbook.createCellStyle(); style.setFont(font);",
"Sheet sheet = workbook.getSheetAt(0); String cellValue = sheet.getRow(0).getCell(0).getStringCellValue();",
"Sheet sheet = workbook.getSheetAt(0); sheet.getRow(0).getCell(0).setCellValue(\"New Value\");",
"BufferedImage image = ImageIO.read(new File(\"image.jpg\")); int width = image.getWidth(); int height = image.getHeight();",
"BufferedImage originalImage = ImageIO.read(new File(\"image.jpg\")); BufferedImage resizedImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, 100, 100, null);"
]
# 全局服务状态
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 = """
<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 请求
@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)
|