Spaces:
Sleeping
Sleeping
Update app.py
Browse files13 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531613 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 lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483513 unmodified lines# 预定义代码片段CODE_SNIPPETS = ["fmt.Print(\"Hello, World!\")","func sum(a, b int) int { return a + b }","func randInt() int { return rand.Intn(100) }","func isEven(n int) bool { return n%2 == 0 }","func strLen(s string) int { return len(s) }","func currentDate() string { return time.Now().Format(\"2006-01-02\") }","func fileExists(path string) bool { _, err := os.Stat(path); return !os.IsNotExist(err) }","func readFile(path string) (string, error) { data, err := os.ReadFile(path); return string(data), err }","func writeFile(path, content string) error { return os.WriteFile(path, []byte(content), 0644) }","func currentTime() string { return time.Now().Format(\"15:04:05\") }","func toUpper(s string) string { return strings.ToUpper(s) }","func toLower(s string) string { return strings.ToLower(s) }","func reverseString(s string) string { runes := []rune(s); for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] }; return string(runes) }","func listLen(list []int) int { return len(list) }","func maxInList(list []int) int { return max(list...) }","func minInList(list []int) int { return min(list...) }","func sortList(list []int) []int { sort.Ints(list); return list }","func mergeLists(list1, list2 []int) []int { return append(list1, list2...) }","func removeFromList(list []int, elem int) []int { return append(list[:elem], list[elem+1:]...) }","func isListEmpty(list []int) bool { return len(list) == 0 }","func countChar(s string, c rune) int { return strings.Count(s, string(c)) }","func containsSubstring(s, substr string) bool { return strings.Contains(s, substr) }","func intToString(n int) string { return strconv.Itoa(n) }","func stringToInt(s string) int { n, _ := strconv.Atoi(s); return n }","func isNumeric(s string) bool { _, err := strconv.Atoi(s); return err == nil }","func indexInList(list []int, elem int) int { for i, v := range list { if v == elem { return i } }; return -1 }","func clearList(list []int) []int { return list[:0] }","func reverseList(list []int) []int { for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 { list[i], list[j] = list[j], list[i] }; return list }","func removeDuplicates(list []int) []int { seen := make(map[int]bool); result := []int{}; for _, v := range list { if !seen[v] { seen[v] = true; result = append(result, v) } }; return result }","func isInList(list []int, elem int) bool { for _, v := range list { if v == elem { return true } }; return false }","func createDict() map[string]int { return make(map[string]int) }","func addToDict(dict map[string]int, key string, value int) { dict[key] = value }","func deleteFromDict(dict map[string]int, key string) { delete(dict, key) }","func dictKeys(dict map[string]int) []string { keys := []string{}; for k := range dict { keys = append(keys, k) }; return keys }","func dictValues(dict map[string]int) []int { values := []int{}; for _, v := range dict { values = append(values, v) }; return values }","func mergeDicts(dict1, dict2 map[string]int) map[string]int { for k, v := range dict2 { dict1[k] = v }; return dict1 }","func isDictEmpty(dict map[string]int) bool { return len(dict) == 0 }","func dictValue(dict map[string]int, key string) int { return dict[key] }","func keyInDict(dict map[string]int, key string) bool { _, ok := dict[key]; return ok }","func clearDict(dict map[string]int) { for k := range dict { delete(dict, k) } }","func countFileLines(path string) (int, error) { data, err := os.ReadFile(path); if err != nil { return 0, err }; return len(strings.Split(string(data), \"\n\")), nil }","func writeListToFile(path string, list []int) error { data := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(list)), \" \"), \"[]\"); return os.WriteFile(path, []byte(data), 0644) }","func readListFromFile(path string) ([]int, error) { data, err := os.ReadFile(path); if err != nil { return nil, err }; var list []int; for _, v := range strings.Fields(string(data)) { n, _ := strconv.Atoi(v); list = append(list, n) }; return list, nil }","func countFileWords(path string) (int, error) { data, err := os.ReadFile(path); if err != nil { return 0, err }; return len(strings.Fields(string(data))), nil }","func isLeapYear(year int) bool { return year%4 == 0 && (year%100 != 0 || year%400 == 0) }","func formatTime(t time.Time, layout string) string { return t.Format(layout) }","func daysBetweenDates(date1, date2 time.Time) int { return int(date2.Sub(date1).Hours() / 24) }","func currentDir() string { dir, _ := os.Getwd(); return dir }","func listFiles(path string) ([]string, error) { files, err := os.ReadDir(path); if err != nil { return nil, err }; var names []string; for _, file := range files { names = append(names, file.Name()) }; return names, nil }","func createDir(path string) error { return os.Mkdir(path, 0755) }","func deleteDir(path string) error { return os.RemoveAll(path) }","func isFile(path string) bool { info, err := os.Stat(path); return err == nil && !info.IsDir() }","func isDir(path string) bool { info, err := os.Stat(path); return err == nil && info.IsDir() }","func fileSize(path string) (int64, error) { info, err := os.Stat(path); if err != nil { return 0, err }; return info.Size(), nil }","func renameFile(oldPath, newPath string) error { return os.Rename(oldPath, newPath) }","func copyFile(src, dst string) error { data, err := os.ReadFile(src); if err != nil { return err }; return os.WriteFile(dst, data, 0644) }","func moveFile(src, dst string) error { return os.Rename(src, dst) }","func deleteFile(path string) error { return os.Remove(path) }","func getEnvVar(key string) string { return os.Getenv(key) }","func setEnvVar(key, value string) error { return os.Setenv(key, value) }","func openURL(url string) error { return exec.Command(\"xdg-open\", url).Start() }","func sendGetRequest(url string) (string, error) { resp, err := http.Get(url); if err != nil { return \"\", err }; defer resp.Body.Close(); body, err := io.ReadAll(resp.Body); if err != nil { return \"\", err }; return string(body), nil }","func parseJSON(data string) (map[string]interface{}, error) { var result map[string]interface{}; err := json.Unmarshal([]byte(data), &result); return result, err }","func writeJSONToFile(path string, data map[string]interface{}) error { jsonData, err := json.Marshal(data); if err != nil { return err }; return os.WriteFile(path, jsonData, 0644) }","func readJSONFromFile(path string) (map[string]interface{}, error) { data, err := os.ReadFile(path); if err != nil { return nil, err }; var result map[string]interface{}; err = json.Unmarshal(data, &result); return result, err }","func listToString(list []int) string { return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(list)), \" \"), \"[]\") }","func stringToList(s string) []int { var list []int; for _, v := range strings.Fields(s) { n, _ := strconv.Atoi(v); list = append(list, n) }; return list }","func joinListWithComma(list []int) string { return strings.Join(strings.Fields(fmt.Sprint(list)), \",\") }","func joinListWithNewline(list []int) string { return strings.Join(strings.Fields(fmt.Sprint(list)), \"\n\") }","func splitStringBySpace(s string) []string { return strings.Fields(s) }","func splitStringByDelimiter(s, delimiter string) []string { return strings.Split(s, delimiter) }","func splitStringToChars(s string) []string { return strings.Split(s, \"\") }","func replaceString(s, old, new string) string { return strings.ReplaceAll(s, old, new) }","func removeSpaces(s string) string { return strings.ReplaceAll(s, \" \", \"\") }","func removePunctuation(s string) string { return strings.Map(func(r rune) rune { if unicode.IsPunct(r) { return -1 }; return r }, s) }","func isStringEmpty(s string) bool { return len(s) == 0 }","func isPalindrome(s string) bool { return s == reverseString(s) }","func writeCSV(path string, data [][]string) error { file, err := os.Create(path); if err != nil { return err }; defer file.Close(); writer := csv.NewWriter(file); return writer.WriteAll(data) }","func readCSV(path string) ([][]string, error) { file, err := os.Open(path); if err != nil { return nil, err }; defer file.Close(); reader := csv.NewReader(file); return reader.ReadAll() }","func countCSVLines(path string) (int, error) { data, err := readCSV(path); if err != nil { return 0, err }; return len(data), nil }","func shuffleList(list []int) []int { rand.Shuffle(len(list), func(i, j int) { list[i], list[j] = list[j], list[i] }); return list }","func randomElement(list []int) int { return list[rand.Intn(len(list))] }","func randomElements(list []int, n int) []int { rand.Shuffle(len(list), func(i, j int) { list[i], list[j] = list[j], list[i] }); return list[:n] }","func rollDice() int { return rand.Intn(6) + 1 }","func flipCoin() string { if rand.Intn(2) == 0 { return \"Heads\" }; return \"Tails\" }","func generatePassword(length int) string { chars := \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()\"; password := make([]byte, length); for i := range password { password[i] = chars[rand.Intn(len(chars))] }; return string(password) }","func randomColor() string { return fmt.Sprintf(\"#%06x\", rand.Intn(0xffffff)) }","func generateUUID() string { return uuid.New().String() }","type MyClass struct{}","func NewMyClass() *MyClass { return &MyClass{} }","func (m *MyClass) MyMethod() {}","type MyClass struct { MyAttribute int }","type ChildClass struct { MyClass }","func (c *ChildClass) MyMethod() {}","func (m *MyClass) MyClassMethod() {}","func MyStaticMethod() {}","func isInstanceOf(obj interface{}, t reflect.Type) bool { return reflect.TypeOf(obj) == t }","func getAttribute(obj interface{}, attr string) interface{} { return reflect.ValueOf(obj).FieldByName(attr).Interface() }","func setAttribute(obj interface{}, attr string, value interface{}) { reflect.ValueOf(obj).FieldByName(attr).Set(reflect.ValueOf(value)) }","func deleteAttribute(obj interface{}, attr string) { reflect.ValueOf(obj).FieldByName(attr).Set(reflect.Zero(reflect.TypeOf(obj).FieldByName(attr).Type)) }","func handleException() { defer func() { if r := recover(); r != nil { fmt.Println(\"Recovered:\", r) } }(); panic(\"An error occurred\") }","""func customError() error {return errors.New("custom error")}""","""func getErrorInfo() {if err := customError(); err != nil {fmt.Println("Error:", err)}}""","""func logError() {if err := customError(); err != nil {log.Println("Error:", err)}}""","""func timer() func() {start := time.Now()return func() {fmt.Println(time.Since(start))}}""","""func runtime() {start := time.Now()time.Sleep(1 * time.Second)fmt.Println(time.Since(start))}""","""func progressBar() {for i := 0; i <= 100; i += 10 {fmt.Printf("\r[%-10s] %d%%", strings.Repeat("=", i/10), i)time.Sleep(100 * time.Millisecond)}fmt.Println()}""","""func delay() {time.Sleep(1 * time.Second)}""","lambda := func(x int) int { return x * x }","result := map(lambda, []int{1, 2, 3, 4})","result := filter(func(x int) bool { return x > 2 }, []int{1, 2, 3, 4})","result := reduce(func(a, b int) int { return a + b }, []int{1, 2, 3, 4})","result := [x * x for x in [1, 2, 3, 4]]","result := {x: x * x for x in [1, 2, 3, 4]}","result := {x * x for x in [1, 2, 3, 4]}","result := intersection(set1, set2)","result := union(set1, set2)","result := difference(set1, set2)","result := [x for x in [1, None, 2, None, 3] if x is not None]","""func checkFile(filename string) {file, err := os.Open(filename)if err != nil {fmt.Println("Error:", err)} else {file.Close()}}""","""func checkType(v interface{}) {fmt.Printf("Type: %T\n", v)}""","""func strToBool(s string) bool {return s == "true"}""","""func ifCondition(x int) {if x > 0 {fmt.Println("Positive")} else {fmt.Println("Non-positive")}}""","""func whileLoop() {i := 0while i < 10 {fmt.Println(i)i++}}""","""func forList() {for _, v := range []int{1, 2, 3} {fmt.Println(v)}}""","""func forDict() {for k, v := range map[string]int{"a": 1, "b": 2} {fmt.Println(k, v)}}""","""func forString() {for _, c := range "hello" {fmt.Println(c)}}""","""func breakLoop() {for i := 0; i < 10; i++ {if i == 5 {break}fmt.Println(i)}}""","""func continueLoop() {for i := 0; i < 10; i++ {if i == 5 {continue}fmt.Println(i)}}""","""func defineFunc() {fmt.Println("Function defined")}""","""func defaultParam(x int = 10) {fmt.Println(x)}""","""func returnMultiple() (int, string) {return 1, "hello"}""","""func variadicParams(nums ...int) {fmt.Println(nums)}""","""func keywordParams(a int, b string) {fmt.Println(a, b)}""","""func measureTime() {start := time.Now()time.Sleep(1 * time.Second)fmt.Println(time.Since(start))}""","""func decorator(f func()) func() {return func() {fmt.Println("Before")f()fmt.Println("After")}}""","""func cacheResult(f func() int) func() int {var result intreturn func() int {if result == 0 {result = f()}return result}}""","""func createGenerator() func() int {i := 0return func() int {i++return i}}""","""func yieldValue() chan int {ch := make(chan int)go func() {ch <- 1ch <- 2close(ch)}()return ch}""","""func nextValue() {ch := yieldValue()fmt.Println(<-ch)fmt.Println(<-ch)}""","""func createIterator() func() (int, bool) {i := 0return func() (int, bool) {if i < 3 {i++return i, true}return 0, false}}""","""func manualIterate() {it := createIterator()for {v, ok := it()if !ok {break}fmt.Println(v)}}""","""func useEnumerate() {for i, v := range []string{"a", "b", "c"} {fmt.Println(i, v)}}""","""func useZip() {for a, b := range zip([]int{1, 2}, []string{"a", "b"}) {fmt.Println(a, b)}}""","""func listToDict() {dict := make(map[int]string)for i, v := range []string{"a", "b"} {dict[i] = v}fmt.Println(dict)}""","""func compareLists() {fmt.Println(reflect.DeepEqual([]int{1, 2}, []int{1, 2}))}""","""func compareDicts() {fmt.Println(reflect.DeepEqual(map[string]int{"a": 1}, map[string]int{"a": 1}))}""","""func compareSets() {fmt.Println(reflect.DeepEqual(map[int]bool{1: true}, map[int]bool{1: true}))}""","""func removeDuplicates() {set := make(map[int]bool)for _, v := range []int{1, 2, 2, 3} {set[v] = true}fmt.Println(set)}""","""func clearSet() {set := map[int]bool{1: true, 2: true}for k := range set {delete(set, k)}fmt.Println(set)}""","func isEmptySet(s map[interface{}]struct{}) bool { return len(s) == 0 }", "func addToSet(s map[interface{}]struct{}, element interface{}) { s[element] = struct{}{} }", "func removeFromSet(s map[interface{}]struct{}, element interface{}) { delete(s, element) }", "func containsInSet(s map[interface{}]struct{}, element interface{}) bool { _, exists := s[element]; return exists }", "func getSetLength(s map[interface{}]struct{}) int { return len(s) }", "func hasIntersection(s1, s2 map[interface{}]struct{}) bool { for k := range s1 { if _, exists := s2[k]; exists { return true } } return false }", "func isSubset(s1, s2 map[interface{}]struct{}) bool { for k := range s1 { if _, exists := s2[k]; !exists { return false } } return true }", "func isSubstring(s, substr string) bool { return strings.Contains(s, substr) }", "func getFirstChar(s string) string { return string(s[0]) }", "func getLastChar(s string) string { return string(s[len(s)-1]) }", "func isTextFile(filename string) bool { return strings.HasSuffix(filename, \".txt\") }", "func isImageFile(filename string) bool { ext := strings.ToLower(filepath.Ext(filename)); return ext == \".jpg\" || ext == \".png\" || ext == \".gif\" }", "func roundNumber(num float64) float64 { return math.Round(num) }", "func ceilNumber(num float64) float64 { return math.Ceil(num) }", "func floorNumber(num float64) float64 { return math.Floor(num) }", "func formatDecimal(num float64, precision int) string { return fmt.Sprintf(\"%.*f\", precision, num) }", "func generateRandomString(length int) string { rand.Seed(time.Now().UnixNano()); b := make([]byte, length); rand.Read(b); return fmt.Sprintf(\"%x\", b)[:length] }", "func pathExists(path string) bool { _, err := os.Stat(path); return !os.IsNotExist(err) }", """func listFilesInDir(dir string) []string {var files []stringfilepath.Walk(dir, func(path string, info os.FileInfo, err error) error {if !info.IsDir() {files = append(files, path)}return nil})return files}""", "func getFileExtension(filename string) string { return filepath.Ext(filename) }", "func getFileName(filename string) string { return filepath.Base(filename) }", "func getFullPath(filename string) string { absPath, _ := filepath.Abs(filename); return absPath }", "func getPythonVersion() string { return runtime.Version() }", "func getPlatformInfo() string { return runtime.GOOS }", "func getCPUCores() int { return runtime.NumCPU() }", "func getMemorySize() uint64 { var mem runtime.MemStats; runtime.ReadMemStats(&mem); return mem.Sys }", """func getDiskUsage() string {var stat syscall.Statfs_tsyscall.Statfs("/", &stat)return fmt.Sprintf("Total: %d, Free: %d", stat.Blocks*uint64(stat.Bsize), stat.Bavail*uint64(stat.Bsize))}""", "func getIPAddress() string { conn, _ := net.Dial(\"udp\", \"8.8.8.8:80\"); defer conn.Close(); return conn.LocalAddr().(*net.UDPAddr).IP.String() }", "func isConnected() bool { _, err := net.LookupIP(\"google.com\"); return err == nil }", """func downloadFile(url, filename string) error {resp, err := http.Get(url)if err != nil {return err}defer resp.Body.Close()out, err := os.Create(filename)if err != nil {return err}defer out.Close()_, err = io.Copy(out, resp.Body)return err}""", """func uploadFile(filename string) string {return fmt.Sprintf("File %s uploaded", filename)}""", """func sendPostRequest(url string, data map[string]string) (string, error) {jsonData, _ := json.Marshal(data)resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))if err != nil {return "", err}defer resp.Body.Close()body, _ := io.ReadAll(resp.Body)return string(body), nil}""", """func sendRequestWithParams(url string, params map[string]string) (string, error) {req, err := http.NewRequest("GET", url, nil)if err != nil {return "", err}q := req.URL.Query()for key, value := range params {q.Add(key, value)}req.URL.RawQuery = q.Encode()resp, err := http.DefaultClient.Do(req)if err != nil {return "", err}defer resp.Body.Close()body, _ := io.ReadAll(resp.Body)return string(body), nil}""", """func setRequestHeader(req *http.Request, headers map[string]string) {for key, value := range headers {req.Header.Set(key, value)}}""", """func parseHTML(htmlContent string) (*goquery.Document, error) {return goquery.NewDocumentFromReader(strings.NewReader(htmlContent))}""", """func extractTitle(doc *goquery.Document) string {return doc.Find("title").Text()}""", """func extractLinks(doc *goquery.Document) []string {var links []stringdoc.Find("a").Each(func(i int, s *goquery.Selection) {href, exists := s.Attr("href")if exists {links = append(links, href)}})return links}""", """func downloadImagesFromPage(url string) error {doc, err := goquery.NewDocument(url)if err != nil {return err}doc.Find("img").Each(func(i int, s *goquery.Selection) {src, exists := s.Attr("src")if exists {downloadFile(src, fmt.Sprintf("image%d.jpg", i))}})return nil}""", """func countWordFrequency(text string) map[string]int {words := strings.Fields(text)freq := make(map[string]int)for _, word := range words {freq[word]++}return freq}""", """func simulateLogin(url, username, password string) (string, error) {form := url.Values{}form.Add("username", username)form.Add("password", password)resp, err := http.PostForm(url, form)if err != nil {return "", err}defer resp.Body.Close()body, _ := io.ReadAll(resp.Body)return string(body), nil}""", """func htmlToText(htmlContent string) string {doc, _ := goquery.NewDocumentFromReader(strings.NewReader(htmlContent))return doc.Text()}""", """func extractEmails(text string) []string {re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}`)return re.FindAllString(text, -1)}""", """func extractPhoneNumbers(text string) []string {re := regexp.MustCompile(`\d{3}-\d{3}-\d{4}`)return re.FindAllString(text, -1)}""", """func findAllNumbers(text string) []string {re := regexp.MustCompile(`\d+`)return re.FindAllString(text, -1)}""", """func replaceWithRegex(text, pattern, replacement string) string {re := regexp.MustCompile(pattern)return re.ReplaceAllString(text, replacement)}""", """func matchRegex(text, pattern string) bool {re := regexp.MustCompile(pattern)return re.MatchString(text)}""", """func removeHTMLTags(htmlContent string) string {re := regexp.MustCompile(`<[^>]*>`)return re.ReplaceAllString(htmlContent, "")}""", """func encodeHTMLEntities(htmlContent string) string {return html.EscapeString(htmlContent)}""", """func decodeHTMLEntities(htmlContent string) string {return html.UnescapeString(htmlContent)}""", """func createGUIWindow() {window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)window.SetTitle("Simple GUI Window")window.Connect("destroy", func() {gtk.MainQuit()})window.ShowAll()gtk.Main()}""","func addButton(w fyne.Window) { w.SetContent(widget.NewButton(\"Button\", nil)) }","""func handleClick(b *widget.Button) {b.OnTapped = func() { fmt.Println("Clicked") }}""","""func showDialog(w fyne.Window) {dialog.ShowInformation("Title", "Message", w)}""","func getText(e *widget.Entry) string { return e.Text }","func setTitle(w fyne.Window) { w.SetTitle(\"Title\") }","func resizeWindow(w fyne.Window) { w.Resize(fyne.NewSize(800, 600)) }","func centerWindow(w fyne.Window) { w.CenterOnScreen() }","""func addMenu(w fyne.Window) {menu := fyne.NewMainMenu(fyne.NewMenu("File"))w.SetMainMenu(menu)}""","func createSelect() *widget.Select { return widget.NewSelect([]string{\"a\", \"b\"}, func(s string) {}) }","func createRadio() *widget.RadioGroup { return widget.NewRadioGroup([]string{\"a\", \"b\"}, func(s string) {}) }","func createCheck() *widget.Check { return widget.NewCheck(\"Check\", func(b bool) {}) }","func showImage() *canvas.Image { return canvas.NewImageFromFile(\"image.png\") }","""func playAudio() {exec.Command("afplay", "audio.mp3").Start()}""","""func playVideo() {exec.Command("vlc", "video.mp4").Start()}""","func getTimestamp() int64 { return time.Now().Unix() }","""func timestampToDate(ts int64) string {return time.Unix(ts, 0).Format("2006-01-02")}""","""func dateToTimestamp(date string) int64 {t, _ := time.Parse("2006-01-02", date)return t.Unix()}""","func getWeekday() string { return time.Now().Weekday().String() }","""func getMonthDays() int {return time.Date(time.Now().Year(), time.Now().Month()+1, 0, 0, 0, 0, 0, time.UTC).Day()}""","func firstDayOfYear() time.Time { return time.Date(time.Now().Year(), 1, 1, 0, 0, 0, 0, time.UTC) }","func lastDayOfYear() time.Time { return time.Date(time.Now().Year(), 12, 31, 0, 0, 0, 0, time.UTC) }","""func firstDayOfMonth(year int, month time.Month) time.Time {return time.Date(year, month, 1, 0, 0, 0, 0, time.UTC)}""","""func lastDayOfMonth(year int, month time.Month) int {return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()}""","func isWorkday() bool { wd := time.Now().Weekday(); return wd != time.Saturday && wd != time.Sunday }","func isWeekend() bool { wd := time.Now().Weekday(); return wd == time.Saturday || wd == time.Sunday }","func currentHour() int { return time.Now().Hour() }","func currentMinute() int { return time.Now().Minute() }","func currentSecond() int { return time.Now().Second() }","func sleep() { time.Sleep(time.Second) }","func millis() int64 { return time.Now().UnixNano() / int64(time.Millisecond) }","""func formatTime(t time.Time) string {return t.Format("2006-01-02 15:04:05")}""","""func parseTime(s string) time.Time {t, _ := time.Parse("2006-01-02", s)return t}""","""func startThread() {go func() { fmt.Println("Thread") }()}""","func threadSleep() { time.Sleep(time.Second) }","""func multiThread() {for i := 0; i < 3; i++ { go func(i int) {}(i) }}""","func threadName() string { return runtime.Version() }","func setDaemon() { /* Not applicable in Go */ }","""func useMutex() {var mu sync.Mutexmu.Lock()defer mu.Unlock()}""","""func createProcess() {cmd := exec.Command("ls")cmd.Start()}""","func getPID() int { return os.Getpid() }","""func isProcessAlive(pid int) bool {err := syscall.Kill(pid, syscall.Signal(0))return err == nil}""","""func multiProcess() {exec.Command("ls").Start()}""","""func useQueue() {ch := make(chan int)go func() { ch <- 1 }()<-ch}""","""func usePipe() {r, w, _ := os.Pipe()w.Write([]byte("data"))var b [4]byter.Read(b[:])}""","func limitCPUUsage() { runtime.GOMAXPROCS(1) }","""func runShellCommand(cmd string) error {return exec.Command("sh", "-c", cmd).Run()}""","""func getCommandOutput(cmd string) (string, error) {out, err := exec.Command("sh", "-c", cmd).Output()return string(out), err}""","""func getCommandStatus(cmd string) (int, error) {err := exec.Command("sh", "-c", cmd).Run()if err != nil {if exitError, ok := err.(*exec.ExitError); ok {return exitError.ExitCode(), nil}return -1, err}return 0, nil}""","""func isCommandSuccess(cmd string) (bool, error) {err := exec.Command("sh", "-c", cmd).Run()return err == nil, err}""","""func getCurrentScriptPath() string {_, filename, _, _ := runtime.Caller(1)return filepath.Dir(filename)}""","""func getCommandLineArgs() []string {return os.Args}""","""func parseArgs() (string, int) {var name stringvar age intflag.StringVar(&name, "name", "", "Name of the person")flag.IntVar(&age, "age", 0, "Age of the person")flag.Parse()return name, age}""","""func generateHelp() string {flag.Usage()return ""}""","""func listPythonModules() {exec.Command("python", "-c", "help('modules')").Run()}""","""func installPythonPackage(pkg string) error {return exec.Command("pip", "install", pkg).Run()}""","""func uninstallPythonPackage(pkg string) error {return exec.Command("pip", "uninstall", "-y", pkg).Run()}""","""func getPackageVersion(pkg string) (string, error) {out, err := exec.Command("pip", "show", pkg).Output()if err != nil {return "", err}return string(out), nil}""","""func useVirtualEnv(envPath string) error {return exec.Command("source", filepath.Join(envPath, "bin", "activate")).Run()}""","""func listInstalledPackages() (string, error) {out, err := exec.Command("pip", "list").Output()return string(out), err}""","""func upgradePythonPackage(pkg string) error {return exec.Command("pip", "install", "--upgrade", pkg).Run()}""","""func connectLocalDB(dbName string) (*sql.DB, error) {return sql.Open("sqlite3", dbName)}""","""func executeSQLQuery(db *sql.DB, query string) (*sql.Rows, error) {return db.Query(query)}""","""func insertRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {return db.Exec(query, args...)}""","""func deleteRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {return db.Exec(query, args...)}""","""func updateRecord(db *sql.DB, query string, args ...interface{}) (sql.Result, error) {return db.Exec(query, args...)}""","""func queryMultipleRecords(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {return db.Query(query, args...)}""","""func useParameterizedQuery(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) {return db.Query(query, args...)}""","""func closeDBConnection(db *sql.DB) error {return db.Close()}""","""func createTable(db *sql.DB, query string) (sql.Result, error) {return db.Exec(query)}""","""func dropTable(db *sql.DB, query string) (sql.Result, error) {return db.Exec(query)}""","""func tableExists(db *sql.DB, tableName string) (bool, error) {var exists boolerr := db.QueryRow("SELECT EXISTS (SELECT 1 FROM sqlite_master WHERE type='table' AND name=?)", tableName).Scan(&exists)return exists, err}""","""func listAllTables(db *sql.DB) ([]string, error) {rows, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'")if err != nil {return nil, err}defer rows.Close()var tables []stringfor rows.Next() {var table stringif err := rows.Scan(&table); err != nil {return nil, err}tables = append(tables, table)}return tables, nil}""","""func exportToCSV(data [][]string, filename string) error {file, err := os.Create(filename)if err != nil {return err}defer file.Close()writer := csv.NewWriter(file)return writer.WriteAll(data)}""","""func exportToExcel(data [][]string, filename string) error {file := excelize.NewFile()for i, row := range data {for j, cell := range row {file.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), cell)}}return file.SaveAs(filename)}""","""func exportToJSON(data interface{}, filename string) error {file, err := os.Create(filename)if err != nil {return err}defer file.Close()encoder := json.NewEncoder(file)return encoder.Encode(data)}""","""func readExcel(filename string) ([][]string, error) {file, err := excelize.OpenFile(filename)if err != nil {return nil, err}rows, err := file.GetRows("Sheet1")return rows, err}""","""func mergeExcelFiles(files []string, output string) error {merged := excelize.NewFile()for _, file := range files {f, err := excelize.OpenFile(file)if err != nil {return err}rows, err := f.GetRows("Sheet1")if err != nil {return err}for i, row := range rows {for j, cell := range row {merged.SetCellValue("Sheet1", fmt.Sprintf("%c%d", 'A'+j, i+1), cell)}}}return merged.SaveAs(output)}""","""func addSheetToExcel(filename, sheetName string) error {file, err := excelize.OpenFile(filename)if err != nil {return err}file.NewSheet(sheetName)return file.Save()}""","""func copyExcelStyle(src, dst string) error {srcFile, err := excelize.OpenFile(src)if err != nil {return err}dstFile, err := excelize.OpenFile(dst)if err != nil {return err}styleID, err := srcFile.GetCellStyle("Sheet1", "A1")if err != nil {return err}dstFile.SetCellStyle("Sheet1", "A1", "A1", styleID)return dstFile.Save()}""","""func setExcelCellColor(filename, cell, color string) error {file, err := excelize.OpenFile(filename)if err != nil {return err}styleID, err := file.NewStyle(&excelize.Style{Fill: excelize.Fill{Type: "pattern", Color: []string{color}, Pattern: 1}})if err != nil {return err}file.SetCellStyle("Sheet1", cell, cell, styleID)return file.Save()}""","""func setExcelFontStyle(filename, cell, fontName string, fontSize int) error {file, err := excelize.OpenFile(filename)if err != nil {return err}styleID, err := file.NewStyle(&excelize.Style{Font: &excelize.Font{Family: fontName, Size: fontSize}})if err != nil {return err}file.SetCellStyle("Sheet1", cell, cell, styleID)return file.Save()}""","""func readExcelCell(filename, cell string) (string, error) {file, err := excelize.OpenFile(filename)if err != nil {return "", err}return file.GetCellValue("Sheet1", cell)}""","""func writeExcelCell(filename, cell, value string) error {file, err := excelize.OpenFile(filename)if err != nil {return err}file.SetCellValue("Sheet1", cell, value)return file.Save()}""","""func getImageDimensions(filename string) (int, int, error) {file, err := os.Open(filename)if err != nil {return 0, 0, err}defer file.Close()img, _, err := image.DecodeConfig(file)return img.Width, img.Height, err}""","""func resizeImage(filename string, width, height int) error {file, err := os.Open(filename)if err != nil {return err}defer file.Close()img, _, err := image.Decode(file)if err != nil {return err}resized := imaging.Resize(img, width, height, imaging.Lanczos)return imaging.Save(resized, filename)}"""
app.py+816-297