Forrest99 commited on
Commit
9284d6e
·
verified ·
1 Parent(s): 11f129c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +419 -297
app.py CHANGED
@@ -13,304 +13,426 @@ app.logger = logging.getLogger("CodeSearchAPI")
13
 
14
  # 预定义代码片段
15
  CODE_SNIPPETS = [
16
- "echo 'Hello, World!';",
17
- "function add($a, $b) { return $a + $b; }",
18
- "$randomNumber = rand();",
19
- "function isEven($num) { return $num % 2 == 0; }",
20
- "strlen('example');",
21
- "date('Y-m-d');",
22
- "file_exists('example.txt');",
23
- "file_get_contents('example.txt');",
24
- "file_put_contents('example.txt', 'Hello, World!');",
25
- "date('H:i:s');",
26
- "strtoupper('example');",
27
- "strtolower('EXAMPLE');",
28
- "strrev('example');",
29
- "count([1, 2, 3]);",
30
- "max([1, 2, 3]);",
31
- "min([1, 2, 3]);",
32
- "sort([3, 1, 2]);",
33
- "array_merge([1, 2], [3, 4]);",
34
- "array_splice($array, $offset, $length);",
35
- "empty([]);",
36
- "substr_count('example', 'e');",
37
- "strpos('example', 'amp') !== false;",
38
- "strval(123);",
39
- "intval('123');",
40
- "is_numeric('123');",
41
- "array_search('value', $array);",
42
- "$array = [];",
43
- "array_reverse([1, 2, 3]);",
44
- "array_unique([1, 2, 2, 3]);",
45
- "in_array('value', $array);",
46
- "$array = ['key' => 'value'];",
47
- "$array['new_key'] = 'new_value';",
48
- "unset($array['key']);",
49
- "array_keys($array);",
50
- "array_values($array);",
51
- "array_merge($array1, $array2);",
52
- "empty($array);",
53
- "$array['key'];",
54
- "array_key_exists('key', $array);",
55
- "$array = [];",
56
- "count(file('example.txt'));",
57
- "file_put_contents('example.txt', implode(PHP_EOL, $array));",
58
- "file('example.txt', FILE_IGNORE_NEW_LINES);",
59
- "str_word_count(file_get_contents('example.txt'));",
60
- "function isLeapYear($year) { return ($year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0)); }",
61
- "date('Y-m-d H:i:s');",
62
- "(strtotime('2023-12-31') - strtotime('2023-01-01')) / (60 * 60 * 24);",
63
- "getcwd();",
64
- "scandir('.');",
65
- "mkdir('new_directory');",
66
- "rmdir('directory');",
67
- "is_file('example.txt');",
68
- "is_dir('directory');",
69
- "filesize('example.txt');",
70
- "rename('old.txt', 'new.txt');",
71
- "copy('source.txt', 'destination.txt');",
72
- "rename('source.txt', 'destination.txt');",
73
- "unlink('example.txt');",
74
- "getenv('PATH');",
75
- "putenv('PATH=/new/path');",
76
- "exec('start https://example.com');",
77
- "file_get_contents('https://example.com');",
78
- "json_decode('{\"key\":\"value\"}', true);",
79
- "file_put_contents('example.json', json_encode($data));",
80
- "json_decode(file_get_contents('example.json'), true);",
81
- "implode(',', $array);",
82
- "explode(',', 'a,b,c');",
83
- "implode(PHP_EOL, $array);",
84
- "explode(' ', 'a b c');",
85
- "explode(',', 'a,b,c');",
86
- "str_split('example');",
87
- "str_replace('old', 'new', 'old text');",
88
- "trim(' example ');",
89
- "preg_replace('/[^a-zA-Z0-9]/', '', 'example!');",
90
- "empty('');",
91
- "strrev('example') == 'example';",
92
- "fputcsv($file, $array);",
93
- "array_map('str_getcsv', file('example.csv'));",
94
- "count(file('example.csv'));",
95
- "shuffle($array);",
96
- "$array[array_rand($array)];",
97
- "array_rand($array, $num);",
98
- "rand(1, 6);",
99
- "rand(0, 1);",
100
- "substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 8);",
101
- "printf('#%06X', mt_rand(0, 0xFFFFFF));",
102
- "uniqid();",
103
- "class Example {}",
104
- "$example = new Example();",
105
- "class Example { function method() {} }",
106
- "class Example { public $property; }",
107
- "class Child extends Parent {}",
108
- "class Child extends Parent { function method() {} }",
109
- "Example::method();",
110
- "Example::staticMethod();",
111
- "is_object($example);",
112
- "get_object_vars($example);",
113
- "$example->property = 'value';",
114
- "unset($example->property);",
115
- "try{foo();}catch(e){}",
116
- "throw new Error('CustomError')",
117
- """try{foo();}catch(e){const info=e.message;}""",
118
- "console.error(err)",
119
- "const timer={start(){this.s=Date.now()},stop(){return Date.now()-this.s}}",
120
- "const runtime=(s)=>Date.now()-s",
121
- """const progress=(i,n)=>process.stdout.write(Math.floor(i/n100)+'%\r')""",
122
- "const delay=(ms)=>new Promise(r=>setTimeout(r,ms))",
123
- "const f=(x)=>x2",
124
- "const m=arr.map(x=>x2)",
125
- "const f2=arr.filter(x=>x>0)",
126
- "const r=arr.reduce((a,x)=>a+x,0)",
127
- "const a=[1,2,3].map(x=>x)",
128
- "const o={a:1,b:2};const d={k:v for([k,v] of Object.entries(o))}",
129
- "const s=new Set([1,2,3]);const p=new Set(x for(x of s))",
130
- "const inter=new Set([...a].filter(x=>b.has(x)))",
131
- "const uni=new Set([...a,...b])",
132
- "const diff=new Set([...a].filter(x=>!b.has(x)))",
133
- "const noNone=list.filter(x=>x!=null)",
134
- """try{fs.openSync(path)}catch{}""",
135
- "typeof x==='string'",
136
- "const b=!!str",
137
- "if(cond)doSomething()",
138
- "while(cond){}",
139
- "for(const x of arr){}",
140
- "for(const k in obj){}",
141
- "for(const c of str){}",
142
- "for(...){if(cond)break}",
143
- "for(...){if(cond)continue}",
144
- "function fn(){}",
145
- "function fn(a=1){}",
146
- "function fn(){return [1,2]}",
147
- "function fn(...a){}",
148
- "function fn(kwargs){const{a,b}=kwargs}",
149
- """function timed(fn){return(...a)=>{const s=Date.now();const r=fn(...a);console.log(Date.now()-s);return r}}""",
150
- """const deco=fn=>(...a)=>fn(...a)""",
151
- """const memo=fn=>{const c={};return x=>c[x]||=(fn(x))}""",
152
- "functiongen(){yield 1;yield 2}",
153
- "const g=gen();",
154
- "const it={i:0,next(){return this.i<2?{value:this.i++,done:false}:{done:true}}}",
155
- "for(const x of it){}",
156
- "for(const [i,x] of arr.entries()){}",
157
- "const z=arr1.map((v,i)=>[v,arr2[i]])",
158
- "const dict=Object.fromEntries(arr1.map((v,i)=>[v,arr2[i]]))",
159
- "JSON.stringify(arr1)===JSON.stringify(arr2)",
160
- "JSON.stringify(obj1)===JSON.stringify(obj2)",
161
- "JSON.stringify(new Set(a))===JSON.stringify(new Set(b))",
162
- "const uniq=[...new Set(arr)]",
163
- "set.clear()",
164
- "set.size===0",
165
- "set.add(x)",
166
- "set.delete(x)",
167
- "set.has(x)",
168
- "set.size",
169
- "const hasInt=([...a].some(x=>b.has(x)))",
170
- "arr1.every(x=>arr2.includes(x))",
171
- "str.includes(sub)",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  "str[0]",
173
- "str[str.length-1]",
174
- """const isText=path=>['.txt','.md'].includes(require('path').extname(path))""",
175
- """const isImage=path=>['.png','.jpg','.jpeg','.gif'].includes(require('path').extname(path))""",
176
- "Math.round(n)",
177
- "Math.ceil(n)",
178
- "Math.floor(n)",
179
- "n.toFixed(2)",
180
- """const randStr=(l)=>[...Array(l)].map(()=>Math.random().toString(36).charAt(2)).join('')""",
181
- "const exists=require('fs').existsSync(path)",
182
- """const walk=(d)=>require('fs').readdirSync(d).flatMap(f=>{const p=require('path').join(d,f);return require('fs').statSync(p).isDirectory()?walk(p):p})""",
183
- """const ext=require('path').extname(fp)""",
184
- """const name=require('path').basename(fp)""",
185
- """const full=require('path').resolve(fp)""",
186
- "process.version",
187
- "process.platform",
188
- "require('os').cpus().length",
189
- "require('os').totalmem()",
190
- """const d=require('os').diskUsageSync?require('os').diskUsageSync('/'):null""",
191
- "require('os').networkInterfaces()",
192
- """require('dns').resolve('www.google.com',e=>console.log(!e))""",
193
- """require('https').get(url,res=>res.pipe(require('fs').createWriteStream(dest)))""",
194
- """const upload=async f=>Promise.resolve('ok')""",
195
- """require('https').request({method:'POST',host,u:path},()=>{}).end(data)""",
196
- """require('https').get(url+'?'+new URLSearchParams(params),res=>{})""",
197
- """const req=()=>fetch(url,{headers})""",
198
- """const jsdom=require('jsdom');const d=new jsdom.JSDOM(html)""",
199
- """const title=jsdom.JSDOM(html).window.document.querySelector('title').textContent""",
200
- """const links=[...d.window.document.querySelectorAll('a')].map(a=>a.href)""",
201
- """Promise.all(links.map(u=>fetch(u).then(r=>r.blob()).then(b=>require('fs').writeFileSync(require('path').basename(u),Buffer.from(b)))))""",
202
- """const freq=html.split(/\W+/).reduce((c,w)=>{c[w]=(c[w]||0)+1;return c},{})""",
203
- """const login=()=>fetch(url,{method:'POST',body:creds})""",
204
- """const text=html.replace(/<[^>]+>/g,'')""",
205
- """const emails=html.match(/[\w.-]+@[\w.-]+/g)""",
206
- """const phones=html.match(/\+?\d[\d -]{7,}\d/g)""",
207
- """const nums=html.match(/\d+/g)""",
208
- """const newHtml=html.replace(/foo/g,'bar')""",
209
- """const ok=/^\d{3}$/.test(str)""",
210
- """const noTags=html.replace(/<[^>]*>/g,'')""",
211
- """const enc=html.replace(/./g,c=>'&#'+c.charCodeAt(0)+';')""",
212
- """const dec=enc.replace(/&#(\d+);/g,(m,n)=>String.fromCharCode(n))""",
213
- """const {app,BrowserWindow}=require('electron');app.on('ready',()=>new BrowserWindow().loadURL('about:blank'))""",
214
- "$button = new GtkButton('Click Me'); $window->add($button);",
215
- "$button->connect('clicked', function() { echo 'Button clicked!'; });",
216
- "$dialog = new GtkMessageDialog($window, GtkDialogFlags::MODAL, GtkMessageType::INFO, GtkButtonsType::OK, 'Hello!'); $dialog->run();",
217
- "$entry = new GtkEntry(); $input = $entry->get_text();",
218
- "$window->set_title('New Title');",
219
- "$window->set_default_size(800, 600);",
220
- "$window->set_position(Gtk::WIN_POS_CENTER);",
221
- "$menubar = new GtkMenuBar(); $menu = new GtkMenu(); $menuitem = new GtkMenuItem('File'); $menuitem->set_submenu($menu); $menubar->append($menuitem); $window->add($menubar);",
222
- "$combobox = new GtkComboBoxText(); $combobox->append_text('Option 1'); $combobox->append_text('Option 2'); $window->add($combobox);",
223
- "$radiobutton1 = new GtkRadioButton('Option 1'); $radiobutton2 = new GtkRadioButton($radiobutton1, 'Option 2'); $window->add($radiobutton1); $window->add($radiobutton2);",
224
- "$checkbutton = new GtkCheckButton('Check Me'); $window->add($checkbutton);",
225
- "$image = new GtkImage('image.png'); $window->add($image);",
226
- "exec('play audio.mp3');",
227
- "exec('play video.mp4');",
228
- "$current_time = exec('get_current_time_command');",
229
- "exec('screenshot_command');",
230
- "exec('record_screen_command');",
231
- "$mouse_position = exec('get_mouse_position_command');",
232
- "exec('simulate_keyboard_input_command');",
233
- "exec('simulate_mouse_click_command');",
234
- "time();",
235
- "date('Y-m-d H:i:s', $timestamp);",
236
- "strtotime('2023-10-01 12:00:00');",
237
- "date('l');",
238
- "date('t');",
239
- "date('Y-01-01');",
240
- "date('Y-12-31');",
241
- "date('Y-m-01', strtotime('2023-10-01'));",
242
- "date('Y-m-t', strtotime('2023-10-01'));",
243
- "date('N') < 6;",
244
- "date('N') >= 6;",
245
- "date('H');",
246
- "date('i');",
247
- "date('s');",
248
- "sleep(1);",
249
- "floor(microtime(true) * 1000);",
250
- "date('Y-m-d H:i:s', $time);",
251
- "strtotime($time_string);",
252
- "$thread = new Thread(); $thread->start();",
253
- "$thread->sleep(1);",
254
- "$threads = []; for ($i = 0; $i < 5; $i++) { $threads[$i] = new Thread(); $threads[$i]->start(); }",
255
- "$thread->getName();",
256
- "$thread->setDaemon(true);",
257
- "$lock = new Mutex(); $lock->lock(); $lock->unlock();",
258
- "$pid = pcntl_fork();",
259
- "getmypid();",
260
- "posix_kill($pid, 0);",
261
- "$pids = []; for ($i = 0; $i < 5; $i++) { $pids[$i] = pcntl_fork(); if ($pids[$i] == 0) { exit; } }",
262
- "$queue = new Threaded(); $queue->push('value');",
263
- "$pipe = fopen('php://stdin', 'r'); fwrite($pipe, 'value'); fclose($pipe);",
264
- "set_time_limit(0);",
265
- "exec('ls');",
266
- "exec('ls', $output);",
267
- "exec('ls', $output, $status);",
268
- "$status === 0;",
269
- "__FILE__;",
270
- "$argv;",
271
- "$parser = new ArgParser(); $parser->addArgument('arg1'); $parser->parse($argv);",
272
- "$parser->printHelp();",
273
- "print_r(get_loaded_extensions());",
274
- "exec('pip install package_name');",
275
- "exec('pip uninstall package_name');",
276
- "exec('pip show package_name | grep Version');",
277
- "exec('python -m venv venv');",
278
- "exec('pip list');",
279
- "exec('pip install --upgrade package_name');",
280
- "$db = new SQLite3('database.db');",
281
- "$result = $db->query('SELECT * FROM table');",
282
- "$db->exec(\"INSERT INTO table (column) VALUES ('value')\");",
283
- "$db->exec(\"DELETE FROM table WHERE id = 1\");",
284
- "$db->exec(\"UPDATE table SET column = 'new_value' WHERE id = 1\");",
285
- "$result = $db->query('SELECT * FROM table'); while ($row = $result->fetchArray()) { print_r($row); }",
286
- "$stmt = $db->prepare('SELECT * FROM table WHERE id = :id'); $stmt->bindValue(':id', 1); $result = $stmt->execute();",
287
- "$db->close();",
288
- "$db->exec('CREATE TABLE table (id INTEGER PRIMARY KEY, column TEXT)');",
289
- "$db->exec('DROP TABLE table');",
290
- "$result = $db->query(\"SELECT name FROM sqlite_master WHERE type='table' AND name='table'\");",
291
- "$result = $db->query(\"SELECT name FROM sqlite_master WHERE type='table'\");",
292
- "$model = new Model(); $model->save();",
293
- "$model = Model::find(1);",
294
- "$model = Model::find(1); $model->delete();",
295
- "$model = Model::find(1); $model->column = 'new_value'; $model->save();",
296
- "class Model extends ORM { protected static $table = 'table'; }",
297
- "class ChildModel extends ParentModel {}",
298
- "protected static $primaryKey = 'id';",
299
- "protected static $unique = ['column'];",
300
- "protected static $defaults = ['column' => 'default_value'];",
301
- "$file = fopen('data.csv', 'w'); fputcsv($file, $data); fclose($file);",
302
- "$excel = new ExcelWriter('data.xlsx'); $excel->write($data); $excel->close();",
303
- "$json = json_encode($data); file_put_contents('data.json', $json);",
304
- "$excel = new ExcelReader('data.xlsx'); $data = $excel->read(); $excel->close();",
305
- "$excel = new ExcelWriter('merged.xlsx'); foreach ($files as $file) { $data = (new ExcelReader($file))->read(); $excel->write($data); } $excel->close();",
306
- "$excel = new ExcelWriter('data.xlsx'); $excel->addSheet('New Sheet'); $excel->close();",
307
- "$excel = new ExcelWriter('data.xlsx'); $excel->copyStyle('Sheet1', 'Sheet2'); $excel->close();",
308
- "$excel = new ExcelWriter('data.xlsx'); $excel->setCellColor('A1', 'FF0000'); $excel->close();",
309
- "$excel = new ExcelWriter('data.xlsx'); $excel->setFontStyle('A1', 'bold'); $excel->close();",
310
- "$excel = new ExcelReader('data.xlsx'); $value = $excel->getCellValue('A1'); $excel->close();",
311
- "$excel = new ExcelWriter('data.xlsx'); $excel->setCellValue('A1', 'Hello'); $excel->close();",
312
- "list($width, $height) = getimagesize('image.png');",
313
- "$image = new Imagick('image.png'); $image->resizeImage(100, 100, Imagick::FILTER_LANCZOS, 1); $image->writeImage('resized_image.png');"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
 
315
 
316
 
 
13
 
14
  # 预定义代码片段
15
  CODE_SNIPPETS = [
16
+
17
+
18
+ "puts 'Hello, World!'",
19
+ "def sum(a, b); a + b; end",
20
+ "rand",
21
+ "def even?(num); num.even?; end",
22
+ "str.length",
23
+ "Date.today",
24
+ "File.exist?('file.txt')",
25
+ "File.read('file.txt')",
26
+ "File.write('file.txt', 'content')",
27
+ "Time.now",
28
+ "str.upcase",
29
+ "str.downcase",
30
+ "str.reverse",
31
+ "list.size",
32
+ "list.max",
33
+ "list.min",
34
+ "list.sort",
35
+ "list1 + list2",
36
+ "list.delete(element)",
37
+ "list.empty?",
38
+ "str.count(char)",
39
+ "str.include?(substring)",
40
+ "num.to_s",
41
+ "str.to_i",
42
+ "str.match?(/^\d+$/)",
43
+ "list.index(element)",
44
+ "list.clear",
45
+ "list.reverse",
46
+ "list.uniq",
47
+ "list.include?(value)",
48
+ "{}",
49
+ "hash[key] = value",
50
+ "hash.delete(key)",
51
+ "hash.keys",
52
+ "hash.values",
53
+ "hash1.merge(hash2)",
54
+ "hash.empty?",
55
+ "hash[key]",
56
+ "hash.key?(key)",
57
+ "hash.clear",
58
+ "File.readlines('file.txt').size",
59
+ "File.write('file.txt', list.join('\\n'))",
60
+ "File.read('file.txt').split('\\n')",
61
+ "File.read('file.txt').split.size",
62
+ "def leap_year?(year); (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0); end",
63
+ "Time.now.strftime('%Y-%m-%d %H:%M:%S')",
64
+ "(Date.today - Date.new(2023, 1, 1)).to_i",
65
+ "Dir.pwd",
66
+ "Dir.entries('.')",
67
+ "Dir.mkdir('new_dir')",
68
+ "Dir.rmdir('new_dir')",
69
+ "File.file?('path')",
70
+ "File.directory?('path')",
71
+ "File.size('file.txt')",
72
+ "File.rename('old.txt', 'new.txt')",
73
+ "FileUtils.cp('source.txt', 'destination.txt')",
74
+ "FileUtils.mv('source.txt', 'destination.txt')",
75
+ "File.delete('file.txt')",
76
+ "ENV['VAR_NAME']",
77
+ "ENV['VAR_NAME'] = 'value'",
78
+ "system('open https://example.com')",
79
+ "require 'net/http'; Net::HTTP.get(URI('https://example.com'))",
80
+ "require 'json'; JSON.parse(json_string)",
81
+ "require 'json'; File.write('file.json', JSON.dump(data))",
82
+ "require 'json'; JSON.parse(File.read('file.json'))",
83
+ "list.join",
84
+ "str.split(',')",
85
+ "list.join(',')",
86
+ "list.join('\\n')",
87
+ "str.split",
88
+ "str.split(delimiter)",
89
+ "str.chars",
90
+ "str.gsub(old, new)",
91
+ "str.gsub(' ', '')",
92
+ "str.gsub(/[^a-zA-Z0-9]/, '')",
93
+ "str.empty?",
94
+ "str == str.reverse",
95
+ "require 'csv'; CSV.open('file.csv', 'w') { |csv| csv << ['data'] }",
96
+ "require 'csv'; CSV.read('file.csv')",
97
+ "require 'csv'; CSV.read('file.csv').size",
98
+ "list.shuffle",
99
+ "list.sample",
100
+ "list.sample(n)",
101
+ "rand(6) + 1",
102
+ "rand(2) == 0 ? 'Heads' : 'Tails'",
103
+ "SecureRandom.alphanumeric(8)",
104
+ "format('#%06x', rand(0xffffff))",
105
+ "SecureRandom.uuid",
106
+ "class MyClass; end",
107
+ "MyClass.new",
108
+ "class MyClass; def my_method; end; end",
109
+ "class MyClass; attr_accessor :my_attr; end",
110
+ "class ChildClass < ParentClass; end",
111
+ "class ChildClass < ParentClass; def my_method; super; end; end",
112
+ "class MyClass; def self.class_method; end; end",
113
+ "class MyClass; def self.static_method; end; end",
114
+ "obj.is_a?(Class)",
115
+ "obj.instance_variable_get(:@attr)",
116
+ "obj.instance_variable_set(:@attr, value)",
117
+ "obj.instance_variable_defined?(:@attr)",
118
+ "begin; risky_operation; rescue => e; puts e; end",
119
+ """class CustomError < StandardError
120
+ end
121
+ raise CustomError, 'error occurred'""",
122
+ "begin; raise 'oops'; rescue => e; e.message; end",
123
+ """require 'logger'
124
+ logger = Logger.new('error.log')
125
+ logger.error('error occurred')""",
126
+ "start_time = Time.now",
127
+ "Time.now - start_time",
128
+ "20.times { |i| print "\r[#{'='(i+1)}#{' '(19-i)}]"; sleep(0.1) }",
129
+ "sleep(1)",
130
+ "square = ->(x) { xx }",
131
+ "squares = [1,2,3].map { |n| nn }",
132
+ "evens = [1,2,3,4].select { |n| n.even? }",
133
+ "sum = [1,2,3].reduce(0) { |acc,n| acc+n }",
134
+ "doubles = [1,2,3,4,5].map { |n| n2 }",
135
+ "hash = [1,2,3].map { |n| [n, n2] }.to_h",
136
+ "require 'set'; s = Set.new([1,2,3].map { |n| n*2 })",
137
+ "intersection = a & b",
138
+ "union = a | b",
139
+ "diff = a - b",
140
+ "filtered = list.compact",
141
+ "begin; File.open('file.txt'); rescue; false; end",
142
+ "x.is_a?(String)",
143
+ "bool = ['true','1'].include?(str.downcase)",
144
+ "puts 'yes' if x > 0",
145
+ "i=0; while i<5; i+=1; end",
146
+ "for item in [1,2,3]; puts item; end",
147
+ """h = {a:1, b:2}
148
+ for k, v in h
149
+ puts "#{k}:#{v}"
150
+ end""",
151
+ """for c in 'hello'.chars
152
+ puts c
153
+ end""",
154
+ """for i in 1..5
155
+ break if i==3
156
+ puts i
157
+ end""",
158
+ """for i in 1..5
159
+ next if i==3
160
+ puts i
161
+ end""",
162
+ "def foo; end",
163
+ "def foo(a=1); a; end",
164
+ "def foo; [1,2]; end",
165
+ "def foo(*args); args; end",
166
+ "def foo(a:, b:); a+b; end",
167
+ """def foo
168
+ end
169
+ start = Time.now
170
+ foo
171
+ puts Time.now - start""",
172
+ """def decorate(f)
173
+ ->(args) { puts 'before'; result = f.call(args); puts 'after'; result }
174
+ end""",
175
+ """def fib(n, memo={})
176
+ return memo[n] if memo[n]
177
+ memo[n] = n<2 ? n : fib(n-1, memo) + fib(n-2, memo)
178
+ end""",
179
+ "gen = Enumerator.new { |y| i=0; loop { y << i; i+=1 } }",
180
+ "def foo; yield 1; end",
181
+ "gen.next",
182
+ "itr = [1,2,3].each",
183
+ """itr = [1,2,3].each
184
+ loop do
185
+ puts itr.next
186
+ end""",
187
+ "[1,2].each_with_index { |v, i| puts i, v }",
188
+ "zipped = [1,2].zip(['a','b'])",
189
+ "h = [1,2].zip(['a','b']).to_h",
190
+ "[1,2] == [1,2]",
191
+ "{a:1, b:2} == {b:2, a:1}",
192
+ "require 'set'; Set.new([1,2]) == Set.new([2,1])",
193
+ "unique = [1,2,1].uniq",
194
+ "s.clear",
195
+ "s.empty?",
196
+ "s.add(1)",
197
+ "s.delete(1)",
198
+ "s.include?(1)",
199
+ "s.size",
200
+ "!(a & b).empty?",
201
+ "[1,2].all? { |e| [1,2,3].include?(e) }",
202
+ "'hi'.include?('h')",
203
  "str[0]",
204
+ "str[-1]",
205
+ "File.extname(path) == '.txt'",
206
+ "['.png','.jpg','.jpeg','.gif'].include?(File.extname(path))",
207
+ "x.round",
208
+ "x.ceil",
209
+ "x.floor",
210
+ "sprintf('%.2f', x)",
211
+ "require 'securerandom'; SecureRandom.alphanumeric(8)",
212
+ "File.exist?('path')",
213
+ "Dir['**/'].each { |f| puts f }",
214
+ "File.extname('path.txt')",
215
+ "File.basename(path)",
216
+ "File.expand_path(path)",
217
+ "RUBY_VERSION",
218
+ "RUBY_PLATFORM",
219
+ "require 'etc'; Etc.nprocessors",
220
+ "mem = grep MemTotal /proc/meminfo",
221
+ "df = df -h /",
222
+ """require 'socket'
223
+ ip = Socket.ip_address_list.detect(&:ipv4_private).ip_address""",
224
+ "system('ping -c1 8.8.8.8 > /dev/null 2>&1')",
225
+ """require 'open-uri'
226
+ File.open('file', 'wb') { |f| f.write open(url).read }""",
227
+ """def upload(file)
228
+ puts 'Uploading'
229
+ end""",
230
+ """require 'net/http'
231
+ uri = URI(url)
232
+ Net::HTTP.post_form(uri, key: 'value')""",
233
+ """uri = URI(url)
234
+ uri.query = URI.encode_www_form(params)
235
+ Net::HTTP.get(uri)""",
236
+ """require 'net/http'
237
+ uri = URI(url)
238
+ req = Net::HTTP::Get.new(uri)
239
+ req['User-Agent'] = 'Custom'
240
+ res = Net::HTTP.start(uri.hostname, uri.port) { |http| http.request(req) }""",
241
+ "require 'nokogiri'; doc = Nokogiri::HTML(html)",
242
+ "doc.at('title').text",
243
+ "links = doc.css('a').map { |a| a['href'] }",
244
+ """doc.css('img').each do |img|
245
+ open(img['src']).each do |chunk|
246
+ File.open(File.basename(img['src']), 'ab') { |f| f.write chunk }
247
+ end
248
+ end""",
249
+ """freq = Hash.new(0)
250
+ text.split.each { |w| freq[w] += 1 }""",
251
+ """require 'net/http'
252
+ res = Net::HTTP.post_form(URI(login_url), username: 'u', password: 'p')""",
253
+ "Nokogiri::HTML(html).text",
254
+ "emails = text.scan(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/)",
255
+ "phones = text.scan(/\b\d{3}-\d{3}-\d{4}\b/)",
256
+ "nums = text.scan(/\d+/)",
257
+ "new = text.gsub(/foo/, 'bar')",
258
+ "!!(text =~ /pattern/)",
259
+ "clean = text.gsub(/<[^>]>/, '')",
260
+ "CGI.escapeHTML(text)",
261
+ "CGI.unescapeHTML(text)",
262
+ """require 'tk'
263
+ root = TkRoot.new { title 'App' }
264
+ Tk.mainloop""",
265
+ "require 'tk'",
266
+ """root = TkRoot.new
267
+ button = TkButton.new(root) {text 'Click Me'; command { Tk.messageBox(message: 'Button Clicked!') }}
268
+ button.pack""",
269
+ """Tk.messageBox(message: 'Hello, World!')""",
270
+ """entry = TkEntry.new(root).pack
271
+ entry.get""",
272
+ """root.title = 'My Window'""",
273
+ """root.geometry('400x300')""",
274
+ """root.geometry('+%d+%d' % [(root.winfo_screenwidth() - root.winfo_reqwidth()) / 2, (root.winfo_screenheight() - root.winfo_reqheight()) / 2])""",
275
+ """menu = TkMenu.new(root)
276
+ root['menu'] = menu
277
+ menu.add('command', 'label' => 'File')""",
278
+ """combobox = Tk::Tile::Combobox.new(root).pack""",
279
+ """radio = TkRadioButton.new(root) {text 'Option 1'}.pack""",
280
+ """check = TkCheckButton.new(root) {text 'Check Me'}.pack""",
281
+ """image = TkPhotoImage.new(file: 'image.png')
282
+ label = TkLabel.new(root) {image image}.pack""",
283
+ """`afplay audio.mp3`""",
284
+ """`ffplay video.mp4`""",
285
+ """`ffmpeg -i video.mp4 -f null - 2>&1 | grep 'time=' | awk '{print $2}'`""",
286
+ """`screencapture screen.png`""",
287
+ """`ffmpeg -f avfoundation -i "1" -t 10 screen.mp4`""",
288
+ """`cliclick p:.`""",
289
+ """`cliclick kd:cmd kp:space ku:cmd`""",
290
+ """`cliclick c:.`""",
291
+ """Time.now.to_i""",
292
+ """Time.at(timestamp).strftime('%Y-%m-%d')""",
293
+ """Time.parse(date).to_i""",
294
+ """Time.now.strftime('%A')""",
295
+ """Time.days_in_month(Time.now.month, Time.now.year)""",
296
+ """Time.new(Time.now.year, 1, 1)""",
297
+ """Time.new(Time.now.year, 12, 31)""",
298
+ """Time.new(year, month, 1)""",
299
+ """Time.new(year, month, -1)""",
300
+ """Time.now.wday.between?(1, 5)""",
301
+ """Time.now.wday.between?(6, 7)""",
302
+ """Time.now.hour""",
303
+ """Time.now.min""",
304
+ """Time.now.sec""",
305
+ """sleep(1)""",
306
+ """(Time.now.to_f * 1000).to_i""",
307
+ """Time.now.strftime('%Y-%m-%d %H:%M:%S')""",
308
+ """Time.parse(time_str)""",
309
+ """Thread.new { puts 'Hello from thread' }""",
310
+ """sleep(1)""",
311
+ """threads = []
312
+ 3.times { threads << Thread.new { puts 'Hello from thread' } }
313
+ threads.each(&:join)""",
314
+ """Thread.current.name""",
315
+ """thread = Thread.new { puts 'Hello from thread' }
316
+ thread.abort_on_exception = true""",
317
+ """mutex = Mutex.new
318
+ mutex.synchronize { puts 'Hello from synchronized thread' }""",
319
+ """pid = Process.spawn('sleep 5')""",
320
+ """Process.pid""",
321
+ """Process.kill(0, pid) rescue false""",
322
+ """pids = []
323
+ 3.times { pids << Process.spawn('sleep 5') }
324
+ pids.each { |pid| Process.wait(pid) }""",
325
+ """queue = Queue.new
326
+ queue.push('Hello')
327
+ queue.pop""",
328
+ """reader, writer = IO.pipe
329
+ writer.puts 'Hello'
330
+ reader.gets""",
331
+ """Process.setrlimit(:CPU, 50)""",
332
+ """`ls`""",
333
+ """`ls`.chomp""",
334
+ """$?.exitstatus""",
335
+ """$?.success?""",
336
+ """File.expand_path(__FILE__)""",
337
+ """ARGV""",
338
+ """require 'optparse'
339
+ OptionParser.new { |opts| opts.on('-h', '--help', 'Show help') { puts opts } }.parse!""",
340
+ """OptionParser.new { |opts| opts.on('-h', '--help', 'Show help') { puts opts } }.parse!""",
341
+ """Gem.loaded_specs.keys""",
342
+ """`gem install package_name`""",
343
+ """`gem uninstall package_name`""",
344
+ """Gem.loaded_specs['package_name'].version.to_s""",
345
+ """`bundle exec ruby script.rb`""",
346
+ """Gem::Specification.map(&:name)""",
347
+ """`gem update package_name`""",
348
+ """require 'sqlite3'
349
+ db = SQLite3::Database.new('test.db')""",
350
+ """db.execute('SELECT * FROM table')""",
351
+ """db.execute('INSERT INTO table (column) VALUES (?)', 'value')""",
352
+ """db.execute('DELETE FROM table WHERE id = ?', 1)""",
353
+ """db.execute('UPDATE table SET column = ? WHERE id = ?', 'new_value', 1)""",
354
+ """db.execute('SELECT * FROM table').each { |row| puts row }""",
355
+ """db.execute('SELECT * FROM table WHERE column = ?', 'value')""",
356
+ """db.close""",
357
+ """db.execute('CREATE TABLE table (id INTEGER PRIMARY KEY, column TEXT)')""",
358
+ """db.execute('DROP TABLE table')""",
359
+ """db.table_info('table').any?""",
360
+ """db.execute('SELECT name FROM sqlite_master WHERE type = "table"')""",
361
+ """class Model < ActiveRecord::Base
362
+ end
363
+ Model.create(column: 'value')""",
364
+ """Model.find_by(column: 'value')""",
365
+ """Model.find_by(column: 'value').destroy""",
366
+ """Model.find_by(column: 'value').update(column: 'new_value')""",
367
+ """class Model < ActiveRecord::Base
368
+ end""",
369
+ """class ChildModel < ParentModel
370
+ end""",
371
+ """class Model < ActiveRecord::Base
372
+ self.primary_key = 'id'
373
+ end""",
374
+ """class Model < ActiveRecord::Base
375
+ validates_uniqueness_of :column
376
+ end""",
377
+ """class Model < ActiveRecord::Base
378
+ attribute :column, default: 'value'
379
+ end""",
380
+ """require 'csv'
381
+ CSV.open('data.csv', 'w') { |csv| csv << ['column1', 'column2'] }""",
382
+ """require 'spreadsheet'
383
+ book = Spreadsheet::Workbook.new
384
+ sheet = book.create_worksheet
385
+ sheet[0, 0] = 'Hello'
386
+ book.write('data.xls')""",
387
+ """require 'json'
388
+ File.write('data.json', {key: 'value'}.to_json)""",
389
+ """require 'spreadsheet'
390
+ book = Spreadsheet.open('data.xls')
391
+ sheet = book.worksheet(0)
392
+ sheet.each { |row| puts row }""",
393
+ """require 'spreadsheet'
394
+ book1 = Spreadsheet.open('file1.xls')
395
+ book2 = Spreadsheet.open('file2.xls')
396
+ book1.worksheets.each { |sheet| book2.add_worksheet(sheet) }
397
+ book2.write('merged.xls')""",
398
+ """require 'spreadsheet'
399
+ book = Spreadsheet::Workbook.new
400
+ book.create_worksheet(name: 'New Sheet')
401
+ book.write('data.xls')""",
402
+ """require 'spreadsheet'
403
+ book = Spreadsheet.open('data.xls')
404
+ sheet = book.worksheet(0)
405
+ new_sheet = book.create_worksheet
406
+ new_sheet.format_with(sheet)
407
+ book.write('data.xls')""",
408
+ """require 'spreadsheet'
409
+ book = Spreadsheet.open('data.xls')
410
+ sheet = book.worksheet(0)
411
+ sheet.row(0).set_format(0, Spreadsheet::Format.new(color: :red))
412
+ book.write('data.xls')""",
413
+ """require 'spreadsheet'
414
+ book = Spreadsheet.open('data.xls')
415
+ sheet = book.worksheet(0)
416
+ sheet.row(0).set_format(0, Spreadsheet::Format.new(weight: :bold))
417
+ book.write('data.xls')""",
418
+ """require 'spreadsheet'
419
+ book = Spreadsheet.open('data.xls')
420
+ sheet = book.worksheet(0)
421
+ sheet[0, 0]""",
422
+ """require 'spreadsheet'
423
+ book = Spreadsheet::Workbook.new
424
+ sheet = book.create_worksheet
425
+ sheet[0, 0] = 'Hello'
426
+ book.write('data.xls')""",
427
+ """require 'rmagick'
428
+ image = Magick::Image.read('image.png').first
429
+ [image.columns, image.rows]""",
430
+ """require 'rmagick'
431
+ image = Magick::Image.read('image.png').first
432
+ image.resize!(100, 100)"""
433
+
434
+
435
+
436
 
437
 
438