Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 39550
1
###############################################################################
2
#
3
# CoCalc: Collaborative Calculation in the Cloud
4
#
5
# Copyright (C) 2016, Sagemath Inc.
6
#
7
# This program is free software: you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# This program is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU General Public License for more details.
16
#
17
# You should have received a copy of the GNU General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
#
20
###############################################################################
21
22
###
23
Definition and control logic behind the various button bars.
24
25
There is a level of separation between the button bar's and the actual content what they insert/modify.
26
This is motivated by editing text, where various markups have different realizations ("B"old button -> **abc** or <b>abc</b>)
27
28
There are less/none overlaps for programming languages.
29
30
FUTURE:
31
* initial examples for Sage, LaTeX, R
32
* think about creating a dedicated dialog for more elaborate examples,
33
which should also have a client/server communication to avoid bloat
34
(think of a repository of hundrets of full examples with explanatory text)
35
* work out how codemirror should react if there is a text selected or multiple cursors active (just the primary one!?)
36
37
CONSIDERATIONS:
38
* buttons should insert code which immediately works:
39
it's easier for users to delete lines than to end up with some partial broken fragments
40
###
41
42
$ = window.$
43
{defaults} = require('smc-util/misc')
44
45
exports.FONT_FACES = FONT_FACES = 'Serif,Sans,Arial,Arial Black,Courier,Courier New,Comic Sans MS,Georgia,Helvetica,Impact,Lucida Grande,Lucida Sans,Monaco,Palatino,Tahoma,Times New Roman,Verdana'.split(',')
46
47
exports.commands =
48
shell :
49
comment :
50
wrap :
51
left : '#'
52
right : ''
53
multi : true
54
space : true
55
set_name_and_email :
56
insert:
57
"""
58
git config --global user.name ""
59
git config --global user.email ""
60
"""
61
initalize_git :
62
insert:
63
"""
64
git init
65
"""
66
create_gitignore :
67
insert:
68
"""
69
# See examples of .gitignore files at https://github.com/github/gitignore
70
echo "
71
# For CoCalc files like .sage-chat etc
72
*.sage-chat
73
*.sage-history
74
*.term
75
*.py[cod]" >> .gitignore
76
"""
77
clone_local_repo :
78
insert:
79
"""
80
git clone ~/local_dir/
81
"""
82
clone_remote_repo :
83
insert:
84
"""
85
git clone https://github.com/sagemathinc/cocalc.git
86
"""
87
add_file_to_repo :
88
insert:
89
"""
90
git add afile.py
91
"""
92
add_all_to_repo :
93
insert:
94
"""
95
git add *
96
"""
97
diff :
98
insert:
99
"""
100
git diff
101
"""
102
commit :
103
insert:
104
"""
105
git commit -a -m "commit message"
106
"""
107
setup_ssh_for_github :
108
insert:
109
"""
110
set -e
111
mkdir -p ~/.ssh/
112
SSHFILE=~/.ssh/id_rsa
113
ssh-keygen -t rsa -b 4096 -N "" -C "[email protected]" -f $SSHFILE
114
eval $(ssh-agent -s)
115
ssh-add ~/.ssh/id_rsa
116
echo "Below this line is your public SSH key"
117
cat ~/.ssh/id_rsa.pub
118
# Copy your public key below and follow the instructions at https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/#platform-linux
119
"""
120
push_origin_master :
121
insert:
122
"""
123
git push origin master
124
"""
125
126
status :
127
insert:
128
"""
129
git status
130
"""
131
132
add_remote_repo :
133
insert:
134
"""
135
git remote add origin <server>
136
"""
137
138
list_remote_repos :
139
insert:
140
"""
141
git remote -v
142
"""
143
144
create_new_branch :
145
insert:
146
"""
147
git checkout -b <branchname>
148
"""
149
150
switch_branches :
151
insert:
152
"""
153
git checkout <branchname>
154
"""
155
156
list_branches :
157
insert:
158
"""
159
git branch
160
"""
161
162
delete_the_feature_branch :
163
insert:
164
"""
165
git branch -d <branchname>
166
"""
167
168
push_branch :
169
insert:
170
"""
171
git push origin <branchname>
172
"""
173
174
push_all_branches :
175
insert:
176
"""
177
git push --all origin
178
"""
179
180
delete_remote_branch :
181
insert:
182
"""
183
git push origin --delete <branchName>
184
"""
185
186
pull :
187
insert:
188
"""
189
git pull
190
"""
191
192
merge_branch :
193
insert:
194
"""
195
git merge <branchname>
196
git diff
197
git diff --base <filename>
198
git diff <sourcebranch> <targetbranch>
199
git add <filename>
200
"""
201
202
show_history :
203
insert:
204
"""
205
git log
206
"""
207
208
undo_local_changes :
209
insert:
210
"""
211
git checkout -- <filename>
212
"""
213
214
get_rid_of_local_changes :
215
insert:
216
"""
217
git fetch origin
218
git reset --hard origin/master
219
"""
220
221
search_for :
222
insert:
223
"""
224
git grep "foo()"
225
"""
226
tex :
227
integral:
228
insert: '$\int_{0}^{\infty} \frac{1}{1+x^2}\,\mathrm{d}x$'
229
cases:
230
insert: """
231
$$
232
f(n) =
233
\begin{cases}
234
2 (n+1) & \text{if} n \equiv 0 \\
235
(3n+1)/2 & \text{if} n \equiv 1.
236
\end{cases}
237
$$
238
"""
239
bold :
240
wrap :
241
left : '\\textbf{'
242
right : '}'
243
italic :
244
wrap :
245
left : '\\textit{'
246
right : '}'
247
underline :
248
wrap :
249
left : '\\underline{'
250
right : '}'
251
strikethrough : # requires the soul package
252
wrap :
253
left : '\\st{'
254
right : '}'
255
equation :
256
wrap :
257
left : "$"
258
right : "$"
259
display_equation :
260
wrap :
261
left : "$$"
262
right : "$$"
263
insertunorderedlist :
264
wrap :
265
left : "\\begin{itemize}\n \\item\n"
266
right : "\\end{itemize}"
267
insertorderedlist :
268
wrap :
269
left : "\\begin{enumerate}\n \\item\n"
270
right : "\\end{enumerate}"
271
format_heading_1 :
272
strip : ['format_heading_2','format_heading_3','format_heading_4']
273
wrap :
274
left : "\\section{"
275
right : "}"
276
format_heading_2 :
277
strip : ['format_heading_1','format_heading_3','format_heading_4']
278
wrap :
279
left : "\\subsection{"
280
right : "}"
281
format_heading_3 :
282
strip : ['format_heading_1','format_heading_2','format_heading_4']
283
wrap :
284
left : "\\subsubsection{"
285
right : "}"
286
format_heading_4 :
287
strip : ['format_heading_1','format_heading_2','format_heading_4']
288
wrap :
289
left : "\\subsubsubsection{"
290
right : "}"
291
format_code :
292
wrap :
293
left : '\n\\begin{verbatim}\n'
294
right : '\n\\end{verbatim}\n'
295
indent :
296
wrap :
297
left : "\n\\begin{quote}\n"
298
right : "\n\\end{quote}\n"
299
subscript :
300
wrap :
301
left : '_{'
302
right : '}'
303
superscript :
304
wrap :
305
left : '^{'
306
right : '}'
307
comment :
308
wrap :
309
left : '%'
310
right : ''
311
multi : true
312
space : true
313
horizontalRule:
314
wrap:
315
left : "\\hrulefill"
316
#left : "\n\\noindent\\makebox[\\linewidth]{\\rule{\\paperwidth}{0.4pt}}\n"
317
right : ""
318
319
md :
320
bold :
321
wrap :
322
left : '**'
323
right : '**'
324
italic :
325
wrap :
326
left : '_'
327
right : '_'
328
underline :
329
wrap :
330
left : '<u>'
331
right : '</u>'
332
strikethrough :
333
wrap :
334
left : '~~'
335
right : '~~'
336
insertunorderedlist :
337
wrap :
338
left : " - "
339
right : ''
340
multi : true
341
space : false
342
newline : true
343
trim : false
344
insertorderedlist :
345
wrap :
346
left : "1. "
347
right : ''
348
multi : true
349
space : false
350
newline : true
351
trim : false
352
format_heading_1 : # FUTURE -- define via for loop below
353
strip : ['format_heading_2','format_heading_3','format_heading_4']
354
wrap :
355
left : "\n# "
356
right : ""
357
format_heading_2 :
358
strip : ['format_heading_1','format_heading_3','format_heading_4']
359
wrap :
360
left : "\n## "
361
right : ""
362
format_heading_3 :
363
strip : ['format_heading_1','format_heading_2','format_heading_4']
364
wrap :
365
left : "\n### "
366
right : ""
367
format_heading_4 :
368
strip : ['format_heading_1','format_heading_2','format_heading_3']
369
wrap :
370
left : "\n#### "
371
right : ""
372
format_code :
373
wrap :
374
left : ' '
375
right : ''
376
multi : true
377
space : false
378
newline : true
379
trim : false
380
indent :
381
wrap :
382
left : '> '
383
right : ''
384
multi : true
385
space : false
386
newline : true
387
trim : false
388
horizontalRule:
389
wrap:
390
left : "\n------------------\n"
391
right : ""
392
table :
393
wrap:
394
left : """
395
| Left-Aligned | Center Aligned | Right Aligned |
396
| :------------ |:---------------:| -------------:|
397
| col 3 is | some wordy text | 1600 |
398
| col 2 is | centered | 12 |
399
| zebra stripes | and math | $\\pi^3$ |
400
"""
401
right : ""
402
403
html:
404
italic :
405
wrap :
406
left : '<em>'
407
right : '</em>'
408
bold :
409
wrap :
410
left : '<strong>'
411
right : '</strong>'
412
underline :
413
wrap :
414
left : '<u>'
415
right : '</u>'
416
strikethrough :
417
wrap :
418
left : '<strike>'
419
right : '</strike>'
420
subscript :
421
wrap :
422
left : '<sub>'
423
right : '</sub>'
424
superscript :
425
wrap :
426
left : '<sup>'
427
right : '</sup>'
428
comment :
429
wrap :
430
left : '<!--'
431
right : ' -->'
432
space : true
433
insertunorderedlist :
434
wrap :
435
left : "\n<ul>\n <li> "
436
right : "</li>\n</ul>\n"
437
insertorderedlist :
438
wrap :
439
left : "\n<ol>\n <li> "
440
right : "</li>\n</ol>\n"
441
justifyleft : # FUTURE -- define via for loop below
442
strip : ['justifycenter','justifyright','justifyfull']
443
wrap :
444
left : ""
445
right : ""
446
justifycenter :
447
strip : ['justifycenter','justifyright','justifyleft']
448
wrap :
449
left : "<div align='center'>"
450
right : "</div>"
451
justifyright :
452
strip : ['justifycenter','justifyright','justifyleft']
453
wrap :
454
left : "<div align='right'>"
455
right : "</div>"
456
justifyfull :
457
strip : ['justifycenter','justifyright','justifyleft']
458
wrap :
459
left : "<div align='justify'>"
460
right : "</div>"
461
indent :
462
wrap :
463
left : "<blockquote>"
464
right : "</blockquote>"
465
format_heading_1 : # FUTURE -- define via for loop below
466
strip : ['format_heading_2','format_heading_3','format_heading_4']
467
wrap :
468
left : "<h1>"
469
right : "</h1>"
470
format_heading_2 :
471
strip : ['format_heading_1','format_heading_3','format_heading_4']
472
wrap :
473
left : "<h2>"
474
right : "</h2>"
475
format_heading_3 :
476
strip : ['format_heading_1','format_heading_2','format_heading_4']
477
wrap :
478
left : "<h3>"
479
right : "</h3>"
480
format_heading_4 :
481
strip : ['format_heading_1','format_heading_2','format_heading_3']
482
wrap :
483
left : "<h4>"
484
right : "</h4>"
485
format_code :
486
wrap :
487
left : '<pre>'
488
right : '</pre>'
489
equation :
490
wrap :
491
left : "$"
492
right : "$"
493
display_equation :
494
wrap :
495
left : "$$"
496
right : "$$"
497
table:
498
wrap:
499
left : """
500
<table>
501
<tr>
502
<th>Header 1</th>
503
<th>Header 2</th>
504
</tr>
505
<tr>
506
<td>Cell 1</td>
507
<td>Cell 2</td>
508
</tr>
509
<tr>
510
<td>Cell 3</td>
511
<td>Cell 4</td>
512
</tr>
513
</table>
514
"""
515
right : "\n"
516
horizontalRule:
517
wrap:
518
left : "\n<hr size='1'/>\n"
519
right : ""
520
521
rst:
522
# there is intentionally no underline or strikethough in rst
523
italic :
524
wrap :
525
left : '*'
526
right : '*'
527
bold :
528
wrap :
529
left : '**'
530
right : '**'
531
subscript :
532
wrap :
533
left : ' :sub:`'
534
right : '` '
535
superscript :
536
wrap :
537
left : ' :sup:`'
538
right : '` '
539
comment :
540
wrap :
541
left : '\n..'
542
right : ''
543
multi : true
544
space : true
545
insertunorderedlist :
546
wrap :
547
left : "\n - "
548
right : ""
549
insertorderedlist :
550
wrap :
551
left : "\n 1. "
552
right : ""
553
justifyleft : # FUTURE -- define via for loop below
554
strip : ['justifycenter','justifyright','justifyfull']
555
wrap :
556
left : ""
557
right : ""
558
justifycenter :
559
strip : ['justifycenter','justifyright','justifyleft']
560
wrap :
561
left : "\n.. class:: center\n\n"
562
right : ""
563
justifyright :
564
strip : ['justifycenter','justifyright','justifyleft']
565
wrap :
566
left : "\n.. class:: right\n\n"
567
right : ""
568
justifyfull :
569
strip : ['justifycenter','justifyright','justifyleft']
570
wrap :
571
left : "\n.. class:: justify\n\n"
572
right : ""
573
indent :
574
wrap :
575
left : "\n "
576
right : ""
577
format_heading_1 : # FUTURE -- define via for loop below
578
strip : ['format_heading_2','format_heading_3','format_heading_4']
579
wrap :
580
left : "\n===============\n"
581
right : "\n===============\n"
582
format_heading_2 :
583
strip : ['format_heading_1','format_heading_3','format_heading_4']
584
wrap :
585
left : "\n---------------\n"
586
right : "\n---------------\n"
587
format_heading_3 :
588
strip : ['format_heading_1','format_heading_2','format_heading_4']
589
wrap :
590
left : "\n"
591
right : "\n=============\n"
592
format_heading_4 :
593
strip : ['format_heading_1','format_heading_2','format_heading_3']
594
wrap :
595
left : "\n"
596
right : "\n-------------\n"
597
format_code :
598
wrap :
599
left : """
600
.. code:: python
601
602
def f(x):
603
return 2*x
604
"""
605
right : '\n'
606
equation :
607
wrap :
608
left : " :math:`"
609
right : "` "
610
display_equation :
611
wrap :
612
left : "\n.. math::\n\n "
613
right : "\n"
614
table: # the first is the more complex grid table, the second one is a "simple" table
615
insert: """
616
+------------+------------+-----------+
617
| Header 1 | Header 2 | Header 3 |
618
+============+============+===========+
619
| body row 1 | column 2 | column 3 |
620
+------------+------------+-----------+
621
| body row 2 | Cells may span columns.|
622
+------------+------------+-----------+
623
| body row 3 | Cells may | - Cells |
624
+------------+ span rows. | - contain |
625
| body row 4 | | - blocks. |
626
+------------+------------+-----------+
627
628
"""
629
###
630
insert: """
631
===== ===== ======
632
Inputs Output
633
------------ ------
634
A B A or B
635
===== ===== ======
636
False False False
637
True False True
638
False True True
639
True True True
640
===== ===== ======
641
"""
642
###
643
horizontalRule:
644
insert : "\n------------------\n"
645
646
647
mediawiki : # https://www.mediawiki.org/wiki/Help:Formatting
648
bold :
649
wrap :
650
left : "'''"
651
right : "'''"
652
italic :
653
wrap :
654
left : "''"
655
right : "''"
656
underline :
657
wrap :
658
left : '<u>'
659
right : '</u>'
660
strikethrough :
661
wrap :
662
left : '<strike>'
663
right : '</strike>'
664
insertunorderedlist :
665
wrap :
666
left : "\n* item1\n* item2\n* "
667
right : "\n"
668
insertorderedlist :
669
wrap :
670
left : "\n# one\n# two\n# "
671
right : "\n"
672
comment :
673
wrap :
674
left : '\n<!--'
675
right : ' -->\n'
676
space : true
677
indent: # pre tag is more for code, but makes more sense than a dysfunctional ":"
678
wrap:
679
left : "\n<pre>"
680
right : "</pre>\n"
681
format_heading_1 : # FUTURE -- define via for loop below
682
strip : ['format_heading_2','format_heading_3','format_heading_4']
683
wrap :
684
left : "\n== "
685
right : " ==\n"
686
format_heading_2 :
687
strip : ['format_heading_1','format_heading_3','format_heading_4']
688
wrap :
689
left : "\n=== "
690
right : " ===\n"
691
format_heading_3 :
692
strip : ['format_heading_1','format_heading_2','format_heading_4']
693
wrap :
694
left : "\n==== "
695
right : " ====\n"
696
format_heading_4 :
697
strip : ['format_heading_1','format_heading_2','format_heading_3']
698
wrap :
699
left : "\n===== "
700
right : " =====\n"
701
format_code :
702
wrap :
703
left : ' <code>'
704
right : '</code> '
705
horizontalRule:
706
wrap:
707
left : "\n----\n"
708
right : ""
709
table: # https://www.mediawiki.org/wiki/Help:Tables
710
insert: """\n
711
{| class="table"
712
|+Table Caption
713
! Column 1
714
! Column 2
715
|-
716
|Integral
717
|Derivative
718
|-
719
|Sin
720
|Cos
721
|-
722
|Tan
723
|Sec
724
|}
725
"""
726
727
python:
728
comment :
729
wrap :
730
left : '#'
731
right : ''
732
multi : true
733
space : true
734
len :
735
insert : "len([1, 2, 5, 6, 10])"
736
list :
737
insert : "[1, 2, 5, 6, 10]"
738
list_comprehension :
739
insert : "[n+1 for n in range(10) if n%2==0]"
740
read_csv_file :
741
insert:
742
"""
743
import csv
744
import sys
745
746
f = open('example.csv', 'rt')
747
try:
748
reader = csv.reader(f)
749
for row in reader:
750
print row
751
finally:
752
f.close()
753
"""
754
write_csv_file :
755
insert:
756
"""
757
import csv
758
import sys
759
760
f = open('example.csv', 'wt')
761
try:
762
writer = csv.writer(f)
763
writer.writerow( ('Title 1', 'Title 2', 'Title 3') )
764
for i in range(10):
765
writer.writerow( (i+1, chr(ord('a') + i), '08/%02d/07' % (i+1)) )
766
finally:
767
f.close()
768
769
print open('example.csv', 'rt').read()
770
"""
771
dict :
772
insert : "{'sage':'math', 3:7}"
773
set :
774
insert : "{7, 3, 2}"
775
tuple :
776
insert : "(2, 3, 7)"
777
forloop :
778
insert: """
779
for i in range(5):
780
print i
781
"""
782
forlistloop:
783
insert: """
784
l = [1, 2, 5, 8, 10]
785
for i in l:
786
print i
787
"""
788
forelseloop:
789
insert: """
790
for k in [1, 2, 5, 10]:
791
if k == 3:
792
print "found k, returning"
793
break
794
else:
795
print "Haven't found k == 3"
796
"""
797
whileloop:
798
insert: """
799
n = 0
800
while n < 5:
801
print n
802
n += 1
803
"""
804
"if":
805
insert: """
806
if i == 1:
807
print 'i equals 1'
808
"""
809
ifelse:
810
insert: """
811
if i == 1:
812
print 'i equals 1'
813
else:
814
print 'i is not 1'
815
"""
816
cases:
817
insert: """
818
if i == 0:
819
print "i is zero"
820
elif i == 1:
821
print "i is one"
822
else:
823
print "i is neither zero or one"
824
"""
825
function:
826
insert: """
827
def f(a, b=0):
828
\"\"\"
829
This function returns the sum of a and b.
830
\"\"\"
831
return a + b
832
"""
833
lambda :
834
insert: """f = lambda a, b: a + b"""
835
simple_class :
836
insert: """
837
class MyClass(object):
838
\"\"\"
839
This is a simple class.
840
\"\"\"
841
def __init__(self, a):
842
self.a = a
843
def __repr__(self):
844
return "Instance of MyClass with a = %s"%self.a
845
846
print(MyClass(5))
847
"""
848
class_inheritence :
849
insert: """
850
class A(object):
851
def __repr__(self):
852
return "instance of A"
853
def foo(self):
854
return "foo"
855
856
class B(object):
857
def __repr__(self):
858
return "instance of B"
859
def bar(self):
860
return "bar"
861
862
class C(A, B):
863
\"\"\"
864
This is a class that inerits from classes A and B.
865
\"\"\"
866
def __repr__(self):
867
return "instance of C"
868
869
# Both foo and bar are defined on instances of C.
870
c = C()
871
print(c.foo(), c.bar())
872
"""
873
cython:
874
cython_class :
875
insert: """
876
cdef class MyClass:
877
\"\"\"
878
This is a Cython class.
879
\"\"\"
880
cdef int a
881
def __init__(self, int a):
882
self.a = a
883
def __repr__(self):
884
return "Instance of MyClass with a = %s"%self.a
885
886
print(MyClass(5))
887
"""
888
sage:
889
sagemathdoc:
890
url: 'http://doc.sagemath.org/'
891
sagemathtutorial:
892
url: 'http://doc.sagemath.org/html/en/tutorial/index.html'
893
sagemathreference:
894
url: 'http://doc.sagemath.org/html/en/reference/index.html'
895
sagemathkeyboardshortcuts:
896
url: 'https://github.com/sagemathinc/cocalc/wiki/Keyboard-Shortcuts'
897
help:
898
wrap:
899
left : "help("
900
right : ")"
901
differentiate:
902
insert : 'diff(1 + x + x^2, x)'
903
integrate:
904
insert : 'integrate(1 + x + x^2, x)'
905
nintegrate:
906
insert : 'numerical_integral(1 + x + x^2, 0, 3)[0] # [1] gives error bound'
907
symbolic_function:
908
insert : 'f(x,y) = x * sin(y)'
909
matrix:
910
insert : "matrix(2, 3, [1,pi,3, e,5,6])"
911
vector:
912
insert : "vector([pi, 2, 3, e])"
913
plot2d:
914
insert : "plot(x * sin(x), (x, -2, 10))"
915
plot_line:
916
insert : "line([(0,0), (1,2), (1/2,pi), (1/2,pi/2)], color='darkgreen', thickness=3)"
917
plot_polygon:
918
insert : """
919
a = polygon2d([(0,0), (1,2), (1/2,pi), (1/2,pi/2)], color='orange')
920
b = polygon2d([(0,0), (1,2), (1/2,pi), (1/2,pi/2)], color='black', fill=False, thickness=3)
921
show(a + b)
922
"""
923
plot_parametric:
924
insert : "parametric_plot([cos(x) + 2*cos(x/4), sin(x) - 2*sin(x/4)], (x,0,8*pi), color='green', thickness=3, fill = True)"
925
plot_random_walk:
926
insert : "stats.TimeSeries(1000).randomize('normal').sums().plot()"
927
plot_text:
928
insert : 'text(r"Text and LaTeX: $\\alpha^3 + 1$", (1,1), color="black", fontsize=15, rotation=30)'
929
plot_points:
930
insert : "show(points([(1,0), (sqrt(2)/2,sqrt(2)/2), (0,1), (1/2,1/2)], color='darkgreen', pointsize=50), aspect_ratio=1)"
931
plot3d:
932
insert : """
933
%var x y
934
plot3d(x * sin(y), (x, -5, 5), (y, -5, 5))
935
"""
936
plot_torus:
937
insert : """
938
from sage.plot.plot3d.shapes import Torus
939
inner_radius = .3; outer_radius = 1
940
show(Torus(outer_radius, inner_radius, color='orange'), aspect_ratio=1, spin=3)
941
"""
942
parametric_curve3d:
943
insert : """
944
%var u
945
parametric_plot3d( (sin(u), cos(u), u/10), (u, 0, 20), thickness=5, color='green', plot_points=100)
946
"""
947
parametric_surface:
948
insert : """
949
%var u, v
950
fx = (3*(1+sin(v)) + 2*(1-cos(v)/2)*cos(u))*cos(v)
951
fy = (4+2*(1-cos(v)/2)*cos(u))*sin(v)
952
fz = -2*(1-cos(v)/2) * sin(u)
953
parametric_plot3d([fx, fy, fz], (u, 0, 2*pi), (v, 0, 2*pi), color="green", opacity=.7, mesh=1, spin=5)
954
"""
955
implicit_plot3d:
956
insert : """
957
%var x y z
958
g = golden_ratio; r = 4.77
959
p = 2 - (cos(x + g*y) + cos(x - g*y) + cos(y + g*z) +
960
cos(y - g*z) + cos(z - g*x) + cos(z + g*x))
961
show(implicit_plot3d(p, (x, -r, r), (y, -r, r), (z, -r, r),
962
plot_points=30, color='orange', mesh=1, opacity=.7), spin=1)
963
"""
964
965
random_walk_3d:
966
insert : """
967
v = [(0,0,0)]
968
for i in range(1000):
969
v.append([a+random()-.5 for a in v[-1]])
970
line3d(v, color='red', thickness=3, spin=3)
971
"""
972
polytope :
973
insert : """
974
points = [(2,0,0), (0,2,0), (0,0,2), (-1,0,0), (0,-1,0), (0,0,-1)]
975
show(LatticePolytope(points).plot3d(), spin=5)
976
"""
977
icosahedron :
978
insert : "show(icosahedron(color='green', opacity=.5, mesh=3), spin=1)"
979
tetrahedron:
980
insert : "show(tetrahedron(color='lime', opacity=.5, mesh=3), spin=1)"
981
cube :
982
insert : """
983
show(cube(color=['red', 'blue', 'green'], frame_thickness=2,
984
frame_color='brown', opacity=0.8), frame=False)
985
"""
986
plot_text3d:
987
insert : 'text3d("Text in 3D", (1,1, 1), color="darkred", fontsize=20)'
988
graphs:
989
insert : "# Press the TAB key after 'graphs.' to see a list of predefined graphs.\ngraphs."
990
petersen:
991
insert : "graphs.PetersenGraph()"
992
random_graph:
993
insert : "g = graphs.RandomGNM(15, 20) # 15 vertices and 20 edges\nshow(g)\ng.incidence_matrix()"
994
chromatic_number:
995
insert : "g = graphs.PetersenGraph().chromatic_number()\nshow(g)"
996
auto_group_graph:
997
insert : "graphs.PetersenGraph().automorphism_group()"
998
graph_2dplot:
999
insert : "show(graphs.PetersenGraph())"
1000
graph_3dplot:
1001
insert : "show(graphs.PetersenGraph().plot3d(), frame=False)"
1002
factor:
1003
insert : "factor(2015)"
1004
primes:
1005
insert : "prime_range(100)"
1006
prime_pi:
1007
insert : "prime_pi(10^6)"
1008
mod:
1009
insert : "Mod(5, 12)"
1010
contfrac:
1011
insert : "continued_fraction(e)"
1012
binary_quadform:
1013
insert : "BinaryQF([1,2,3])"
1014
ellcurve:
1015
insert : "EllipticCurve([1,2,3,4,5])"
1016
var:
1017
insert : "%var x, theta"
1018
det:
1019
insert : "matrix(2, 2, [1,2, 3,4]).det()"
1020
charpoly:
1021
insert : "matrix(2, 2, [1,2, 3,4]).charpoly()"
1022
eigen:
1023
insert : "matrix(3,[1,2,3, 4,5,6, 7,8,9]).right_eigenvectors()"
1024
svd:
1025
insert : "matrix(CDF, 3, [1,2,3, 4,5,6, 7,8,9]).SVD()"
1026
numpy_array:
1027
insert : "import numpy\nnumpy.array([[1,2,3], [4,5,6]], dtype=float)"
1028
1029
ring_AA:
1030
insert : "AA"
1031
ring_CC:
1032
insert : "CC"
1033
ring_CDF:
1034
insert : "CDF"
1035
ring_CIF:
1036
insert : "CIF"
1037
ring_CLF:
1038
insert : "CLF"
1039
ring_FF_p:
1040
insert : "GF(7)"
1041
ring_FF_pr:
1042
insert : "GF(7^3,'a')"
1043
ring_QQ:
1044
insert : "QQ"
1045
ring_QQbar:
1046
insert : "QQbar"
1047
ring_QQp:
1048
insert : "Qp(7)"
1049
ring_RR:
1050
insert : "RR"
1051
ring_RDF:
1052
insert : "RDF"
1053
ring_RIF:
1054
insert : "RIF"
1055
ring_RLF:
1056
insert : "RLF"
1057
ring_ZZ:
1058
insert : "ZZ"
1059
ring_ZZp:
1060
insert : "Zp(7)"
1061
ring_QQx:
1062
insert : "R.<x> = QQ[]"
1063
ring_QQxyz:
1064
insert : "R.<x,y,z> = QQ[]"
1065
ring_ZZxp:
1066
insert : "R = PolynomialRing(ZZ, ['x%s'%p for p in primes(100)])\nR.inject_variables()"
1067
ring_QQ_quo:
1068
insert : "R.<x,y> = QQ[]\nR.<xx, yy> = R.quo([y^2 - x^3 - x])"
1069
interact_fx:
1070
insert : """
1071
@interact
1072
def interactive_function(a = slider(0, 10, .05, default=4),
1073
b = (-3, 3, .1)):
1074
f(x) = b * x + sin(a * x)
1075
plot(f, (x, -5, 5)).show()
1076
"""
1077
modes:
1078
insert : "print('\\n'.join(modes()))"
1079
jupyterkernels:
1080
insert : "print(jupyter.available_kernels())"
1081
mode_typeset:
1082
insert : "%typeset_mode True\n"
1083
mode_auto:
1084
insert : "%auto"
1085
mode_cython:
1086
insert : "%cython\n"
1087
mode_default_mode:
1088
insert : "%default_mode r # change r to any mode\n"
1089
mode_exercise:
1090
insert : "%exercise\n"
1091
mode_gap:
1092
insert : "%gap\n"
1093
mode_gp:
1094
insert : "%gp\n"
1095
mode_hide:
1096
insert : "%hide\n"
1097
mode_html:
1098
insert : "%html\n"
1099
mode_julia:
1100
insert : "%julia\n"
1101
mode_javascript:
1102
insert : "%javascript\n/* Use print(...) for output */"
1103
mode_jupyter_bridge:
1104
insert : """
1105
a3 = jupyter("anaconda3")
1106
# start new cells with %a3
1107
# or set %default_mode a3
1108
"""
1109
mode_md:
1110
insert : "%md\n"
1111
mode_octave:
1112
insert : "%octave\n"
1113
mode_python:
1114
insert : "%python\n"
1115
mode_r:
1116
insert : "%r\n"
1117
mode_scilab:
1118
insert : "%scilab\n"
1119
mode_sh:
1120
insert : "%sh\n"
1121
mode_time:
1122
wrap:
1123
left : "%time "
1124
right : ""
1125
mode_timeit:
1126
wrap:
1127
left : "%timeit "
1128
right : ""
1129
comment:
1130
wrap:
1131
left : "# "
1132
right : ""
1133
multi : true
1134
space : true
1135
assign:
1136
insert : "a = 5"
1137
forloop:
1138
insert : """
1139
for animal in ["dog", "cat", "mouse"]
1140
println("$animal is a mammal")
1141
end
1142
"""
1143
function :
1144
insert : """
1145
function add(x, y)
1146
println("x is $x and y is $y")
1147
# Functions return the value of their last statement
1148
x + y
1149
end
1150
1151
println(add(2000, 15))
1152
"""
1153
ifelse:
1154
insert : """
1155
a = 10
1156
if a > 10
1157
println("a is bigger than 10.")
1158
elseif a < 10 # This elseif clause is optional.
1159
println("a is smaller than 10.")
1160
else # The else clause is optional too.
1161
println("a is indeed 10.")
1162
end
1163
"""
1164
1165
r: # http://cran.r-project.org/doc/manuals/r-release/R-intro.html
1166
comment:
1167
wrap:
1168
left : "#"
1169
right : ''
1170
multi : true
1171
space : true
1172
vector:
1173
insert : "v <- c(1,1,2,3,5,8,13)"
1174
forloop:
1175
insert : """
1176
for (i in seq(1, 10, by=2)) {
1177
print(sprintf("i = %s", i));
1178
}
1179
"""
1180
ifelse:
1181
insert: """
1182
k <- 10
1183
if (k > 5) {
1184
print("k greater than 5")
1185
} else {
1186
print("k less or equal than 5")
1187
}
1188
"""
1189
summary:
1190
wrap:
1191
left : "summary("
1192
right : ")"
1193
plot:
1194
insert: "plot(c(1,2,4,8,16,32,64), c(1,1,2,3,5,8,13), type=\"l\")"
1195
seq:
1196
insert: "-5:5"
1197
seq_by:
1198
insert: "seq(-5, 5, by=.2)"
1199
seq_length:
1200
insert: "seq(length=51, from=-5, by=.2)"
1201
rep1:
1202
insert: "rep(c(5,1,3), times = 3)"
1203
rep2:
1204
insert: "rep(c(5,1,3), each = 3)"
1205
charvec:
1206
insert: """paste(c("X","Y"), 1:10, sep="")"""
1207
mean:
1208
insert: "mean(c(4,3,4,2,-1,3,2,3,2))"
1209
matrix:
1210
insert: "array(1:20, dim=c(4,5))"
1211
assign:
1212
insert: """
1213
x <- "hello"
1214
print(x)
1215
"""
1216
outer:
1217
insert: "c(1,2) %o% c(4,4)"
1218
matrixmult:
1219
insert: """
1220
x <- c(1,2,3,4)
1221
A <- array(seq(1:20), dim=c(5,4))
1222
A %*% x
1223
"""
1224
function:
1225
insert: """
1226
f <- function(x, y) {
1227
y <- 2 * x + y
1228
return(y + cos(x))
1229
}
1230
f(1,2)
1231
"""
1232
inverse:
1233
insert: "solve(array(c(2,1,-4,1), dim=c(2,2)))"
1234
solvelin:
1235
insert: "solve(array(c(2,1,-4,1), dim=c(2,2)), c(6,7))"
1236
svd:
1237
insert: "svd(array(-9:6, dim=c(4,4)))"
1238
list1:
1239
insert: """
1240
# index into a list via [[idx]]
1241
l <- list(1,"fred", c(1,2,3))
1242
print(l[[1]])
1243
print(l[[2]])
1244
print(l[[3]])
1245
"""
1246
list2:
1247
insert: """
1248
# assoziated list of names and objects
1249
l <- list(a = 1, b = c(1,2,3))
1250
print(l$a) # access a in l
1251
print(l$b)
1252
"""
1253
arrayselect:
1254
insert: "x <- c(4,7,3,2,9)\nx[x > 4]"
1255
dataframe:
1256
insert:
1257
"""
1258
a <- c(1,2,1)
1259
b <- c("Fred", "Susan", "Joe")
1260
c <- seq(1, by=.01, length=3)
1261
df <- data.frame(sex = a, name = b, result = c)
1262
df
1263
# for more information: help(data.frame)
1264
"""
1265
normal:
1266
insert: "rnorm(10, mean = 100, sd = 1)"
1267
stem:
1268
insert: "# condensed overview of all numbers in the given list\nstem(rnorm(1000, mean = 5, sd = 10))"
1269
defaultsize:
1270
insert: "%sage r.set_plot_options(height=4, width=10)"
1271
attach:
1272
insert: "# attach loads internal datasets\nattach(faithful)\nprint(summary(faithful))\nprint(head(faithful))"
1273
histdensity:
1274
insert: """
1275
attach(faithful)
1276
hist(eruptions, seq(1.6, 5.2, 0.2), prob=TRUE)
1277
lines(density(eruptions, bw=0.1))
1278
rug(eruptions)
1279
"""
1280
qqplot:
1281
insert: """
1282
attach(faithful)
1283
long <- eruptions[eruptions > 3]
1284
par(pty="s") # square figure
1285
qqnorm(long)
1286
qqline(long)
1287
"""
1288
boxplot:
1289
insert: """
1290
a <- rnorm(10)
1291
b <- rnorm(10, mean=2)
1292
boxplot(a, b)
1293
"""
1294
contour:
1295
insert: """
1296
x <- seq(-pi, pi, len=50)
1297
y <- x
1298
f <- outer(x, y, function(x, y) cos(y)/(1 + x^2))
1299
contour(x, y, f, nlevels=15)
1300
"""
1301
lm:
1302
insert: """
1303
y <- c(0,3,2,2,4,5,8,9,7,6,2,0)
1304
x1 <- c(1,2,3,4,3,4,5,7,5,7,8,9)
1305
x2 <- c(1,1,1,1,2,2,2,3,3,3,4,4)
1306
df <- data.frame(x1=x1, x2=x2)
1307
model <-lm(y ~ x1 + x2, data=df)
1308
model
1309
summary(model)
1310
anova(model)
1311
"""
1312
nlm:
1313
insert: """
1314
x <- c(0.02, 0.02, 0.06, 0.06, 0.11, 0.11, 0.22, 0.22, 0.56, 0.56, 1.10, 1.10)
1315
y <- c(76, 47, 97, 107, 123, 139, 159, 152, 191, 201, 207, 200)
1316
# function to be fitted
1317
fn <- function(p) sum((y - (p[1] * x)/(p[2] + x))^2)
1318
# supplying nlm with starting varlues
1319
nlm(fn, p = c(200, 0.1), hessian = TRUE)
1320
"""
1321
1322
###
1323
fricas:
1324
help:
1325
wrap:
1326
insert : ")summary"
1327
explain:
1328
wrap:
1329
left : ")display operation "
1330
right : ""
1331
differentiate:
1332
insert : 'differentiate(1 + x + x^2, x)'
1333
integrate:
1334
insert : 'integrate(1 + x + x^2, x)'
1335
nintegrate:
1336
insert : 'aromberg(sin, -%pi, %pi, 0.0001, 0.001, 2, 5, 20) -- aromberg(fn, a, b, epsrel, epsabs, nmin, nmax, nint)'
1337
'one-line function':
1338
insert : 'f(x,y) == x * sin(y)'
1339
matrix:
1340
insert : "matrix [[1,%pi],[3, %e],[5,6]]"
1341
vector:
1342
insert : "vector [%pi, 2, 3, %e]"
1343
factor:
1344
insert : "factor 2015"
1345
primes:
1346
insert : "primes(1,100)"
1347
mod:
1348
insert : "12::IntegerMod(5)"
1349
contfrac:
1350
insert : "continuedFraction(%e::Expression Float)$NumericContinuedFraction(Float)"
1351
determinant:
1352
insert : "determinant matrix [[1,2], [3,4]]"
1353
charpoly:
1354
insert : "characteristicPolynomial matrix [[1,2], [3,4]]"
1355
eigen:
1356
insert : "eigenvectors matrix [[1,2, 3], [4,5,6], [7,8,9]]"
1357
1358
ring_CC:
1359
insert : "Polynomial Complex Float"
1360
ring_QQ:
1361
insert : "Polynomial Fraction Integer"
1362
ring_RR:
1363
insert : "Polynomial Float"
1364
ring_ZZ:
1365
insert : "Polynomial Integer"
1366
comment:
1367
wrap:
1368
left : "--"
1369
right: ""
1370
multi : true
1371
space : true
1372
assign:
1373
insert : "a: = 5"
1374
forloop:
1375
insert : """
1376
for animal in ["dog", "cat", "mouse"] repeat
1377
output("Mammal: ",animal)
1378
"""
1379
function :
1380
insert : """
1381
plus(x, y) ==
1382
output("x is ",x)
1383
output("and y is ",y)
1384
-- Functions return the value of their last statement
1385
return x + y
1386
1387
output plus(2000, 15)
1388
"""
1389
ifelse:
1390
insert : """
1391
a := 10
1392
if a > 10 then
1393
output("a is bigger than 10.")
1394
else -- This elseif clause is optional.
1395
if a < 10 then
1396
output("a is smaller than 10.")
1397
else -- The else clause is optional too.
1398
output("a is indeed 10.")
1399
"""
1400
###
1401
1402
#
1403
# programmatically creating the menu entries and buttons
1404
#
1405
1406
#
1407
# helper functions
1408
#
1409
1410
make_bar = (cls) ->
1411
cls ?= ""
1412
return $("<span class='btn-group #{cls}'></span>")
1413
1414
# this adds the content of a dropdown menu (basically, single or triple entries)
1415
add_menu = (bar, entries) ->
1416
dropdown = $("<span class='btn-group'></span>")
1417
dropdown.append($("""
1418
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="#{entries[1]}">
1419
#{entries[0]} <b class="caret"></b>
1420
</span>
1421
"""))
1422
1423
droplist = $("<ul class='dropdown-menu'></ul>")
1424
divider = """<li class="divider"></li>"""
1425
first = true
1426
for item in entries[2]
1427
if item.length == 1 # new divider
1428
# don't show dividing line if it is at the very top
1429
d = if first then '' else divider
1430
d += """<li role="presentation" class="dropdown-header">#{item[0]}</li>"""
1431
e = $(d)
1432
else if item.length in [2, 3] # item in the menu
1433
help = ""
1434
if item.length == 3 and item[2].length > 0
1435
help = "data-toggle='tooltip' data-placement='right' title='#{item[2]}'"
1436
e = $("<li><a href='#{item[1]}' #{help}>#{item[0]}</a></li>")
1437
first = false
1438
droplist.append(e)
1439
1440
dropdown.append(droplist)
1441
bar.append(dropdown)
1442
1443
# this adds a single icon to the bar
1444
add_icon = (bar, inner, href, comment) ->
1445
help = ""
1446
if comment.length > 0
1447
help = "data-toggle='tooltip' data-placement='bottom' title='#{comment}'"
1448
icon = $("<a href='#{href}' class='btn btn-default' #{help}></a>")
1449
icon.html(inner)
1450
bar.append(icon)
1451
1452
#
1453
# initializing and creating the menus
1454
# this works in conjunction with editor.html
1455
#
1456
1457
# Initialize fonts for the editor
1458
initialize_sagews_editor = () ->
1459
bar = $(".webapp-editor-codemirror-worksheet-editable-buttons")
1460
elt = bar.find(".sagews-output-editor-font").find(".dropdown-menu")
1461
for font in 'Serif,Sans,Arial,Arial Black,Courier,Courier New,Comic Sans MS,Georgia,Helvetica,Impact,Lucida Grande,Lucida Sans,Monaco,Palatino,Tahoma,Times New Roman,Verdana'.split(',')
1462
item = $("<li><a href='#fontName' data-args='#{font}'>#{font}</a></li>")
1463
item.css('font-family', font)
1464
elt.append(item)
1465
1466
elt = bar.find(".sagews-output-editor-font-size").find(".dropdown-menu")
1467
for size in [1..7]
1468
item = $("<li><a href='#fontSize' data-args='#{size}'><font size=#{size}>Size #{size}</font></a></li>")
1469
elt.append(item)
1470
1471
elt = bar.find(".sagews-output-editor-block-type").find(".dropdown-menu")
1472
for i in [1..6]
1473
item = $("<li><a href='#formatBlock' data-args='<H#{i}>'><H#{i} style='margin:0'>Heading</H#{i}></a></li>")
1474
elt.append(item)
1475
1476
elt.prepend('<li role="presentation" class="divider"></li>')
1477
1478
# trick so that data is retained even when editor is cloned:
1479
args = JSON.stringify([null, {normalize: true, elementTagName:'code', applyToEditableOnly:true}])
1480
item = $("<li><a href='#ClassApplier' data-args='#{args}'><i class='fa fa-code'></i> <code>Code</code></a></li>")
1481
elt.prepend(item)
1482
1483
elt.prepend('<li role="presentation" class="divider"></li>')
1484
item = $("<li><a href='#removeFormat'><i class='fa fa-remove'></i>
1485
Normal</a></li>")
1486
elt.prepend(item)
1487
1488
1489
# Initialize fonts for the editor
1490
initialize_md_html_editor = () ->
1491
bar = $(".webapp-editor-textedit-buttonbar")
1492
elt = bar.find(".sagews-output-editor-font-face").find(".dropdown-menu")
1493
for font in FONT_FACES
1494
item = $("<li><a href='#font_face' data-args='#{font}'>#{font}</a></li>")
1495
item.css('font-family', font)
1496
elt.append(item)
1497
1498
elt = bar.find(".sagews-output-editor-font-size").find(".dropdown-menu")
1499
v = [1..7]
1500
v.reverse()
1501
for size in v
1502
item = $("<li><a href='#font_size' data-args='#{size}'><font size=#{size}>Size #{size} #{if size==3 then 'default' else ''}</font></a></li>")
1503
elt.append(item)
1504
1505
elt = bar.find(".sagews-output-editor-block-type").find(".dropdown-menu")
1506
for i in [1..4]
1507
elt.append($("<li><a href='#format_heading_#{i}'><H#{i} style='margin:0'>Heading #{i}</H#{i}></a></li>"))
1508
elt.append('<li role="presentation" class="divider"></li>')
1509
elt.append($("<li><a href='#format_code'><i class='fa fa-code'></i> <code>Code</code></a></li>"))
1510
1511
# adding Python & Sage menu entries programmatically (editing HTML directly is too painful)
1512
# FUTURE: make a general class for menu entries and hence use these functions for all menu entries?
1513
initialize_sage_python_r_toolbar = () ->
1514
# reference example, FUTURE: delete it
1515
"""
1516
<span class="btn-group">
1517
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Control Structures">
1518
<i class="fa">Control</i> <b class="caret"></b>
1519
</span>
1520
<ul class="dropdown-menu">
1521
<li role="presentation" class="dropdown-header">Loops</li>
1522
<li><a href='#forloop' data-toggle="tooltip" data-placement="right" title="Iterate over a range of integers">For-Loop</a></li>
1523
<li><a href="#forlistloop">For-Loop over a list</a></li>
1524
<li class="divider"></li>
1525
<li role="presentation" class="dropdown-header">Decisions</li>
1526
<li><a href='#if'>If clause</a></li>
1527
<li><a href='#ifelse'>If-else clause</a></li>
1528
<li class="divider"></li>
1529
<li role="presentation" class="dropdown-header">Advanced</li>
1530
<li><a href="#cases">Cases</a></li>
1531
<li><a href='#forelseloop'>For-Else Loop</a></li>
1532
</ul>
1533
</span>
1534
<a href='#comment' class='btn btn-default' data-toggle="tooltip" data-placement="bottom" title="Comment selected code"><i class="fa">#</i></a>
1535
</span>
1536
"""
1537
1538
codebar = $(".webapp-editor-codeedit-buttonbar")
1539
1540
# -- modes (this isn't really code so weird to put here)
1541
system_bar = make_bar("webapp-editor-codeedit-buttonbar-system")
1542
1543
mode_list = ["Modes", "Sage Worksheet Modes",
1544
[
1545
["General"],
1546
["Auto execute cell on startup", "#mode_auto"],
1547
["Hide input", "#mode_hide"],
1548
["Set default mode", "#mode_default_mode"],
1549
["Typeset output", "#mode_typeset"],
1550
["Timing"],
1551
["Benchmark code repeatedly", "#mode_timeit"],
1552
["Time code once", "#mode_time"],
1553
["Language modes"],
1554
["Cython", "#mode_cython"],
1555
["Gap", "#mode_gap"],
1556
["PARI/GP", "#mode_gp"],
1557
["HTML", "#mode_html"],
1558
["Javascript", "#mode_javascript"],
1559
["Julia", "#mode_julia"],
1560
["Jupyter bridge", "#mode_jupyter_bridge"],
1561
["Markdown", "#mode_md"],
1562
["Octave", "#mode_octave"],
1563
["Python", "#mode_python"],
1564
["R", "#mode_r"],
1565
["Shell", "#mode_sh"],
1566
1567
]]
1568
add_menu(system_bar, mode_list)
1569
1570
help_list = ["<i class='fa fa-question-circle'></i> Help", "Sage Worksheet Help",
1571
[
1572
["General help", "#help"],
1573
["Mode commands", "#modes"],
1574
["Jupyter kernels", "#jupyterkernels"],
1575
["SageMath Documentation"],
1576
["Overview", "#sagemathdoc"],
1577
["Tutorial", "#sagemathtutorial"],
1578
["Reference", "#sagemathreference"],
1579
["Keyboard Shortcuts", "#sagemathkeyboardshortcuts"]
1580
]]
1581
add_menu(system_bar, help_list)
1582
## MAYBE ADD THESE in another menu:
1583
#axiom
1584
#capture
1585
#coffeescript
1586
#command
1587
#file
1588
#fork
1589
#fortran
1590
#fricas
1591
#gap3
1592
#giac
1593
#go
1594
#hideall
1595
#javascript
1596
#kash
1597
#lie
1598
#lisp
1599
#load
1600
#macaulay2
1601
#maxima
1602
#octave
1603
#pandoc
1604
#perl
1605
#prun
1606
#reset
1607
#ruby
1608
#runfile
1609
#sage0
1610
#script
1611
#singular
1612
#typeset_mode
1613
#var
1614
#wiki
1615
#mode_list = ["More", "More Sage Worksheet Modes",
1616
# [
1617
# ["Axiom", "#mode_axiom"],
1618
# ["Scilab", "#mode_scilab"],
1619
# ["Shell script", "#mode_sh"],
1620
# []
1621
# ]]
1622
#add_menu(system_bar, mode_list)
1623
codebar.append(system_bar)
1624
1625
# -- python specific --
1626
pybar = make_bar("webapp-editor-codeedit-buttonbar-python")
1627
add_icon(pybar, "<i class='fa'>#</i>", "#comment", "Comment selected text")
1628
1629
py_control = ["Data", "Basic Data Types",
1630
[["Construction"],
1631
["Dictionary", "#dict"],
1632
["List", "#list"],
1633
["List Comprehension", "#list_comprehension"],
1634
["Set", "#set"],
1635
["Tuple", "#tuple"],
1636
["Properties"],
1637
["Length", "#len"],
1638
["CSV"],
1639
["Read CSV file", "#read_csv_file"],
1640
["Write CSV file", "#write_csv_file"]
1641
]]
1642
add_menu(pybar, py_control)
1643
1644
# structured dropdown menu data: button text, title info, list of ["button, "#id", "title help (optional)"]
1645
py_control = ["Control", "Control Structures",
1646
[["Loops"],
1647
["For-Loop", "#forloop", "Iterate over a range of integers"],
1648
["For-Loop over a list", "#forlistloop", "Iterate over a list"],
1649
["While loop", "#whileloop", "Loop while a condition holds"],
1650
["Decisions"],
1651
["If", "#if"],
1652
["If-Else", "#ifelse"],
1653
["Advanced"],
1654
["Cases", "#cases", "Deciding between different cases"],
1655
["For-Else Loop", "#forelseloop", "Searching for an item with a fallback."]
1656
]]
1657
add_menu(pybar, py_control)
1658
1659
py_func = ["Program", "Define Functions and Classes",
1660
[
1661
["Functions"],
1662
["Function", "#function", "Define a Python function"],
1663
["Lambda", "#lambda", "A Python lambda function"]
1664
["Classes"],
1665
["Class", "#simple_class", "Define a simple class"],
1666
["Class with inheritence", "#class_inheritence", "A class that inherits from other classes"]
1667
]]
1668
1669
add_menu(pybar, py_func)
1670
1671
codebar.append(pybar)
1672
1673
# -- Cython specific
1674
cythonbar = make_bar("webapp-editor-codeedit-buttonbar-cython")
1675
cython_classes = ["Cython Classes", "Define cdef'd Classes",
1676
[
1677
["cdef Class", "#cython_class", "Define a Cython class"],
1678
]
1679
]
1680
add_menu(cythonbar, cython_classes)
1681
cythonbar.append(cythonbar)
1682
1683
# -- sage specific --
1684
sagebar = make_bar("webapp-editor-codeedit-buttonbar-sage")
1685
1686
sage_calculus = ["Calculus", "Calculus",
1687
[["&part; Differentiate", "#differentiate", "Differentiate a function"],
1688
["&int; Numerical Integral", "#nintegrate", "Numerically integrate a function"]
1689
["$f(x,y) = \\cdots $ - Symbolic Function", "#symbolic_function", "Define a symbolic function"]
1690
["&int; Symbolic Integral", "#integrate", "Integrate a function"],
1691
["Interact Plots"],
1692
["Interactive f(x)", "#interact_fx"]
1693
]]
1694
sage_linalg = ["Linear", "Linear Algebra",
1695
[
1696
["Matrix $M$", "#matrix", "Define a matrix"],
1697
["Vector $\\vec v$", "#vector", "Define a vector"],
1698
["Functions"]
1699
["Characteristic Polynomial", "#charpoly"]
1700
["Determinant", "#det"]
1701
["Eigenvectors", "#eigen", "Eigenvalues and eigenvectors of matrix"]
1702
["SVD", "#svd", "Singular value decomposition of matrix"]
1703
1704
["Numpy"],
1705
["Array", "#numpy_array"],
1706
]]
1707
sage_plotting = ["Plots", "Plotting Graphics",
1708
[
1709
["2D Plotting"],
1710
["Function", "#plot2d", "Plot f(x)"],
1711
["Line", "#plot_line", "Sequence of line segments"],
1712
["Parametric", "#plot_parametric", "Parematric plot"],
1713
["Points", "#plot_points", "Plot many points"],
1714
["Polygon", "#plot_polygon"],
1715
["Random Walk", "#plot_random_walk", "A random walk"],
1716
["Text", "#plot_text", "Draw text"],
1717
["3D Plotting"],
1718
["Cube", "#cube", "Show a colored cube"],
1719
["Function", "#plot3d", "Plot f(x, y)"],
1720
["Icosahedron", "#icosahedron"],
1721
["Implicit Plot", "#implicit_plot3d", "Create an implicit 3D plot"],
1722
["Parametric Curve", "#parametric_curve3d"],
1723
["Parametric Surface", "#parametric_surface"],
1724
["Polytope", "#polytope"],
1725
["Random Walk", "#random_walk_3d", "A 3d Random Walk"],
1726
["Tetrahedron", "#tetrahedron"],
1727
["Text", "#plot_text3d", "Draw text"],
1728
["Torus", "#plot_torus"]
1729
]]
1730
sage_graphs = ["Graphs", "Graph Theory",
1731
[["graphs.&lt;tab&gt;", "#graphs"],
1732
["Petersen Graph", "#petersen", "Define the Peterson graph"]
1733
["Random Graph", "#random_graph"]
1734
['Invariants'],
1735
["Automorphism Group", "#auto_group_graph", "Automorphism group of a graph"]
1736
["Chromatic Number", "#chromatic_number", "Chromatic number of a graph"],
1737
['Visualization'],
1738
["2D Plot", "#graph_2dplot"],
1739
["3D Plot", "#graph_3dplot"]
1740
]]
1741
sage_nt = ["Number Theory", "Number Theory",
1742
[
1743
["Binary Quadratic Form", "#binary_quadform", "Define a binary quadratic form"],
1744
["Continued Fraction", "#contfrac", "Compute a continued fraction"],
1745
["Elliptic Curve", "#ellcurve", "Define an elliptic curve"],
1746
["Factor", "#factor", "Factorization of something"],
1747
["Mod $n$", "#mod", "Number modulo n"],
1748
["List Prime Numbers", "#primes", "Enumerate prime numbers"]
1749
["Count Prime Numbers", "#prime_pi", "Count prime numbers"]
1750
]]
1751
1752
sage_rings = ["Rings", "Rings and Fields",
1753
[
1754
["$\\CC$ - Complex Numbers", "#ring_CC"],
1755
["$\\QQ$ - Rational Numbers", "#ring_QQ"],
1756
["$\\RR$ - Real Numbers", "#ring_RR"],
1757
["$\\ZZ$ - Integers", "#ring_ZZ"],
1758
["Polynomial Rings"],
1759
["$\\QQ[x, y, z]$", "#ring_QQxyz"],
1760
["$\\QQ[x, y]/(y^2-x^3-x)$", "#ring_QQ_quo"],
1761
["$\\ZZ[x_2, x_3, \\ldots, x_{97}]$", "#ring_ZZxp"],
1762
["Advanced Rings"],
1763
["$\\mathbb{A}$ - Algebraic Reals", "#ring_AA"],
1764
["$\\CDF$ - Complex Double", "#ring_CDF"],
1765
["$\\CC$ - Complex Interval", "#ring_CIF"],
1766
["$\\CLF$ - Complex Lazy", "#ring_CLF"],
1767
["$\\FF_p$ - Prime Finite Field", "#ring_FF_p"],
1768
["$\\FF_{p^r}$ - Finite Field", "#ring_FF_pr"],
1769
["$\\overline{\\QQ}$ - Algebraic Closure", "#ring_QQbar"],
1770
["$\\QQ_p$ - $p$-adic Numbers", "#ring_QQp"],
1771
["$\\RDF$ - Real Double", "#ring_RDF"],
1772
["$\\RR$ - Real Interval", "#ring_RIF"],
1773
["$\\RLF$ - Real Lazy", "#ring_RLF"],
1774
["$\\ZZ_p$ - $p$-adic Integers", "#ring_ZZp"],
1775
]]
1776
1777
add_icon(sagebar, "$x$", "#var", "Define a symbolic variable", true)
1778
add_menu(sagebar, sage_plotting)
1779
add_menu(sagebar, sage_calculus)
1780
add_menu(sagebar, sage_linalg)
1781
add_menu(sagebar, sage_graphs)
1782
add_menu(sagebar, sage_nt)
1783
add_menu(sagebar, sage_rings)
1784
1785
codebar.append(sagebar)
1786
1787
# -- r specific --
1788
rbar = $(".webapp-editor-redit-buttonbar")
1789
1790
r_basic = make_bar()
1791
add_icon(r_basic, "<i class='fa'>#</i>", "#comment", "Comment selected text")
1792
add_icon(r_basic, "$\\vec v$", "#vector", "Insert a vector")
1793
1794
r_control = make_bar()
1795
r_control_entries = ["Control", "Control Structures",
1796
[
1797
["Assignment", "#assign", "Give an object a (variable)name"],
1798
["For-Loop", "#forloop", "Insert a for loop"],
1799
["Function definition", "#function", "Define a function"],
1800
["If-Else", "#ifelse"]
1801
]]
1802
add_menu(r_control, r_control_entries)
1803
1804
r_data = make_bar()
1805
r_bar_entries = ["Data", "Data structures",
1806
[
1807
["List, indexed", "#list1"],
1808
["List, associative", "#list2"],
1809
["Array selection", "#arrayselect"]
1810
["Data Frame", "#dataframe"],
1811
["Attach", "#attach"]
1812
]]
1813
1814
r_funcs = make_bar()
1815
r_funcs_entries = ["Functions", "Some selected functions",
1816
[
1817
["Sequence Simple", "#seq"]
1818
["Sequence Stepsize", "#seq_by"],
1819
["Sequence Length", "#seq_length"],
1820
["Repetitions (times)", "rep1"],
1821
["Repetitions (each)", "rep2"],
1822
["Character Vector", "#charvec"],
1823
["Matrix array", "#matrix"],
1824
["Matrix multipliation", "#matrixmult"]
1825
["Outer product", "#outer"],
1826
["Inverse matrix", "#inverse"],
1827
["Solve A*x=b", "#solvelin"],
1828
["SVD", "#svd"]
1829
]]
1830
1831
r_stats = make_bar()
1832
r_stats_entries = ["Stats", "Basic Statistical Functions",
1833
[
1834
["Statistical summary", "#summary"],
1835
["Mean", "#mean"],
1836
["Normal Distribution", "#normal"],
1837
["Linear Model", "#lm"],
1838
["Nonlinear Model", "#nlm"]
1839
]]
1840
add_menu(r_stats, r_stats_entries)
1841
1842
r_plot = make_bar()
1843
r_plot_entries = ["Plots", "Basic Plots",
1844
[
1845
["Plot x/y pairs", "#plot"],
1846
["Stem Plot", "#stem"],
1847
["Histogram + Density + Rug", "#histdensity"],
1848
["QQ-Plot", "#qqplot", "Quantile-quantile plot"],
1849
["Boxplot", "#boxplot"],
1850
["Contour Plot", "#contour"]
1851
["Change default plot size", "#defaultsize"]
1852
]]
1853
add_menu(r_plot, r_plot_entries)
1854
1855
rbar.append(r_basic)
1856
rbar.append(r_control)
1857
rbar.append(r_stats)
1858
rbar.append(r_plot)
1859
1860
# -- Julia specific --
1861
julia_bar = $(".webapp-editor-julia-edit-buttonbar")
1862
1863
julia_basic = make_bar()
1864
add_icon(julia_basic, "<i class='fa'>#</i>", "#comment", "Comment selected text")
1865
1866
julia_control = make_bar()
1867
julia_control_entries = ["Control", "Control Structures",
1868
[
1869
["Assignment", "#assign", "Give an object a (variable)name"],
1870
["For-Loop", "#forloop", "Insert a for loop"],
1871
["Function definition", "#function", "Define a function"],
1872
["If-Else", "#ifelse"]
1873
]]
1874
add_menu(julia_control, julia_control_entries)
1875
julia_bar.append(julia_basic)
1876
julia_bar.append(julia_control)
1877
1878
# -- sh specific --
1879
sh_bar = $(".webapp-editor-sh-edit-buttonbar")
1880
1881
sh_git = make_bar()
1882
sh_git_entries = ["Git", "Basic Git commands",
1883
[
1884
["Set name and email", "#set_name_and_email", "Set name and email"],
1885
["Initalize Git", "#initalize_git", "Initalize Git"],
1886
["Create an ignore file", "#create_gitignore", "Create an ignore file"],
1887
["Clone a local repo", "#clone_local_repo", "Clone local repo"],
1888
["Clone a remote repo", "#clone_remote_repo", "Clone remote repo"],
1889
["Add a file to repo", "#add_file_to_repo", "Add file to the repo"],
1890
["Add all files to repo", "#add_all_to_repo", "Add all not ignored files to the repo"],
1891
["See changes before committing", "#diff", "See changes before committing"],
1892
["Commit your changes", "#commit", "Commit all your changes"],
1893
["Setup SSH for Github", "#setup_ssh_for_github", "Setup SSH for Github"],
1894
["Push changes", "#push_origin_master", "Push changes to the master branch of your remote repository"],
1895
["Status", "#status", "Status"],
1896
["Add remote repo", "#add_remote_repo", "Connect to a remote repository"],
1897
["List remote repos", "#list_remote_repos", "List all currently configured remote repositories"],
1898
["Create a new branch", "#create_new_branch", "Create a new branch and switch to it"],
1899
["Switch branches", "#switch_branches", "Switch from one branch to another"],
1900
["List branches", "#list_branches", "List all the branches in your repo, and also tell you what branch you're currently in"],
1901
["Delete the feature branch", "#delete_the_feature_branch", "Delete the feature branch"],
1902
["Push branch", "#push_branch", "Push the branch to your remote repository, so others can use it"],
1903
["Push all branches", "#push_all_branches", "Push all branches to your remote repository"],
1904
["Delete remote branch", "#delete_remote_branch", "Delete a branch on your remote repository"],
1905
["Update repo", "#pull", "Update from the remote repository Fetch and merge changes on the remote server to your working directory"],
1906
["Merge a branch", "#merge_branch", "To merge a different branch into your active branch"],
1907
["Show history", "#show_history", "Show the history of previous commits"],
1908
["Undo local changes", "#undo_local_changes", "Undo local changes"],
1909
["Get rid of local changes", "#get_rid_of_local_changes", "Drop all your local changes and commits, fetch the latest history from the server and point your local master branch at it"],
1910
["Search the working directory for foo()", "#search_for", "Search the working directory for foo()"]
1911
]]
1912
add_menu(sh_git, sh_git_entries)
1913
sh_bar.append(sh_git)
1914
1915
1916
initialize_latex_buttonbar = () ->
1917
latexbar = make_bar()
1918
add_icon(latexbar, "<i class='fa fa-comment'></i>", "#comment", "Comment selected text")
1919
1920
templates = ["Templates", "These templates come exclusively on top",
1921
[
1922
["Article", "#article"],
1923
["KOMA Script"],
1924
["Article", "#scrartcl"],
1925
["Report", "#scrreprt"]
1926
]]
1927
add_menu(latexbar, templates)
1928
1929
# FUTURE: merge this with the usual text formatting toolbar, such that its list of actions is inserted here
1930
# IDEA: maybe, clicking on the "Format" dropdown shows the cloned formatting toolbar?
1931
#text = ["Format", "Text formatting",[]]
1932
#add_menu(latexbar, text)
1933
formatting = $("<span class='btn-group'></span>")
1934
formatting.append($("""
1935
<span class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Text Formatting">
1936
<i class="fa">Format</i> <b class="caret"></b>
1937
</span>
1938
"""))
1939
format_buttons = $(".webapp-editor-codemirror-worksheet-editable-buttons").clone()
1940
format_buttons.addClass("dropdown-menu")
1941
format_buttons.removeClass("hide")
1942
format_buttons.css("min-width", 300)
1943
formatting.append(format_buttons)
1944
latexbar.append(formatting)
1945
# end format button idea
1946
1947
formulas = ["Formula", "These are some standard formuas",
1948
[
1949
["$x^2$", "#xsquare"],
1950
["$\\int$", "#integral"],
1951
["Environment"],
1952
["Cases", "#cases"]
1953
]]
1954
add_menu(latexbar, formulas)
1955
1956
bb = $(".webapp-editor-latex-buttonbar")
1957
bb.append(latexbar)
1958
1959
# NOT READY YET.
1960
#initialize_latex_buttonbar()
1961
1962
# used in entry-point
1963
exports.init_buttonbars = ->
1964
initialize_sagews_editor()
1965
initialize_md_html_editor()
1966
initialize_sage_python_r_toolbar()
1967
1968