Spaces:
Sleeping
Sleeping
Update app.py
Browse files13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731813 unmodified lines# 预定义代码片段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);"13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935013 unmodified lines# 预定义代码片段CODE_SNIPPETS = ["print('Hello, World!')","def add(a, b): return a + b","import random; def generate_random(): return random.randint(1, 100)","def is_even(n): return n % 2 == 0","def string_length(s): return len(s)","from datetime import date; def get_current_date(): return date.today()","import os; def file_exists(path): return os.path.exists(path)","def read_file(path): return open(path, 'r').read()","def write_file(path, content): open(path, 'w').write(content)","from datetime import datetime; def get_current_time(): return datetime.now()","def to_upper(s): return s.upper()","def to_lower(s): return s.lower()","def reverse_string(s): return s[::-1]","def list_length(lst): return len(lst)","def list_max(lst): return max(lst)","def list_min(lst): return min(lst)","def sort_list(lst): return sorted(lst)","def merge_lists(lst1, lst2): return lst1 + lst2","def remove_element(lst, element): lst.remove(element)","def is_list_empty(lst): return len(lst) == 0","def count_char(s, char): return s.count(char)","def contains_substring(s, sub): return sub in s","def int_to_str(n): return str(n)","def str_to_int(s): return int(s)","def is_numeric(s): return s.isdigit()","def get_index(lst, element): return lst.index(element)","def clear_list(lst): lst.clear()","def reverse_list(lst): lst.reverse()","def remove_duplicates(lst): return list(set(lst))","def is_in_list(lst, value): return value in lst","def create_dict(): return {}","def add_to_dict(d, key, value): d[key] = value","def delete_key(d, key): del d[key]","def get_keys(d): return list(d.keys())","def get_values(d): return list(d.values())","def merge_dicts(d1, d2): return {**d1, **d2}","def is_dict_empty(d): return len(d) == 0","def get_value(d, key): return d[key]","def key_exists(d, key): return key in d","def clear_dict(d): d.clear()","def count_lines(path): return len(open(path).readlines())","def write_list_to_file(path, lst): open(path, 'w').write('\\n'.join(map(str, lst)))","def read_list_from_file(path): return open(path, 'r').read().splitlines()","def count_words(path): return len(open(path, 'r').read().split())","def is_leap_year(year): return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)","from datetime import datetime; def format_time(dt): return dt.strftime('%Y-%m-%d %H:%M:%S')","from datetime import date; def days_between(d1, d2): return (d2 - d1).days","import os; def get_current_dir(): return os.getcwd()","import os; def list_files(path): return os.listdir(path)","import os; def create_dir(path): os.mkdir(path)""import os; def remove_dir(path): os.rmdir(path)","import os; def is_file(path): return os.path.isfile(path)","import os; def is_dir(path): return os.path.isdir(path)","import os; def get_file_size(path): return os.path.getsize(path)","import os; def rename_file(src, dst): os.rename(src, dst)","import shutil; def copy_file(src, dst): shutil.copy(src, dst)","import shutil; def move_file(src, dst): shutil.move(src, dst)","import os; def delete_file(path): os.remove(path)","import os; def get_env_var(key): return os.getenv(key)","import os; def set_env_var(key, value): os.environ[key] = value","import webbrowser; def open_url(url): webbrowser.open(url)","import requests; def send_get_request(url): return requests.get(url).text","import json; def parse_json(data): return json.loads(data)","import json; def write_json(data, path): open(path, 'w').write(json.dumps(data))","import json; def read_json(path): return json.loads(open(path, 'r').read())","def list_to_string(lst): return ''.join(lst)","def string_to_list(s): return list(s)","def join_with_comma(lst): return ','.join(lst)","def join_with_newline(lst): return '\\n'.join(lst)","def split_by_space(s): return s.split()","def split_by_char(s, char): return s.split(char)","def split_to_chars(s): return list(s)","def replace_string(s, old, new): return s.replace(old, new)","def remove_spaces(s): return s.replace(' ', '')","import string; def remove_punctuation(s): return s.translate(str.maketrans('', '', string.punctuation))","def is_string_empty(s): return len(s) == 0","def is_palindrome(s): return s == s[::-1]","import csv; def write_csv(data, path): open(path, 'w', newline='').write('\\n'.join([','.join(map(str, row)) for row in data]))","import csv; def read_csv(path): return [row for row in csv.reader(open(path, 'r'))]","def count_csv_lines(path): return len(open(path).readlines())","import random; def shuffle_list(lst): random.shuffle(lst)","import random; def random_choice(lst): return random.choice(lst)","import random; def random_sample(lst, k): return random.sample(lst, k)","import random; def roll_dice(): return random.randint(1, 6)","import random; def flip_coin(): return random.choice(['Heads', 'Tails'])","import random; import string; def generate_password(length=8): return ''.join(random.choices(string.ascii_letters + string.digits, k=length))","import random; def generate_color(): return '#%06x' % random.randint(0, 0xFFFFFF)","import uuid; def generate_uuid(): return str(uuid.uuid4())","class MyClass: pass","def create_instance(): return MyClass()","class MyClass: def my_method(self): pass","class MyClass: def __init__(self): self.my_attr = None","class ChildClass(MyClass): pass","class ChildClass(MyClass): def my_method(self): pass","class MyClass: @classmethod def my_class_method(cls): pass","class MyClass: @staticmethod def my_static_method(): pass","def check_type(obj): return type(obj)","def get_attr(obj, attr): return getattr(obj, attr)","def set_attr(obj, attr, value): setattr(obj, attr, value)","def del_attr(obj, attr): delattr(obj, attr)","""try:x = 1 / 0except ZeroDivisionError:pass""","""class CustomError(Exception): passdef raise_custom_error(): raise CustomError('Error occurred')""","""try:x = 1 / 0except Exception as e: return str(e)""","""import logging; logging.basicConfig(filename='error.log', level=logging.ERROR); logging.error('Error occurred')""","""import time; def timer(): start = time.time(); return lambda: time.time() - start""","""import time; def run_time(): start = time.time(); return lambda: time.time() - start""","""import sys; def print_progress(progress): sys.stdout.write(f'\\rProgress: {progress}%'); sys.stdout.flush()""","""import time; def delay(seconds): time.sleep(seconds)""","lambda x: x * 2","map(lambda x: x * 2, [1, 2, 3])","filter(lambda x: x > 2, [1, 2, 3])","from functools import reduce; reduce(lambda x, y: x + y, [1, 2, 3])","[x * 2 for x in [1, 2, 3]]","{x: x * 2 for x in [1, 2, 3]}","{x for x in [1, 2, 3]}","set1 & set2","set1 | set2","set1 - set2","[x for x in lst if x is not None]","""try:with open('file.txt', 'r') as f: passexcept IOError: pass""","type(var)","bool(s)","if condition: pass","while condition: pass","for item in lst: pass","for key, value in d.items(): pass","for char in s: pass","for item in lst: if condition: break","for item in lst: if condition: continue","def my_func(): pass","def my_func(param=1): pass","def my_func(): return 1, 2","def my_func(*args): pass","def my_func(**kwargs): pass","""import time; def timer(func):def wrapper(*args, **kwargs):start = time.time()result = func(*args, **kwargs)print(f'Time: {time.time() - start}'); return resultreturn wrapper""","""def decorator(func):def wrapper(*args, **kwargs): return func(*args, **kwargs)return wrapper""","""from functools import lru_cache; @lru_cache(maxsize=None)def my_func(): pass""","def my_generator(): yield 1","gen = my_generator(); next(gen)","class MyIterator: def __iter__(self): return self; def __next__(self): pass","it = iter([1, 2, 3]); next(it)","for i, val in enumerate(lst): pass","list(zip(lst1, lst2))","dict(zip(keys, values))","lst1 == lst2","dict1 == dict2","set1 == set2","set(lst)","set.clear()","len(set) == 0","set.add(item)","set.remove(item)","item in set","len(set)","set1 & set2","set(lst1).issubset(lst2)","sub in s","s[0]","s[-1]","import mimetypes; mimetypes.guess_type(path)[0] == 'text/plain'","import mimetypes; mimetypes.guess_type(path)[0].startswith('image/')","round(num)","import math; math.ceil(num)","import math; math.floor(num)","f'{num:.2f}'","import random; import string; ''.join(random.choices(string.ascii_letters + string.digits, k=8))","import os; os.path.exists(path)","import os; for root, dirs, files in os.walk(path): pass","import os; os.path.splitext(path)[1]","import os; os.path.basename(path)","import os; os.path.abspath(path)","import platform; platform.python_version()","import platform; platform.system()","import multiprocessing; multiprocessing.cpu_count()","import psutil; psutil.virtual_memory().total","import psutil; psutil.disk_usage('/')","import socket; socket.gethostbyname(socket.gethostname())","import requests; try: requests.get('http://www.google.com'); return True; except: return False","import requests; def download_file(url, path): with open(path, 'wb') as f: f.write(requests.get(url).content)","def upload_file(path): with open(path, 'rb') as f: requests.post('http://example.com/upload', files={'file': f})","import requests; requests.post(url, data={'key': 'value'})","import requests; requests.get(url, params={'key': 'value'})","import requests; requests.get(url, headers={'key': 'value'})","from bs4 import BeautifulSoup; BeautifulSoup(html, 'html.parser')","from bs4 import BeautifulSoup; soup.title.text","from bs4 import BeautifulSoup; [a['href'] for a in soup.find_all('a')]","from bs4 import BeautifulSoup; import requests; for img in soup.find_all('img'): requests.get(img['src']).content","from collections import Counter; Counter(text.split())","import requests; session = requests.Session(); session.post(login_url, data={'username': 'user', 'password': 'pass'})","from bs4 import BeautifulSoup; soup.get_text()","import re; re.findall(r'[\\w.-]+@[\\w.-]+', text)","import re; re.findall(r'\\+?\\d[\\d -]{8,12}\\d', text)","import re; re.findall(r'\\d+', text)","import re; re.sub(pattern, repl, text)","import re; re.match(pattern, text)","from bs4 import BeautifulSoup; soup.get_text()","import html; html.escape(text)","import html; html.unescape(text)","import tkinter as tk; root = tk.Tk(); root.mainloop()","import tkinter as tk; def add_button(window, text): return tk.Button(window, text=text)","""def bind_click(button, func): button.config(command=func)""","""import tkinter.messagebox; def show_alert(message): tkinter.messagebox.showinfo('Info', message)""","""def get_entry_text(entry): return entry.get()""","def set_title(window, title): window.title(title)","def set_size(window, width, height): window.geometry(f'{width}x{height}')","""def center_window(window):window.update_idletasks()width = window.winfo_width()height = window.winfo_height()x = (window.winfo_screenwidth() // 2) - (width // 2)y = (window.winfo_screenheight() // 2) - (height // 2)window.geometry(f'{width}x{height}+{x}+{y}')""","""def create_menu(window): return tk.Menu(window)""","def create_combobox(window): return ttk.Combobox(window)","def create_radiobutton(window, text): return tk.Radiobutton(window, text=text)","def create_checkbutton(window, text): return tk.Checkbutton(window, text=text)","""from PIL import ImageTk, Image; def show_image(window, path):img = Image.open(path)photo = ImageTk.PhotoImage(img)label = tk.Label(window, image=photo)label.image = photoreturn label""","import pygame; def play_audio(path): pygame.mixer.init(); pygame.mixer.music.load(path); pygame.mixer.music.play()","import cv2; def play_video(path): cap = cv2.VideoCapture(path); while cap.isOpened(): ret, frame = cap.read()","def get_playback_time(): return pygame.mixer.music.get_pos()","import pyautogui; def screenshot(): return pyautogui.screenshot()","import pyautogui; import time; def record_screen(duration): return [pyautogui.screenshot() for _ in range(duration)]","def get_mouse_pos(): return pyautogui.position()","import pyautogui; def type_text(text): pyautogui.write(text)","import pyautogui; def click_mouse(x, y): pyautogui.click(x, y)","import time; def get_timestamp(): return int(time.time())","import datetime; def timestamp_to_date(ts): return datetime.datetime.fromtimestamp(ts)","import time; def date_to_timestamp(dt): return int(time.mktime(dt.timetuple()))","def get_weekday(): return datetime.datetime.now().strftime('%A')","import calendar; def get_month_days(): return calendar.monthrange(datetime.datetime.now().year, datetime.datetime.now().month)[1]","def first_day_of_year(): return datetime.date(datetime.datetime.now().year, 1, 1)","def last_day_of_year(): return datetime.date(datetime.datetime.now().year, 12, 31)","def first_day_of_month(month): return datetime.date(datetime.datetime.now().year, month, 1)","import calendar; def last_day_of_month(month): return datetime.date(datetime.datetime.now().year, month, calendar.monthrange(datetime.datetime.now().year, month)[1])","def is_weekday(): return datetime.datetime.now().weekday() < 5","def is_weekend(): return datetime.datetime.now().weekday() >= 5","def current_hour(): return datetime.datetime.now().hour","def current_minute(): return datetime.datetime.now().minute","def current_second(): return datetime.datetime.now().second","import time; def delay_1s(): time.sleep(1)","import time; def millis_timestamp(): return int(time.time() * 1000)","def format_time(dt, fmt='%Y-%m-%d %H:%M:%S'): return dt.strftime(fmt)","from dateutil.parser import parse; def parse_time(s): return parse(s)","import threading; def create_thread(target): return threading.Thread(target=target)","import time; def thread_pause(seconds): time.sleep(seconds)","def run_threads(*threads): [t.start() for t in threads]","import threading; def current_thread_name(): return threading.current_thread().name","def set_daemon(thread): thread.daemon = True","import threading; lock = threading.Lock()","import multiprocessing; def create_process(target): return multiprocessing.Process(target=target)","import os; def get_pid(): return os.getpid()","import psutil; def is_process_alive(pid): return psutil.pid_exists(pid)","def run_processes(*procs): [p.start() for p in procs]","from queue import Queue; q = Queue()","from multiprocessing import Pipe; parent_conn, child_conn = Pipe()","import os; def limit_cpu_usage(percent): os.system(f'cpulimit -p {os.getpid()} -l {percent}')","import subprocess; def run_command(cmd): subprocess.run(cmd, shell=True)","import subprocess; def get_command_output(cmd): return subprocess.check_output(cmd, shell=True).decode()","def get_exit_code(cmd): return subprocess.call(cmd, shell=True)","def is_success(code): return code == 0","import os; def script_path(): return os.path.realpath(__file__)","import sys; def get_cli_args(): return sys.argv[1:]","import argparse; parser = argparse.ArgumentParser()","parser.print_help()","help('modules')","import pip; def install_pkg(pkg): pip.main(['install', pkg])","import pip; def uninstall_pkg(pkg): pip.main(['uninstall', pkg])","import pkg_resources; def get_pkg_version(pkg): return pkg_resources.get_distribution(pkg).version","import venv; def create_venv(path): venv.create(path)","import pip; def list_pkgs(): return pip.get_installed_distributions()","import pip; def upgrade_pkg(pkg): pip.main(['install', '--upgrade', pkg])","import sqlite3; conn = sqlite3.connect(':memory:')","def execute_query(conn, query): return conn.execute(query)","""def insert_record(conn, table, data): conn.execute(f'INSERT INTO {table} VALUES ({",".join("?"*len(data))})', data)""","def delete_record(conn, table, condition): conn.execute(f'DELETE FROM {table} WHERE {condition}')","def update_record(conn, table, set_clause, condition): conn.execute(f'UPDATE {table} SET {set_clause} WHERE {condition}')","def fetch_all(conn, query): return conn.execute(query).fetchall()","def safe_query(conn, query, params): return conn.execute(query, params)","def close_db(conn): conn.close()","def create_table(conn, name, columns): conn.execute(f'CREATE TABLE {name} ({columns})')","def drop_table(conn, name): conn.execute(f'DROP TABLE {name}')","def table_exists(conn, name): return conn.execute(f\"SELECT name FROM sqlite_master WHERE type='table' AND name='{name}'\").fetchone()","def list_tables(conn): return conn.execute(\"SELECT name FROM sqlite_master WHERE type='table'\").fetchall()","""from sqlalchemy import Column, Integer, Stringclass User(Base):__tablename__ = 'users'id = Column(Integer, primary_key=True)name = Column(String)""","session.add(User(name='John'))","session.query(User).filter_by(name='John')","session.query(User).filter_by(name='John').delete()","session.query(User).filter_by(name='John').update({'name': 'Bob'})","Base = declarative_base()","class Admin(User): pass","id = Column(Integer, primary_key=True)","name = Column(String, unique=True)","name = Column(String, default='Unknown')","import csv; def export_csv(data, path): open(path, 'w').write('\\n'.join([','.join(map(str, row)) for row in data]))","import pandas as pd; pd.DataFrame(data).to_excel(path)","import json; json.dump(data, open(path, 'w'))","pd.read_excel(path).values.tolist()","pd.concat([pd.read_excel(f) for f in files])","with pd.ExcelWriter(path, mode='a') as writer: df.to_excel(writer, sheet_name='New')","from openpyxl.styles import copy; copy.copy(style)","from openpyxl.styles import PatternFill; cell.fill = PatternFill(start_color='FFFF00', fill_type='solid')","from openpyxl.styles import Font; cell.font = Font(bold=True)","sheet['A1'].value","sheet['A1'] = value","from PIL import Image; Image.open(path).size","from PIL import Image; Image.open(path).resize((w, h))"
app.py+331-299