├── tests ├── errors │ ├── modules │ │ └── __init__.py │ └── py_collision.py ├── modules │ ├── modules │ │ ├── __init__.py │ │ ├── submodules │ │ │ ├── __init__.py │ │ │ ├── module_name.py │ │ │ └── diamondbase.py │ │ ├── module_name.py │ │ ├── diamond1.py │ │ ├── diamond2.py │ │ ├── moda.py │ │ └── klasses.py │ ├── imported │ │ ├── __init__.py │ │ ├── submodules │ │ │ ├── __init__.py │ │ │ └── submodulea.py │ │ ├── alias_fns.py │ │ ├── modulee.py │ │ ├── modulec.py │ │ ├── moduled.py │ │ ├── alias_classes.py │ │ ├── modulea.py │ │ └── moduleb.py │ ├── children │ │ ├── fuga.py │ │ ├── hoge.py │ │ ├── grandchildren │ │ │ └── foo.py │ │ ├── bar.py │ │ └── __init__.py │ ├── module_name.py │ ├── classname.py │ ├── import_multi.py │ ├── import_diamond.py │ ├── import_global.py │ ├── import_class.py │ ├── import_init.py │ ├── import_alias.py │ ├── from_import.py │ ├── import_as_module.py │ ├── from_import_as_module.py │ ├── import.py │ └── rng.py ├── os │ ├── testdir │ │ ├── test_file1.txt │ │ ├── test_file2.txt │ │ └── test_child_dir │ │ │ ├── test_child_file1.txt │ │ │ └── test_child_file2.txt │ ├── path_dirname.py │ ├── path_join.py │ ├── path_basename.py │ └── walk.py ├── decorator │ ├── function3.rb.expected_in_out │ ├── decorator.rb.expected_in_out │ ├── function1.rb.expected_out │ ├── function2.rb.expected_out │ ├── property.py │ ├── setter.py │ ├── function2.py │ ├── function1.py │ ├── function3.py │ ├── decorator.py │ └── class.py ├── functions │ ├── uminus.py │ ├── uplus.py │ ├── ubitcomp.py │ ├── int.py │ ├── float.py │ ├── len.py │ ├── pop.py │ ├── bitxor.py │ ├── lshift.py │ ├── bitand.py │ ├── bitor.py │ ├── rshift.py │ ├── divfloor.py │ ├── floatdiv.py │ ├── str.py │ ├── sort.py │ ├── append.py │ ├── ne.py │ ├── sort_cmp.py │ ├── in.py │ ├── or.py │ ├── and.py │ ├── aug.py │ ├── sort23.py │ ├── gtge.py │ ├── ltle.py │ └── isinstance.py ├── basic │ ├── ifelse.py │ ├── print.py │ ├── for_range1.py │ ├── multiassign.py │ ├── for_step.py │ ├── helloworld.py │ ├── lambda2.py │ ├── sumcomp.py │ ├── globalvar.py │ ├── lambda3.py │ ├── augassign.py │ ├── class3.py │ ├── lambda.py │ ├── str_endswith.py │ ├── continue.py │ ├── float2int.py │ ├── for_range2.py │ ├── break.py │ ├── none.py │ ├── del_array.py │ ├── dictcomp1.py │ ├── list.py │ ├── del_slice.py │ ├── literals.py │ ├── scope.py │ ├── dictcomp2.py │ ├── del_local.py │ ├── dictionary.py │ ├── fib.py │ ├── logicalops.py │ ├── keys.py │ ├── listcomp2.py │ ├── trueorfalse.py │ ├── class5.py │ ├── pass.py │ ├── default.py │ ├── lambda_map.py │ ├── tuple2.rb.expected_out │ ├── class4.py │ ├── del_global.py │ ├── yield.py │ ├── closure.py │ ├── vargs.py │ ├── with.py │ ├── binaryops.py │ ├── embedding.py │ ├── listcomp1.py │ ├── kwargs3.py │ ├── dictionary3.py │ ├── numeric.py │ ├── class6.py │ ├── list3.py │ ├── vars.py │ ├── oo_static_inherit.py │ ├── assign.py │ ├── loops.py │ ├── oo_static_inherit2.py │ ├── valueerror.py │ ├── closure_in_class.py │ ├── raise.py │ ├── docstring.py │ ├── nestedclass.py │ ├── assign_slice.py │ ├── assert.py │ ├── kwargs.py │ ├── set.py │ ├── dictionary2.py │ ├── getattr.py │ ├── while.py │ ├── oo_super.py │ ├── class.py │ ├── kwargs2.py │ ├── vars2.py │ ├── hasattr2.py │ ├── oo_attributes.py │ ├── tuple.py │ ├── class2.py │ ├── del_dict.py │ ├── oo_inherit2.py │ ├── str1.py │ ├── ifs2.py │ ├── generator.py │ ├── oo_inherit3.py │ ├── hasattr1.py │ ├── oo_diamond.py │ ├── raise2.py │ ├── for_in2.py │ ├── oo.py │ ├── del_attr.py │ ├── super1.py │ ├── try.py │ ├── augassign2.py │ ├── ifs.py │ ├── super2.py │ ├── oo_inherit.py │ ├── tuple2.py │ ├── oo_inherit_simple.py │ ├── oo_inherit_simple_super1.py │ ├── oo_inherit_simple_super3.py │ ├── oo_inherit_simple_super2.py │ ├── for_in.py │ └── list2.py ├── lists │ ├── reverse.py │ ├── max.py │ ├── min.py │ ├── xrange.py │ ├── sum.py │ ├── sum2.py │ ├── filter.py │ ├── map.py │ ├── extend.py │ ├── reduce.py │ ├── zip.py │ ├── insert.py │ ├── subclass.py │ ├── in.py │ ├── all.py │ ├── any.py │ ├── subclass3.py │ └── subclass2.py ├── numpy │ ├── ellipsis.py │ ├── random_rand.py │ ├── random_random.py │ ├── linspace.py │ ├── ndarray.py │ ├── ndarray3.py │ ├── ndarray2.py │ ├── sum.py │ ├── type.rb.expected_out │ ├── array2string.rb.expected_out │ ├── special_values.py │ ├── type.py │ ├── np_copy.py │ ├── full.py │ ├── any.py │ ├── all.py │ ├── empty.py │ ├── arange.py │ ├── sqrt.py │ ├── random_uniform.py │ ├── array2string.py │ ├── random_randint.py │ ├── asarray.py │ ├── maximum_minimum.py │ ├── product.py │ ├── like.py │ ├── abs.py │ ├── insert.py │ ├── not_like.py │ ├── trigonometric_funcitons.py │ ├── ext_slice.py │ ├── arg_max_min.py │ └── max_min.py ├── strings │ ├── other_strings.py │ ├── strings_in_strings.py │ ├── lstrip1.py │ ├── rstrip1.py │ ├── strip1.py │ ├── join.py │ ├── ulcase.py │ ├── replace.py │ ├── find.py │ ├── rfind.py │ ├── rstrip0.py │ ├── string_format_combined_simple.py │ ├── lstrip0.py │ ├── strip.py │ ├── splitlines.py │ ├── zipstring.py │ ├── string_format_s_simple.py │ ├── string_format_o.py │ ├── string_format_x.py │ ├── string_format_f_simple.py │ ├── count.py │ ├── split.py │ ├── replace2.py │ ├── string_format_i.py │ ├── string_format_d.py │ ├── string_format_u.py │ ├── string_format_d_simple.py │ └── string_format_efg.py ├── six │ ├── integer_types.py │ ├── moves.range.py │ ├── py23.py │ ├── itervalues.py │ └── iteritems.py ├── unittest │ ├── class.py │ ├── assertIn.rb.expected_in_out │ ├── assertIs.rb.expected_in_out │ ├── assertEqual.rb.expected_in_out │ ├── assertRaises.rb.expected_in_out │ ├── assertTrue.rb.expected_in_out │ ├── assertAlmostEqual.rb.expected_in_out │ ├── assertIsInstance.rb.expected_in_out │ ├── assertIs.py │ ├── assertTrue.py │ ├── assertIn.py │ ├── assertEqual.py │ ├── assertIsInstance.py │ ├── assertAlmostEqual.py │ └── assertRaises.py ├── deep-learning-from-scratch │ ├── and_gate.rb.expected_out │ ├── and_gate.py │ ├── sigmoid.py │ ├── relu.py │ ├── step_function.py │ └── LICENSE.md ├── random │ └── random_random.py ├── convert_tabs_spaces.py ├── algorithms │ ├── triangulation.rb.expected_out │ ├── sqrt.py │ └── triangulation.py ├── collections │ └── ordered_dict.py ├── libraries │ └── xmlwriter.py └── test_builtins.rb ├── py2rb ├── builtins │ ├── require.rb │ └── module.rb ├── modules │ ├── lib.yaml │ └── unittest.yaml └── formater.py ├── testtools ├── __init__.py ├── env_tests.py ├── known_to_fail.py ├── runner.py ├── tests.py ├── writer.py └── util.py ├── py2rb.py ├── .gitignore ├── .travis.yml ├── LICENSE ├── run_tests.py ├── setup.py ├── ast.txt ├── README.rst └── test_results.txt /tests/errors/modules/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/modules/modules/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/os/testdir/test_file1.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/os/testdir/test_file2.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/modules/imported/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/modules/imported/submodules/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/modules/modules/submodules/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/os/testdir/test_child_dir/test_child_file1.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/os/testdir/test_child_dir/test_child_file2.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/decorator/function3.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | ((world)) 2 | -------------------------------------------------------------------------------- /tests/functions/uminus.py: -------------------------------------------------------------------------------- 1 | 2 | x = -7623 3 | print(x) 4 | -------------------------------------------------------------------------------- /tests/functions/uplus.py: -------------------------------------------------------------------------------- 1 | 2 | x = +7623 3 | print(x) 4 | -------------------------------------------------------------------------------- /tests/basic/ifelse.py: -------------------------------------------------------------------------------- 1 | print("OK") if True else print("NG") 2 | -------------------------------------------------------------------------------- /tests/basic/print.py: -------------------------------------------------------------------------------- 1 | print(1.23, "foobar", -1, 'x') 2 | 3 | -------------------------------------------------------------------------------- /tests/functions/ubitcomp.py: -------------------------------------------------------------------------------- 1 | 2 | b = (~1 & 0xFFFF) 3 | print(b) 4 | -------------------------------------------------------------------------------- /tests/basic/for_range1.py: -------------------------------------------------------------------------------- 1 | 2 | for x in range(1,10): 3 | print(x) 4 | -------------------------------------------------------------------------------- /tests/basic/multiassign.py: -------------------------------------------------------------------------------- 1 | 2 | x,y,z = (1,2,3) 3 | 4 | print(x,y,z) 5 | -------------------------------------------------------------------------------- /tests/decorator/decorator.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | (hello) 2 | ((world)) 3 | -------------------------------------------------------------------------------- /tests/functions/int.py: -------------------------------------------------------------------------------- 1 | 2 | x = '123' 3 | y = int(x) 4 | print(y) 5 | -------------------------------------------------------------------------------- /tests/lists/reverse.py: -------------------------------------------------------------------------------- 1 | a = [1, 2, 3, 4] 2 | a.reverse() 3 | print(a) 4 | -------------------------------------------------------------------------------- /tests/basic/for_step.py: -------------------------------------------------------------------------------- 1 | 2 | for x in range(19,342,13): 3 | print(x) 4 | -------------------------------------------------------------------------------- /tests/basic/helloworld.py: -------------------------------------------------------------------------------- 1 | 2 | print('hello') 3 | print('hello world') 4 | -------------------------------------------------------------------------------- /tests/basic/lambda2.py: -------------------------------------------------------------------------------- 1 | l = lambda *x: print("%s %s %s" % x) 2 | l(1,2,3) 3 | -------------------------------------------------------------------------------- /tests/functions/float.py: -------------------------------------------------------------------------------- 1 | 2 | a = '123.456' 3 | b = float(a) 4 | print(b) 5 | -------------------------------------------------------------------------------- /tests/functions/len.py: -------------------------------------------------------------------------------- 1 | 2 | mylist = [1,2,3] 3 | 4 | print(len(mylist)) 5 | -------------------------------------------------------------------------------- /tests/functions/pop.py: -------------------------------------------------------------------------------- 1 | 2 | a = [1,2,3,4] 3 | 4 | print(a.pop()) 5 | 6 | -------------------------------------------------------------------------------- /tests/modules/children/fuga.py: -------------------------------------------------------------------------------- 1 | def hi(): 2 | print("Hi! I'm fuga.") 3 | -------------------------------------------------------------------------------- /tests/modules/children/hoge.py: -------------------------------------------------------------------------------- 1 | def hi(): 2 | print("Hi! I'm hoge.") 3 | -------------------------------------------------------------------------------- /tests/functions/bitxor.py: -------------------------------------------------------------------------------- 1 | x = 32213 2 | y = 98743 3 | z = x ^ y 4 | print(z) 5 | -------------------------------------------------------------------------------- /tests/functions/lshift.py: -------------------------------------------------------------------------------- 1 | 2 | x = 10 3 | y = x << 3 4 | x <<= 3 5 | print(x,y) 6 | -------------------------------------------------------------------------------- /tests/lists/max.py: -------------------------------------------------------------------------------- 1 | 2 | l = [4,7,3,4,2,1] 3 | 4 | v = max(l) 5 | 6 | print(v) 7 | -------------------------------------------------------------------------------- /tests/lists/min.py: -------------------------------------------------------------------------------- 1 | 2 | l = [4,7,3,4,2,1] 3 | 4 | v = min(l) 5 | 6 | print(v) 7 | -------------------------------------------------------------------------------- /tests/os/path_dirname.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | print(os.path.dirname(__file__)) 4 | -------------------------------------------------------------------------------- /tests/basic/sumcomp.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | x = sum(x*x for x in [2,3,4,5,6,7]) 4 | print(x) 5 | -------------------------------------------------------------------------------- /tests/functions/bitand.py: -------------------------------------------------------------------------------- 1 | 2 | x = 32424 3 | y = 1437 4 | z = x & y 5 | print(z) 6 | -------------------------------------------------------------------------------- /tests/functions/bitor.py: -------------------------------------------------------------------------------- 1 | 2 | x = 123215 3 | y = 3423 4 | z = x | y 5 | print(z) 6 | -------------------------------------------------------------------------------- /tests/functions/rshift.py: -------------------------------------------------------------------------------- 1 | 2 | x = 345 3 | y = x >> 7 4 | x >>= 7 5 | print(x,y) 6 | -------------------------------------------------------------------------------- /tests/lists/xrange.py: -------------------------------------------------------------------------------- 1 | 2 | xr = range(20,40) 3 | 4 | for x in xr: 5 | print(x) 6 | -------------------------------------------------------------------------------- /tests/modules/children/grandchildren/foo.py: -------------------------------------------------------------------------------- 1 | def hi(): 2 | print("Hi! I'm foo.") 3 | -------------------------------------------------------------------------------- /tests/os/path_join.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | print(os.path.join('foo/bar/', 'hoge.txt')) 4 | -------------------------------------------------------------------------------- /py2rb/builtins/require.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'module' 4 | 5 | -------------------------------------------------------------------------------- /tests/functions/divfloor.py: -------------------------------------------------------------------------------- 1 | 2 | x = 23423 3 | y = 213 4 | z = x // y 5 | 6 | print(z) 7 | -------------------------------------------------------------------------------- /tests/functions/floatdiv.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | a = 3 5 | b = 2 6 | c = a / b 7 | print(c) 8 | -------------------------------------------------------------------------------- /tests/os/path_basename.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | print(os.path.basename('foo/bar/hoge.txt')) 4 | -------------------------------------------------------------------------------- /tests/basic/globalvar.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a = "spam" 4 | b = "eggs" 5 | 6 | print(a) 7 | print(b) 8 | -------------------------------------------------------------------------------- /tests/decorator/function1.rb.expected_out: -------------------------------------------------------------------------------- 1 | decorating # 2 | (world) 3 | -------------------------------------------------------------------------------- /tests/decorator/function2.rb.expected_out: -------------------------------------------------------------------------------- 1 | decorating # 2 | (world) 3 | -------------------------------------------------------------------------------- /tests/modules/imported/alias_fns.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | print("this is foo") 4 | 5 | 6 | -------------------------------------------------------------------------------- /tests/numpy/ellipsis.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.array([1, 1, 1]) 4 | x[...] = 1 5 | -------------------------------------------------------------------------------- /tests/strings/other_strings.py: -------------------------------------------------------------------------------- 1 | # Test other strings: 2 | print("\\u0000") 3 | print(b"\\x00") 4 | -------------------------------------------------------------------------------- /testtools/__init__.py: -------------------------------------------------------------------------------- 1 | """Everything that is python and has to do with tests goes in here.""" 2 | -------------------------------------------------------------------------------- /tests/basic/lambda3.py: -------------------------------------------------------------------------------- 1 | a = 5 2 | def foo(x, y): 3 | x(y) 4 | 5 | foo(lambda x: print(a), a) 6 | -------------------------------------------------------------------------------- /tests/lists/sum.py: -------------------------------------------------------------------------------- 1 | 2 | s = [1,2,3,4,5] 3 | t = sum(s) 4 | u = sum([x*x for x in s]) 5 | print(t,u) 6 | -------------------------------------------------------------------------------- /tests/modules/modules/submodules/module_name.py: -------------------------------------------------------------------------------- 1 | 2 | print("3rd level module __name__:"+__name__) 3 | -------------------------------------------------------------------------------- /tests/numpy/random_rand.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.random.rand(3,3,3) 4 | print(x.ndim) 5 | -------------------------------------------------------------------------------- /tests/strings/strings_in_strings.py: -------------------------------------------------------------------------------- 1 | print(""""Hello World!" <- should 'mess' up '''thing'''?""") 2 | -------------------------------------------------------------------------------- /py2rb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import py2rb 3 | 4 | if __name__ == '__main__': 5 | py2rb.main() 6 | -------------------------------------------------------------------------------- /tests/numpy/random_random.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.random.random((3,3,3)) 4 | print(x.ndim) 5 | -------------------------------------------------------------------------------- /tests/basic/augassign.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1 3 | a += 1 4 | print(a) 5 | a += 3 6 | print(a) 7 | a -= 2 8 | print(a) 9 | -------------------------------------------------------------------------------- /tests/basic/class3.py: -------------------------------------------------------------------------------- 1 | class A(object): 2 | v = 1 3 | 4 | a = A() 5 | XX = A 6 | x = XX() 7 | print(x.v) 8 | -------------------------------------------------------------------------------- /tests/basic/lambda.py: -------------------------------------------------------------------------------- 1 | 2 | y = lambda x:x*x 3 | 4 | print(y(4)) 5 | 6 | print((lambda x,y:x*y)(4,2)) 7 | 8 | -------------------------------------------------------------------------------- /tests/basic/str_endswith.py: -------------------------------------------------------------------------------- 1 | if 'hoge.txt'.endswith('.txt'): 2 | print('OK') 3 | else: 4 | print('NG') 5 | -------------------------------------------------------------------------------- /tests/functions/str.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1 3 | b = str(a) 4 | c = 'x: ' + b 5 | print(a) 6 | print(b) 7 | print(c) 8 | -------------------------------------------------------------------------------- /tests/six/integer_types.py: -------------------------------------------------------------------------------- 1 | import six 2 | 3 | if type(1) in six.integer_types: 4 | print('Integer') 5 | 6 | -------------------------------------------------------------------------------- /tests/unittest/class.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class TestRunnable(unittest.TestCase): 4 | pass 5 | 6 | -------------------------------------------------------------------------------- /tests/functions/sort.py: -------------------------------------------------------------------------------- 1 | 2 | l = [3,2,1] 3 | 4 | l.sort() 5 | 6 | print(l[0]) 7 | print(l[1]) 8 | print(l[2]) 9 | -------------------------------------------------------------------------------- /tests/modules/module_name.py: -------------------------------------------------------------------------------- 1 | 2 | import modules.module_name 3 | 4 | print("1st level module __name__:"+__name__) 5 | -------------------------------------------------------------------------------- /tests/six/moves.range.py: -------------------------------------------------------------------------------- 1 | import six 2 | 3 | xr = six.moves.range(20,40) 4 | 5 | for x in xr: 6 | print(x) 7 | -------------------------------------------------------------------------------- /tests/basic/continue.py: -------------------------------------------------------------------------------- 1 | 2 | for x in range(0,20): 3 | if x > 10 and x < 17: 4 | continue 5 | print(x) 6 | -------------------------------------------------------------------------------- /tests/basic/float2int.py: -------------------------------------------------------------------------------- 1 | 2 | for f in [123.456,1.1,-0.00045,-1.45,1.5,1022423.22]: 3 | i = int(f) 4 | print(i) 5 | -------------------------------------------------------------------------------- /tests/basic/for_range2.py: -------------------------------------------------------------------------------- 1 | for i in range(5): 2 | for j in range(i+1, 5): 3 | print("i:%s, j:%s" % (i,j)) 4 | -------------------------------------------------------------------------------- /tests/deep-learning-from-scratch/and_gate.rb.expected_out: -------------------------------------------------------------------------------- 1 | [0, 0] -> 0 2 | [1, 0] -> 0 3 | [0, 1] -> 0 4 | [1, 1] -> 1 5 | -------------------------------------------------------------------------------- /tests/lists/sum2.py: -------------------------------------------------------------------------------- 1 | s = [1,2,3,4,5] 2 | print(sum(s)) 3 | 4 | print(sum([1, 8, 11])) 5 | 6 | print(sum((1, 8, 11))) 7 | -------------------------------------------------------------------------------- /tests/modules/children/bar.py: -------------------------------------------------------------------------------- 1 | class bar_class(): 2 | def hi(self): 3 | print("Hi! I'm bar object.") 4 | 5 | -------------------------------------------------------------------------------- /tests/six/py23.py: -------------------------------------------------------------------------------- 1 | import six 2 | 3 | if six.PY2: 4 | print('Python 2') 5 | elif six.PY3: 6 | print('Python 3') 7 | -------------------------------------------------------------------------------- /tests/basic/break.py: -------------------------------------------------------------------------------- 1 | 2 | x = 0 3 | 4 | while True: 5 | x = x + 1 6 | print(x) 7 | if x > 10: 8 | break 9 | -------------------------------------------------------------------------------- /tests/modules/imported/submodules/submodulea.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | print("imported.modules.submodules.modulea.foo()") 4 | -------------------------------------------------------------------------------- /tests/numpy/linspace.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.linspace(2.0, 3.0, num=5) 4 | for a in x: 5 | print(a) 6 | 7 | -------------------------------------------------------------------------------- /tests/six/itervalues.py: -------------------------------------------------------------------------------- 1 | import six 2 | 3 | foo = { 'a':'b' } 4 | 5 | for f in six.itervalues(foo): 6 | print(f) 7 | 8 | -------------------------------------------------------------------------------- /tests/strings/lstrip1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = "abcxyz" 4 | 5 | print("original("+s+")") 6 | print("strip("+s.lstrip("cba")+")") 7 | -------------------------------------------------------------------------------- /tests/strings/rstrip1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = "abcxyz" 4 | 5 | print("original("+s+")") 6 | print("strip("+s.rstrip("yzx")+")") 7 | -------------------------------------------------------------------------------- /tests/strings/strip1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = "yxabcxyz" 4 | 5 | print("original("+s+")") 6 | print("strip("+s.strip("yzx")+")") 7 | -------------------------------------------------------------------------------- /tests/unittest/assertIn.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | 1 tests, 1 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 2 | -------------------------------------------------------------------------------- /tests/unittest/assertIs.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | 1 tests, 1 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 2 | -------------------------------------------------------------------------------- /tests/basic/none.py: -------------------------------------------------------------------------------- 1 | 2 | x = None 3 | 4 | if x == None: 5 | print("x is None/null") 6 | else: 7 | print("x is not None/null") 8 | -------------------------------------------------------------------------------- /tests/modules/children/__init__.py: -------------------------------------------------------------------------------- 1 | from . import fuga 2 | from . import hoge 3 | from . import bar 4 | from .grandchildren import foo 5 | -------------------------------------------------------------------------------- /tests/strings/join.py: -------------------------------------------------------------------------------- 1 | a = ["a", "b", "c"] 2 | print("".join(a)) 3 | print(" ".join(a)) 4 | print("x".join(a)) 5 | print("x ".join(a)) 6 | -------------------------------------------------------------------------------- /tests/unittest/assertEqual.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | 1 tests, 1 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 2 | -------------------------------------------------------------------------------- /tests/unittest/assertRaises.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | 2 tests, 12 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 2 | -------------------------------------------------------------------------------- /tests/unittest/assertTrue.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | 1 tests, 1 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 2 | -------------------------------------------------------------------------------- /tests/basic/del_array.py: -------------------------------------------------------------------------------- 1 | 2 | mylist = [1,2,3,4,5] 3 | 4 | del mylist[3] 5 | 6 | for x in range(0,len(mylist)): 7 | print(mylist[x]) 8 | -------------------------------------------------------------------------------- /tests/basic/dictcomp1.py: -------------------------------------------------------------------------------- 1 | foo = {key.upper(): data * 2 for key, data in {'a': 7, 'b': 5}.items()} 2 | print(foo['A']) 3 | print(foo['B']) 4 | -------------------------------------------------------------------------------- /tests/basic/list.py: -------------------------------------------------------------------------------- 1 | 2 | x = [1,2,3,'a','b','c'] 3 | y = x[2:4] 4 | print((x[0])) 5 | print((x[3])) 6 | print((y[0])) 7 | print((y[1])) 8 | -------------------------------------------------------------------------------- /tests/modules/modules/module_name.py: -------------------------------------------------------------------------------- 1 | 2 | from modules.submodules import module_name 3 | 4 | print("2nd level module __name__:"+__name__) 5 | -------------------------------------------------------------------------------- /tests/strings/ulcase.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | s = "aBcddEzUh" 4 | 5 | print(s) 6 | s = s.upper() 7 | print(s) 8 | s = s.lower() 9 | print(s) 10 | -------------------------------------------------------------------------------- /tests/unittest/assertAlmostEqual.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | 1 tests, 3 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 2 | -------------------------------------------------------------------------------- /tests/unittest/assertIsInstance.rb.expected_in_out: -------------------------------------------------------------------------------- 1 | 1 tests, 2 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications 2 | -------------------------------------------------------------------------------- /tests/basic/del_slice.py: -------------------------------------------------------------------------------- 1 | 2 | mylist = [1,2,3,4,5] 3 | 4 | del mylist[1:3] 5 | 6 | for x in range(0,len(mylist)): 7 | print(mylist[x]) 8 | -------------------------------------------------------------------------------- /tests/basic/literals.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.234 3 | b = 3 4 | c = 3.45 5 | d = 'cats' 6 | 7 | print(a) 8 | print(b) 9 | print(c) 10 | print(d) 11 | -------------------------------------------------------------------------------- /tests/basic/scope.py: -------------------------------------------------------------------------------- 1 | 2 | x = 12 3 | 4 | def loopy(): 5 | for x in range(0,8): 6 | print(x) 7 | 8 | loopy() 9 | print(x) 10 | -------------------------------------------------------------------------------- /tests/basic/dictcomp2.py: -------------------------------------------------------------------------------- 1 | foo = {key.upper(): data * 2 for key, data in {'a': 7, 'b': 5}.items() if data > 6} 2 | print(len(foo)) 3 | print(foo['A']) 4 | -------------------------------------------------------------------------------- /tests/lists/filter.py: -------------------------------------------------------------------------------- 1 | 2 | l = [1,2,3,4,5,6,7,8,8] 3 | 4 | l2 = [x for x in l if x>4] 5 | 6 | for v in l2: 7 | print(v) 8 | 9 | 10 | -------------------------------------------------------------------------------- /tests/modules/classname.py: -------------------------------------------------------------------------------- 1 | 2 | from modules.moda import ModA 3 | 4 | m = ModA('hello') 5 | m.describe() 6 | 7 | mc = m.clone() 8 | mc.describe() 9 | -------------------------------------------------------------------------------- /tests/modules/import_multi.py: -------------------------------------------------------------------------------- 1 | 2 | import imported.modulec 3 | 4 | def foo(): 5 | print("foo") 6 | imported.modulec.foo() 7 | 8 | foo() 9 | -------------------------------------------------------------------------------- /tests/random/random_random.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | x = random.random() 4 | 5 | if 0 < x < 1: 6 | print("OK") 7 | else: 8 | print("NG") 9 | -------------------------------------------------------------------------------- /tests/basic/del_local.py: -------------------------------------------------------------------------------- 1 | 2 | x = "ABC" 3 | 4 | print(x) 5 | 6 | del x 7 | 8 | try: 9 | print(x) 10 | except: 11 | print("x is gone") 12 | -------------------------------------------------------------------------------- /tests/basic/dictionary.py: -------------------------------------------------------------------------------- 1 | 2 | foo = { 'a':'b', 'c':'d' } 3 | 4 | print(foo['a']) 5 | print(foo['c']) 6 | 7 | if 'a' in foo: 8 | print("a in foo") 9 | -------------------------------------------------------------------------------- /tests/modules/import_diamond.py: -------------------------------------------------------------------------------- 1 | 2 | import modules.diamond1 3 | import modules.diamond2 4 | 5 | modules.diamond1.run() 6 | modules.diamond2.run() 7 | 8 | -------------------------------------------------------------------------------- /tests/lists/map.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(x): 3 | return x*x 4 | 5 | y = [1,2,3,4,5] 6 | 7 | z = list(map(foo,y)) 8 | for val in z: 9 | print(val) 10 | -------------------------------------------------------------------------------- /tests/basic/fib.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def fib(x): 5 | if x == 1: 6 | return x 7 | else: 8 | return x*fib(x-1) 9 | 10 | print(fib(4)) 11 | -------------------------------------------------------------------------------- /tests/modules/import_global.py: -------------------------------------------------------------------------------- 1 | 2 | import imported.moduleb 3 | import imported.moduled 4 | 5 | imported.moduleb.moduleb_fn() 6 | imported.moduled.moduled_fn() 7 | -------------------------------------------------------------------------------- /tests/modules/imported/modulee.py: -------------------------------------------------------------------------------- 1 | from imported.submodules import submodulea 2 | 3 | def bar(): 4 | print("imported.modulee.bar()") 5 | submodulea.foo() 6 | -------------------------------------------------------------------------------- /tests/strings/replace.py: -------------------------------------------------------------------------------- 1 | 2 | txt = "the quick brown fox jumped over thethe lazy dog" 3 | 4 | txt2 = txt.replace("the","a") 5 | 6 | print(txt) 7 | print(txt2) 8 | -------------------------------------------------------------------------------- /tests/modules/modules/diamond1.py: -------------------------------------------------------------------------------- 1 | 2 | from modules.submodules import diamondbase 3 | 4 | def run(): 5 | print("calling diamond1.run()") 6 | diamondbase.run() 7 | -------------------------------------------------------------------------------- /tests/modules/modules/diamond2.py: -------------------------------------------------------------------------------- 1 | 2 | from modules.submodules import diamondbase 3 | 4 | def run(): 5 | print("Calling diamond2.run()") 6 | diamondbase.run() 7 | -------------------------------------------------------------------------------- /tests/basic/logicalops.py: -------------------------------------------------------------------------------- 1 | 2 | x = True 3 | y = False 4 | z = not y 5 | 6 | if x: 7 | print('x') 8 | if y: 9 | print('y') 10 | if z: 11 | print('z') 12 | -------------------------------------------------------------------------------- /tests/modules/import_class.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import modules.klasses 4 | 5 | k = modules.klasses.Klass() 6 | 7 | k.sayhello() 8 | modules.klasses.Klass.sayhello() 9 | 10 | -------------------------------------------------------------------------------- /tests/strings/find.py: -------------------------------------------------------------------------------- 1 | 2 | s = "the quick brown fox" 3 | i = s.find("quick") 4 | print(str(i)) 5 | i = s.find("dog") 6 | print(str(i)) 7 | i = s.find("the") 8 | print(str(i)) 9 | -------------------------------------------------------------------------------- /tests/basic/keys.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | x = { 'foo':'bar','aaa':'bbb','xyz':'zyx','spam':'eggs' } 4 | 5 | s = list(x.keys()) 6 | s.sort() 7 | for k in s: 8 | print(k + " -> " + x[k]) 9 | -------------------------------------------------------------------------------- /tests/lists/extend.py: -------------------------------------------------------------------------------- 1 | 2 | list1 = [1,2,'f',44] 3 | list2 = ['a',99,77] 4 | 5 | list3 = list1[:] 6 | list3.extend(list2) 7 | 8 | for item in list3: 9 | print(item) 10 | -------------------------------------------------------------------------------- /tests/modules/import_init.py: -------------------------------------------------------------------------------- 1 | import children 2 | children.fuga.hi() 3 | children.hoge.hi() 4 | b = children.bar.bar_class() 5 | b.hi() 6 | children.grandchildren.foo.hi() 7 | 8 | -------------------------------------------------------------------------------- /tests/numpy/ndarray.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | a = np.array([1,2,3,4,5], dtype='int8') 4 | if isinstance(a, np.ndarray): 5 | print('OK') 6 | else: 7 | print('NG') 8 | 9 | -------------------------------------------------------------------------------- /tests/numpy/ndarray3.py: -------------------------------------------------------------------------------- 1 | from numpy import * 2 | 3 | a = array([1,2,3,4,5], dtype='int8') 4 | if isinstance(a, ndarray): 5 | print('OK') 6 | else: 7 | print('NG') 8 | 9 | -------------------------------------------------------------------------------- /tests/basic/listcomp2.py: -------------------------------------------------------------------------------- 1 | 2 | for (x,y,z) in [(x,y,z) for x in range(0,3) for y in range(0,4) for z in range(0,5)]: 3 | if x < y < z: 4 | print(x,y,z,"x "+str(y)) 8 | else: 9 | print("not: " + str(x)+" <> "+str(y)) 10 | 11 | 12 | -------------------------------------------------------------------------------- /tests/functions/sort_cmp.py: -------------------------------------------------------------------------------- 1 | 2 | def revcmp(a,b): 3 | if b np.nan: # False 10 | print("True") 11 | else: 12 | print("False") 13 | print(str(np.nan - np.nan).lower()) 14 | -------------------------------------------------------------------------------- /tests/numpy/type.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | print(np.int8) 5 | print(np.int16) 6 | print(np.int32) 7 | print(np.int64) 8 | print(np.int) 9 | print(np.uint8) 10 | print(np.uint16) 11 | print(np.uint32) 12 | print(np.uint64) 13 | print(np.uint) 14 | print(np.float32) 15 | print(np.float64) 16 | -------------------------------------------------------------------------------- /tests/basic/assign_slice.py: -------------------------------------------------------------------------------- 1 | 2 | a = [1,2,3,4,5,6,7] 3 | 4 | a[4:6] = ['a','b'] 5 | 6 | #def show(x): 7 | def show(a): 8 | print("----") 9 | for x in a: 10 | print(x) 11 | 12 | show(a) 13 | 14 | 15 | a[2:4] = ['z'] 16 | 17 | show(a) 18 | 19 | a[0:2] = ['abc','def','abc','def'] 20 | 21 | show(a) 22 | -------------------------------------------------------------------------------- /tests/modules/imported/moduleb.py: -------------------------------------------------------------------------------- 1 | 2 | def foo(): 3 | print("foo") 4 | 5 | def moduleb_fn(): 6 | print("import_moduleb.moduleb_fn()") 7 | 8 | class moduleb_class(object): 9 | 10 | def __init__(self): 11 | pass 12 | 13 | def msg(self,val): 14 | return "moduleb_class:"+str(val) 15 | -------------------------------------------------------------------------------- /tests/numpy/np_copy.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def print_array(data): 4 | datas = [] 5 | for i in data: 6 | datas.append(i) 7 | print(datas) 8 | 9 | x = np.array([1, 2, 3]) 10 | print_array(x) 11 | y = np.copy(x) 12 | print_array(y) 13 | x[0] = 10 14 | print_array(x) 15 | print_array(y) 16 | 17 | -------------------------------------------------------------------------------- /tests/os/walk.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | for dirpath, dirnames, filenames in os.walk('tests/os/testdir'): 4 | print('') 5 | print(dirpath) 6 | print('') 7 | for dirname in dirnames: 8 | print(dirname) 9 | print('') 10 | for filename in filenames: 11 | print(filename) 12 | -------------------------------------------------------------------------------- /tests/basic/assert.py: -------------------------------------------------------------------------------- 1 | try: 2 | assert True, "no message" 3 | except AssertionError as err: 4 | print('AssertionError :', err) 5 | except: 6 | print('Error :') 7 | 8 | try: 9 | assert False, "error message" 10 | except AssertionError as err: 11 | print('AssertionError :', err) 12 | except: 13 | print('Error :') 14 | -------------------------------------------------------------------------------- /tests/basic/kwargs.py: -------------------------------------------------------------------------------- 1 | def myfunc(a, b, *c, **d): 2 | print(a) 3 | print(b) 4 | for i in c: 5 | print(i) 6 | keys = list(d.keys()) 7 | keys.sort() 8 | for i in keys: 9 | print(i) 10 | print(d[i]) 11 | 12 | myfunc(1, 2, bar='a', foo='c') 13 | print() 14 | myfunc(1, 2, 3, 4, bar='a', foo='c') 15 | -------------------------------------------------------------------------------- /tests/lists/in.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | l = ['a','b','c'] 4 | 5 | def intest(item,ll): 6 | if item in ll: 7 | print(str(item) + ' is in list') 8 | else: 9 | print(str(item) + ' is not in list') 10 | 11 | 12 | intest('a',l) 13 | intest('b',l) 14 | intest(99,l) 15 | intest(0,l) 16 | intest('z',l) 17 | intest('c',l) 18 | 19 | 20 | -------------------------------------------------------------------------------- /tests/basic/set.py: -------------------------------------------------------------------------------- 1 | # iterating over a list 2 | print('-- set --') 3 | a = set([1,2,3,4,5]) 4 | a.remove(3) 5 | for x in a: 6 | print(x) 7 | 8 | print('-- set add --') 9 | a = set() 10 | a.add(1) 11 | a.add(2) 12 | a.add(1) 13 | for x in a: 14 | print(x) 15 | 16 | print('-- set clear --') 17 | 18 | a.clear() 19 | for x in a: 20 | print(x) 21 | -------------------------------------------------------------------------------- /tests/decorator/setter.py: -------------------------------------------------------------------------------- 1 | class propertyDecorator(object): 2 | def __init__(self, x): 3 | self._x = x 4 | 5 | @property 6 | def x(self): 7 | return self._x 8 | 9 | @x.setter 10 | def x(self, value): 11 | self._x = value 12 | 13 | pd = propertyDecorator(100) 14 | print(pd.x) 15 | pd.x = 10 16 | print(pd.x) 17 | 18 | -------------------------------------------------------------------------------- /tests/functions/in.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a = { 1:'aaa', 'b':2 } 4 | 5 | if 2 in a: 6 | print("2 in a - incorrect") 7 | 8 | if 'b' in a: 9 | print("b in a - correct") 10 | 11 | if 1 in a: 12 | print("1 in a - correct") 13 | 14 | if 3 not in a: 15 | print("3 not in a - correct") 16 | 17 | if 'x' not in a: 18 | print("x not in a - correct") 19 | -------------------------------------------------------------------------------- /tests/modules/modules/klasses.py: -------------------------------------------------------------------------------- 1 | 2 | class Baseklass(object): 3 | 4 | @staticmethod 5 | def sayhello(): 6 | print("baseklass says hello") 7 | 8 | class Klass(Baseklass): 9 | 10 | pass 11 | 12 | 13 | if __name__ == '__main__': 14 | 15 | k = Klass() 16 | k.sayhello() 17 | Klass.sayhello() 18 | Baseklass.sayhello() 19 | -------------------------------------------------------------------------------- /tests/strings/count.py: -------------------------------------------------------------------------------- 1 | 2 | txt = "the quick brown fox jumped over the lazy dogthe" 3 | 4 | c = txt.count("the") 5 | print(c) 6 | c = txt.count("the",0,-20) 7 | print(c) 8 | c = txt.count("the",3) 9 | print(c) 10 | c = txt.count("the",4,15) 11 | print(c) 12 | c = txt.count("the",1,len(txt)) 13 | print(c) 14 | c = txt.count("the",4,len(txt)-1) 15 | print(c) 16 | -------------------------------------------------------------------------------- /tests/strings/split.py: -------------------------------------------------------------------------------- 1 | 2 | s="the quick brown fox jumped over the lazy dog" 3 | t = s.split(" ") 4 | for v in t: 5 | print(v) 6 | r = s.split("e") 7 | for v in r: 8 | print(v) 9 | x = s.split() 10 | for v in x: 11 | print(v) 12 | 13 | # 2-arg version of split not supported 14 | # y = s.split(" ",7) 15 | # for v in y: 16 | # print v 17 | -------------------------------------------------------------------------------- /tests/algorithms/triangulation.rb.expected_out: -------------------------------------------------------------------------------- 1 | nodes [[0, 0], [1, 0], [1, 1], [0, 1]] 2 | edges [[0, 1], [1, 2], [2, 3], [3, 0]] 3 | elems [[3, 0, 1], [3, 1, 2]] 4 | ok 5 | 6 | nodes [[0, 0], [1, 0], [2, 1], [2, 2], [1, 2], [0.5, 1.5], [0, 1]] 7 | edges [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0]] 8 | elems [[5, 0, 1], [5, 1, 2], [5, 2, 4], [4, 2, 3]] 9 | ok 10 | -------------------------------------------------------------------------------- /tests/basic/dictionary2.py: -------------------------------------------------------------------------------- 1 | def dict1(): 2 | a = {1: 3, "s": 4} 3 | return len(a) 4 | 5 | def dict2(): 6 | a = {1: 3, "s": 4} 7 | b = a[1] + a["s"] 8 | return b 9 | 10 | def dict3(): 11 | a = {} 12 | a[1] = 3 13 | a["s"] = 4 14 | b = a[1] + a["s"] 15 | return b 16 | 17 | print(dict1()) 18 | print(dict2()) 19 | print(dict3()) 20 | -------------------------------------------------------------------------------- /tests/basic/getattr.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class foobar(object): 4 | 5 | x = 1 6 | 7 | def __init__(self): 8 | self.foovar = 1 9 | 10 | def bar(self, y=0): 11 | print(self.foovar + y) 12 | 13 | f = foobar() 14 | a = 'bar' 15 | 16 | getattr(f, 'bar')(y=1) 17 | getattr(f, a)() 18 | print(getattr(f, 'x')) 19 | print(getattr(f, 'z', 'Nothing')) 20 | -------------------------------------------------------------------------------- /tests/numpy/full.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_matrix(data): 5 | data_i = [] 6 | for i in list(data): 7 | data_j = [] 8 | for j in i: 9 | data_j.append(int("%d" % j)) 10 | data_i.append(data_j) 11 | print(data_i) 12 | 13 | x = np.full((2, 2), 5, dtype=np.int64) 14 | print_matrix(x) 15 | 16 | -------------------------------------------------------------------------------- /tests/functions/or.py: -------------------------------------------------------------------------------- 1 | 2 | tests = [(False,False),(False,True),(True,False),(True,True),(True,None),(False,None),(None,True),(None,False)] 3 | 4 | def pp(v): 5 | if v == False: 6 | return "F" 7 | if v == True: 8 | return "T" 9 | return "?" 10 | 11 | for t in tests: 12 | (b1,b2) = t 13 | print(pp(b1) + " OR " + pp(b2) + "=" + pp(b1 or b2)) 14 | -------------------------------------------------------------------------------- /tests/basic/while.py: -------------------------------------------------------------------------------- 1 | """ while case """ 2 | x = 1 3 | while x<10: 4 | print(x) 5 | x = x + 1 6 | 7 | """ while and else case """ 8 | x = 1 9 | while x<10: 10 | print(x) 11 | x = x + 1 12 | else: 13 | print("ok") 14 | """ while and else break case """ 15 | x = 1 16 | while x<10: 17 | print(x) 18 | x = x + 1 19 | break 20 | else: 21 | print("ok") 22 | -------------------------------------------------------------------------------- /tests/functions/and.py: -------------------------------------------------------------------------------- 1 | 2 | tests = [(False,False),(False,True),(True,False),(True,True),(True,None),(False,None),(None,True),(None,False)] 3 | 4 | def pp(v): 5 | if v == False: 6 | return "F" 7 | if v == True: 8 | return "T" 9 | return "?" 10 | 11 | for t in tests: 12 | (b1,b2) = t 13 | print(pp(b1) + " AND " + pp(b2) + "=" + pp(b1 and b2)) 14 | -------------------------------------------------------------------------------- /tests/decorator/function2.py: -------------------------------------------------------------------------------- 1 | 2 | class wrapper: 3 | 4 | def __init__(self,fn): 5 | self.fn = fn 6 | 7 | def __call__(self,*args): 8 | return "(" + self.fn(*args) + ")" 9 | 10 | def mydecorator(x): 11 | print("decorating " + str(x)) 12 | return wrapper(x) 13 | 14 | @mydecorator 15 | def describe(): 16 | return "world" 17 | 18 | print(describe()) 19 | -------------------------------------------------------------------------------- /tests/functions/aug.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | a = 244 4 | b = 23 5 | 6 | print(a) 7 | a += 4 8 | print(a) 9 | a -= 2 10 | print(a) 11 | a <<= 4 12 | print(a) 13 | a >>= 2 14 | print(a) 15 | a |= 234324 16 | print(a) 17 | a &= 213213 18 | print(a) 19 | a ^= 2312 20 | print(a) 21 | a //= 324 22 | print(a) 23 | a += 1 24 | print(a) 25 | a /= 2 26 | print(a) 27 | 28 | print(b) 29 | b **= 3 30 | print(b) 31 | -------------------------------------------------------------------------------- /tests/strings/replace2.py: -------------------------------------------------------------------------------- 1 | 2 | txt = "the quick brown fox jumped over thethe lazy dog" 3 | 4 | txt2 = txt.replace("the","a") 5 | 6 | print(txt) 7 | print(txt2) 8 | 9 | print(txt.replace("the", "a", 0)) 10 | print(txt.replace("the", "a", 1)) 11 | print(txt.replace("the", "a", 2)) 12 | print(txt.replace("the", "a", 3)) 13 | print(txt.replace("the", "a", 4)) 14 | print(txt.replace("the", "a", 50)) 15 | -------------------------------------------------------------------------------- /tests/decorator/function1.py: -------------------------------------------------------------------------------- 1 | 2 | class wrapper: 3 | 4 | def __init__(self,fn): 5 | self.fn = fn 6 | 7 | def __call__(self,*args): 8 | return "(" + self.fn(*args) + ")" 9 | 10 | def mydecorator(x): 11 | print("decorating " + str(x)) 12 | return wrapper(x) 13 | 14 | def describe(): 15 | return "world" 16 | describe = mydecorator(describe) 17 | 18 | print(describe()) 19 | -------------------------------------------------------------------------------- /tests/basic/oo_super.py: -------------------------------------------------------------------------------- 1 | class A(object): 2 | def met(self): 3 | print('A.met') 4 | class B(A): 5 | def met(self): 6 | print('B.met') 7 | super(B,self).met( ) 8 | class C(A): 9 | def met(self): 10 | print('C.met') 11 | super(C,self).met( ) 12 | class D(B,C): 13 | def met(self): 14 | print('D.met') 15 | super(D,self).met( ) 16 | 17 | D().met() 18 | -------------------------------------------------------------------------------- /tests/collections/ordered_dict.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | 4 | d = collections.OrderedDict({'one': 1, 'two':2, 'three':3}) 5 | print(d['one']) 6 | print(d['two']) 7 | print(d['three']) 8 | 9 | e = collections.OrderedDict(d) 10 | print(e['one']) 11 | print(e['two']) 12 | print(e['three']) 13 | #d = collections.OrderedDict(one=1, two=2, three=3) 14 | #print(d['one']) 15 | #print(d['two']) 16 | #print(d['three']) 17 | -------------------------------------------------------------------------------- /tests/decorator/function3.py: -------------------------------------------------------------------------------- 1 | 2 | class wrapper: 3 | 4 | def __init__(self,fn): 5 | self.fn = fn 6 | 7 | def __call__(self,*args): 8 | return "(" + self.fn(*args) + ")" 9 | 10 | def mydecorator(x): 11 | print("decorating " + str(x)) 12 | return wrapper(x) 13 | 14 | @mydecorator 15 | def describe(): 16 | return "world" 17 | describe = mydecorator(describe) 18 | 19 | print(describe()) 20 | -------------------------------------------------------------------------------- /tests/basic/class.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class foobar(object): 4 | 5 | x = 1 6 | 7 | def __init__(self): 8 | self.foovar = 1 9 | 10 | def foo(self,x): 11 | self.foovar = self.foovar + x 12 | 13 | def bar(self): 14 | print(self.foovar) 15 | 16 | f = foobar() 17 | f.bar() 18 | f.foo(1) 19 | f.foo(2) 20 | f.bar() 21 | f.bar() 22 | f.foo(-1) 23 | f.bar() 24 | f.foo(7) 25 | f.bar() 26 | 27 | 28 | -------------------------------------------------------------------------------- /tests/basic/kwargs2.py: -------------------------------------------------------------------------------- 1 | def myfunc(a, b, *c, fuga='hoge', **d): 2 | print(a) 3 | print(b) 4 | for i in c: 5 | print(i) 6 | print(fuga) 7 | keys = list(d.keys()) 8 | keys.sort() 9 | for i in keys: 10 | print(i) 11 | print(d[i]) 12 | 13 | myfunc(1, 2, bar='a', foo='c') 14 | print() 15 | myfunc(1, 2, 3, 4, bar='a', foo='c') 16 | myfunc(1, 2, 3, 4, bar='a', fuga='hogehoge', foo='c') 17 | -------------------------------------------------------------------------------- /tests/strings/string_format_i.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 10 4 | c = -30 5 | d = 34 6 | e = 123.456 7 | f = 19892122 8 | 9 | # form 0 10 | s = "b=%i" % b 11 | print(s) 12 | 13 | # form 1 14 | s = "b,c,d=%i+%i+%i" % (b,c,d) 15 | print(s) 16 | 17 | # form 2 18 | s = "b=%(b)i and c=%(c)i and d=%(d)i" % { 'b':b,'c':c,'d':d } 19 | print(s) 20 | 21 | # width,flags 22 | s = "e=%020i e=%+i e=%20i e=%-20i (e=%- 20i)" % (e,e,e,e,e) 23 | print(s) 24 | -------------------------------------------------------------------------------- /tests/unittest/assertAlmostEqual.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class TestRunnable(unittest.TestCase): 4 | 5 | def test_runnable(self): 6 | #(first, second, places=7, msg=None, delta=None) 7 | self.assertAlmostEqual(1.0, 1.00000001, 7) 8 | self.assertAlmostEqual(1.0, 1.00000001, 7, '''comment test''') 9 | self.assertAlmostEqual(1.0, 1.00000001, msg='''comment test''', delta=1e-8) 10 | 11 | unittest.main() 12 | -------------------------------------------------------------------------------- /tests/strings/string_format_d.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 10 4 | c = -30 5 | d = 34 6 | e = 123.456 7 | f = 19892122 8 | 9 | # form 0 10 | s = "b=%d" % b 11 | print(s) 12 | 13 | # form 1 14 | s = "b,c,d=%d+%d+%d" % (b,c,d) 15 | print(s) 16 | 17 | # form 2 18 | s = "b=%(b)0d and c=%(c)d and d=%(d)d" % { 'b':b,'c':c,'d':d } 19 | print(s) 20 | 21 | # width,flags 22 | s = "e=%020d e=%+d e=%20d e=%-20d (e=%- 20d)" % (e,e,e,e,e) 23 | print(s) 24 | -------------------------------------------------------------------------------- /tests/strings/string_format_u.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 10 4 | c = -30 5 | d = 34 6 | e = 123.456 7 | f = 19892122 8 | 9 | # form 0 10 | s = "b=%u" % b 11 | print(s) 12 | 13 | # form 1 14 | s = "b,c,d=%u+%u+%u" % (b,c,d) 15 | print(s) 16 | 17 | # form 2 18 | s = "b=%(b)0u and c=%(c)u and d=%(d)u" % { 'b':b,'c':c,'d':d } 19 | print(s) 20 | 21 | # width,flags 22 | s = "e=%020u e=%+u e=%20u e=%-20u (e=%- 20u)" % (e,e,e,e,e) 23 | print(s) 24 | -------------------------------------------------------------------------------- /tests/strings/string_format_d_simple.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 10 4 | c = -30 5 | d = 34 6 | e = 123.456 7 | f = 19892122 8 | 9 | # form 0 10 | s = "b=%d" % b 11 | print(s) 12 | 13 | # form 1 14 | s = "b,c,d=%d+%d+%d" % (b,c,d) 15 | print(s) 16 | 17 | # form 2 18 | #s = "b=%(b)0d and c=%(c)d and d=%(d)d" % { 'b':b,'c':c,'d':d } 19 | print(s) 20 | 21 | # width,flags 22 | #s = "e=%020d e=%+d e=%20d e=%-20d (e=%- 20d)" % (e,e,e,e,e) 23 | print(s) 24 | -------------------------------------------------------------------------------- /tests/lists/all.py: -------------------------------------------------------------------------------- 1 | 2 | l = [4,7,3,4,2,1] 3 | v = all(l) 4 | print(str(v).upper()) 5 | 6 | print(str(all([])).upper()) 7 | print(str(all({})).upper()) 8 | print(str(all(())).upper()) 9 | print(str(all([False])).upper()) 10 | print(str(all([None])).upper()) 11 | print(str(all([0])).upper()) 12 | print(str(all([''])).upper()) 13 | print(str(all([[]])).upper()) 14 | print(str(all([{}])).upper()) 15 | 16 | l = [0,{}] 17 | v = all(l) 18 | print(str(v).upper()) 19 | -------------------------------------------------------------------------------- /tests/lists/any.py: -------------------------------------------------------------------------------- 1 | 2 | l = [4,7,3,4,2,1] 3 | v = any(l) 4 | print(str(v).upper()) 5 | 6 | print(str(any([])).upper()) 7 | print(str(any({})).upper()) 8 | print(str(any(())).upper()) 9 | print(str(any([False])).upper()) 10 | print(str(any([None])).upper()) 11 | print(str(any([0])).upper()) 12 | print(str(any([''])).upper()) 13 | print(str(any([[]])).upper()) 14 | print(str(any([{}])).upper()) 15 | 16 | l = [0,{}] 17 | v = any(l) 18 | print(str(v).upper()) 19 | -------------------------------------------------------------------------------- /tests/strings/string_format_efg.py: -------------------------------------------------------------------------------- 1 | 2 | a = 1.123456 3 | b = 0.000000000324324 4 | c = 18347894.213123 5 | d = 0.0 6 | e = -1324323.456 7 | f = -0.000000000019892122 8 | 9 | vars = [a,b,c,d,e,f] 10 | codes = ['e','E','f','F','g','G'] 11 | 12 | fmts = ["a=%e","a=%10.5e","a=%+10.5e","a=%#e"] 13 | 14 | for code in codes: 15 | for fmt in fmts: 16 | fmt = fmt.replace('e',code) 17 | for v in vars: 18 | print(fmt + ":", fmt % v) 19 | -------------------------------------------------------------------------------- /tests/numpy/any.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | v = np.any([[True, False], [True, True]]) 5 | print(str(v).upper()) 6 | 7 | """ [False, True] => [0, 1] """ 8 | v = np.any([[True, False], [True, True]], axis=0) 9 | for a in v: 10 | if a in (True, 1): 11 | print('TRUE') 12 | else: 13 | print('FALSE') 14 | 15 | v = np.any([-1, 0, 4]) 16 | print(str(v).upper()) 17 | 18 | v = np.any(np.nan) 19 | print(str(v).upper()) 20 | 21 | -------------------------------------------------------------------------------- /tests/numpy/all.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | v = np.all([[True, False], [True, True]]) 5 | print(str(v).upper()) 6 | 7 | """ [True, False] => [1, 0] """ 8 | v = np.all([[True, False], [True, True]], axis=0) 9 | for a in v: 10 | if a in (True, 1): 11 | print('TRUE') 12 | else: 13 | print('FALSE') 14 | 15 | v = np.all([-1, 0, 4]) 16 | print(str(v).upper()) 17 | 18 | v = np.all([1.0 ,np.nan]) 19 | print(str(v).upper()) 20 | 21 | -------------------------------------------------------------------------------- /tests/deep-learning-from-scratch/and_gate.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | 5 | def AND(x1, x2): 6 | x = np.array([x1, x2]) 7 | w = np.array([0.5, 0.5]) 8 | b = -0.7 9 | tmp = np.sum(w*x) + b 10 | if tmp <= 0: 11 | return 0 12 | else: 13 | return 1 14 | 15 | if __name__ == '__main__': 16 | for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]: 17 | y = AND(xs[0], xs[1]) 18 | print(str(xs) + " -> " + str(y)) 19 | -------------------------------------------------------------------------------- /tests/numpy/empty.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_array(data): 5 | datas = [] 6 | for i in data: 7 | datas.append(i) 8 | print(datas) 9 | 10 | x = np.empty(()) 11 | print_array(x.shape) 12 | 13 | x = np.empty((0)) 14 | print_array(x.shape) 15 | 16 | x = np.empty((0,0)) 17 | print_array(x.shape) 18 | 19 | x = np.empty(3, dtype=np.float32) 20 | print_array(x.shape) 21 | 22 | x = np.empty((2,3)) 23 | print_array(x.shape) 24 | 25 | -------------------------------------------------------------------------------- /tests/basic/vars2.py: -------------------------------------------------------------------------------- 1 | x = 1 2 | y = 2 3 | 4 | def f1(): 5 | x, y = 3, 4 6 | print([x, y]) 7 | 8 | def f2(): 9 | global y 10 | x, y = 5, 6 11 | print([x, y]) 12 | 13 | def f3(): 14 | global x 15 | x, y = 7, 8 16 | print([x, y]) 17 | 18 | def f4(): 19 | global x, y 20 | x, y = 9, 10 21 | print([x, y]) 22 | 23 | print([x, y]) 24 | f1() 25 | print([x, y]) 26 | f2() 27 | print([x, y]) 28 | f3() 29 | print([x, y]) 30 | f4() 31 | print([x, y]) 32 | -------------------------------------------------------------------------------- /tests/functions/sort23.py: -------------------------------------------------------------------------------- 1 | 2 | def getkey(x): 3 | if x < 5: 4 | return x + 10 5 | else: 6 | return x 7 | 8 | def revcmp(a,b): 9 | if b y: 8 | print("x > y - incorrect") 9 | else: 10 | print("not x > y - correct") 11 | 12 | if y >= y2: 13 | print("y >= y2 - correct") 14 | else: 15 | print("not y >= y2 - incorrect") 16 | 17 | if z > x: 18 | print("z > x - correct") 19 | else: 20 | print("not z > x - incorrect") 21 | 22 | if y >= z: 23 | print("y >= z - incorrect") 24 | else: 25 | print("not y >= x - correct") 26 | 27 | -------------------------------------------------------------------------------- /tests/functions/ltle.py: -------------------------------------------------------------------------------- 1 | 2 | x = 123 3 | y = 233 4 | y2 = 233 5 | z = 892 6 | 7 | if x < y: 8 | print("x < y - correct") 9 | else: 10 | print("not x < y - incorrect") 11 | 12 | if y <= y2: 13 | print("y <= y2 - correct") 14 | else: 15 | print("not y <= y2 - incorrect") 16 | 17 | if z < x: 18 | print("z < x - incorrect") 19 | else: 20 | print("not z < x - correct") 21 | 22 | if y <= z: 23 | print("y <= z - correct") 24 | else: 25 | print("not y <= x - incorrect") 26 | 27 | -------------------------------------------------------------------------------- /tests/lists/subclass3.py: -------------------------------------------------------------------------------- 1 | class List(object): 2 | 3 | def __init__(self, l=[]): 4 | self._list = list(l) 5 | 6 | def append(self, x): 7 | self._list.append(x) 8 | 9 | def remove(self, x): 10 | self._list.remove(x) 11 | 12 | def __str__(self): 13 | return str(self._list) 14 | 15 | class Layer(List): 16 | pass 17 | 18 | l1 = Layer() 19 | l1.append(1) 20 | l1.append(2) 21 | l2 = list() 22 | l2.append(3) 23 | l2.append(4) 24 | print(l1) 25 | print(l2) 26 | -------------------------------------------------------------------------------- /tests/basic/tuple.py: -------------------------------------------------------------------------------- 1 | 2 | tup = ('a','b',1,2,3) 3 | print(len(tup)) 4 | print(tup[0]) 5 | print(tup[1]) 6 | print(tup[2]) 7 | print(tup[3]) 8 | print(tup[4]) 9 | 10 | tup = tuple() 11 | print(len(tup)) 12 | 13 | tup = tuple(('a','b',1,2,3)) 14 | print(len(tup)) 15 | print(tup[0]) 16 | print(tup[1]) 17 | print(tup[2]) 18 | print(tup[3]) 19 | 20 | tup = tuple("ABC") 21 | print(len(tup)) 22 | print(tup[0]) 23 | print(tup[1]) 24 | print(tup[2]) 25 | 26 | tup = tuple([10, 20]) 27 | print(len(tup)) 28 | print(tup[0]) 29 | print(tup[1]) 30 | -------------------------------------------------------------------------------- /tests/numpy/random_uniform.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def print_matrix(data): 4 | data_i = [] 5 | for i in list(data): 6 | data_j = [] 7 | for j in i: 8 | data_j.append(j) 9 | data_i.append(data_j) 10 | print(data_i) 11 | 12 | x = np.random.uniform(-1, 1, (3,2)) 13 | 14 | y = np.array(x < 1, dtype=np.int) 15 | print_matrix(y) 16 | 17 | y = np.array(x > -1, dtype=np.int) 18 | print_matrix(y) 19 | 20 | x = np.random.uniform(-1, 1) 21 | x = np.asarray(x) 22 | print(x.ndim) 23 | 24 | -------------------------------------------------------------------------------- /tests/lists/subclass2.py: -------------------------------------------------------------------------------- 1 | class List(object): 2 | 3 | def __init__(self, l=[]): 4 | self._list = list(l) 5 | 6 | def append(self, x): 7 | self._list.append(x) 8 | 9 | def remove(self, x): 10 | self._list.remove(x) 11 | 12 | def __str__(self): 13 | return str(self._list) 14 | 15 | class A(List): 16 | 17 | def my_append(self, a): 18 | self.append(a) 19 | 20 | a = A() 21 | print(a) 22 | a.append(5) 23 | print(a) 24 | a.append(6) 25 | print(a) 26 | a.remove(5) 27 | print(a) 28 | -------------------------------------------------------------------------------- /tests/basic/class2.py: -------------------------------------------------------------------------------- 1 | class Class1(object): 2 | 3 | def __init__(self): 4 | pass 5 | 6 | def test1(self): 7 | return 5 8 | 9 | class Class2(object): 10 | 11 | def test1(self): 12 | return 6 13 | 14 | class Class3(object): 15 | 16 | def test1(self, x): 17 | return self.test2(x)-1 18 | 19 | def test2(self, x): 20 | return 2*x 21 | 22 | a = Class1() 23 | print(a.test1()) 24 | 25 | a = Class2() 26 | print(a.test1()) 27 | 28 | a = Class3() 29 | print(a.test1(3)) 30 | print(a.test2(3)) 31 | -------------------------------------------------------------------------------- /tests/deep-learning-from-scratch/sigmoid.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def sigmoid(x): 4 | return 1 / (1 + np.exp(-x)) 5 | 6 | x = np.arange(-5.0, 5.0, 0.1) 7 | y = sigmoid(x) 8 | 9 | def print_array(data): 10 | datas = [] 11 | for i in data: 12 | if float("%.3f" % abs(i)) == 0: 13 | datas.append(float("%.3f" % abs(i))) 14 | else: 15 | datas.append(float("%.3f" % i)) 16 | print(datas) 17 | 18 | print(len(x)) 19 | print_array(list(x)) 20 | 21 | print(len(y)) 22 | print_array(list(y)) 23 | -------------------------------------------------------------------------------- /tests/deep-learning-from-scratch/relu.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def relu(x): 5 | return np.maximum(0, x) 6 | 7 | x = np.arange(-5.0, 5.0, 0.1) 8 | y = relu(x) 9 | 10 | def print_array(data): 11 | datas = [] 12 | for i in data: 13 | if float("%.3f" % abs(i)) == 0: 14 | datas.append(float("%.3f" % abs(i))) 15 | else: 16 | datas.append(float("%.3f" % i)) 17 | print(datas) 18 | 19 | print(len(x)) 20 | print_array(list(x)) 21 | print(len(y)) 22 | print_array(list(y)) 23 | 24 | -------------------------------------------------------------------------------- /tests/basic/del_dict.py: -------------------------------------------------------------------------------- 1 | 2 | mydict = {} 3 | 4 | mydict["abc"] = "def" 5 | mydict["def"] = "abc" 6 | mydict["xyz"] = "rst" 7 | 8 | print(mydict["abc"]) 9 | print(mydict["def"]) 10 | print(mydict["xyz"]) 11 | 12 | del mydict["def"] 13 | 14 | if "abc" in mydict: 15 | print("abc in mydict") 16 | else: 17 | print("abc not in mydict") 18 | 19 | if "def" in mydict: 20 | print("def in mydict") 21 | else: 22 | print("def not in mydict") 23 | 24 | if "xyz" in mydict: 25 | print("xyz in mydict") 26 | else: 27 | print("xyz not in mydict") 28 | -------------------------------------------------------------------------------- /tests/basic/oo_inherit2.py: -------------------------------------------------------------------------------- 1 | def show(o): 2 | """ 3 | This tests that the proper method is called. 4 | """ 5 | o.msg() 6 | 7 | def show2(o): 8 | """ 9 | This tests oo inheritance. 10 | """ 11 | o.print_msg() 12 | 13 | class A(object): 14 | 15 | def msg(self): 16 | print("A.msg()") 17 | 18 | def print_msg(self): 19 | self.msg() 20 | 21 | class B(A): 22 | 23 | def msg(self): 24 | print("B.msg()") 25 | 26 | 27 | a = A() 28 | show(a) 29 | show2(a) 30 | b = B() 31 | show(b) 32 | show2(b) 33 | -------------------------------------------------------------------------------- /tests/basic/str1.py: -------------------------------------------------------------------------------- 1 | s1 = "some string" 2 | 3 | s2 = "some 'x' string" 4 | 5 | s3 = 'some "x" string' 6 | 7 | s4 = "some \"x\" string" 8 | 9 | s5 = """some "x" string""" 10 | 11 | s6 = """some "x" string 12 | and some other string too... 13 | """ 14 | 15 | if s2 == s3: 16 | print("ok1") 17 | if s3 == s4: 18 | print("ok2") 19 | if s3 == s5: 20 | print("ok3") 21 | if s3 != s6: 22 | print("ok4") 23 | 24 | """some "x" string 25 | and some other string too... 26 | """ 27 | 28 | if True: 29 | """some "x" string 30 | and some other string too... 31 | """ 32 | -------------------------------------------------------------------------------- /tests/numpy/array2string.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | x = np.array([1,2,3,4,5,6,7,8,9,10], dtype='int8') 4 | print(list(x)) 5 | print(np.array2string(x)) 6 | print(np.array2string(x, None)) 7 | print(np.array2string(x, None, None, None, ' ')) 8 | print(np.array2string(x, precision=2, separator=',', suppress_small=True)) 9 | print(np.array2string(x, precision=3, separator=',', suppress_small=True)) 10 | print('hoge : ' +np.array2string(x, precision=4, separator=',', suppress_small=True, prefix='hoge : ')) 11 | print(np.array2string(x, precision=4)) 12 | print(np.array2string(x)) 13 | -------------------------------------------------------------------------------- /tests/numpy/random_randint.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def print_array(data): 4 | datas = [] 5 | for i in data: 6 | datas.append(i) 7 | print(datas) 8 | 9 | x = np.random.randint(3) 10 | if 0 <= x <= 3: 11 | print('OK') 12 | else: 13 | print('NG') 14 | 15 | x = np.random.randint(1,3) 16 | if 1 <= x <= 3: 17 | print('OK') 18 | else: 19 | print('NG') 20 | 21 | x = np.random.randint(1,3,(3,3)) 22 | print(x.ndim) 23 | print_array(x.shape) 24 | 25 | x = np.random.randint(1,3,(3,3), dtype=np.int64) 26 | print(x.ndim) 27 | print_array(x.shape) 28 | -------------------------------------------------------------------------------- /tests/deep-learning-from-scratch/step_function.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def step_function(x): 5 | return np.array(x > 0, dtype=np.int) 6 | 7 | X = np.arange(-5.0, 5.0, 0.1) 8 | Y = step_function(X) 9 | 10 | 11 | def print_array(data): 12 | datas = [] 13 | for i in data: 14 | if float("%.3f" % abs(i)) == 0: 15 | datas.append(float("%.3f" % abs(i))) 16 | else: 17 | datas.append(float("%.3f" % i)) 18 | print(datas) 19 | 20 | print(len(X)) 21 | print_array(list(X)) 22 | print(len(Y)) 23 | print_array(list(Y)) 24 | -------------------------------------------------------------------------------- /tests/basic/ifs2.py: -------------------------------------------------------------------------------- 1 | def ifs1(x): 2 | a = 1 3 | if 0 < x < 10: 4 | a = 2 5 | else: 6 | a = 3 7 | return a 8 | 9 | def ifs2(x): 10 | a = 1 11 | if 0 == x != 10: 12 | a = 2 13 | else: 14 | a = 3 15 | return a 16 | 17 | def ifs3(x): 18 | a = 1 19 | if 0 in x in [[0]]: 20 | a = 2 21 | else: 22 | a = 3 23 | return a 24 | 25 | print('ifs1') 26 | print(ifs1(-1)) 27 | print(ifs1(1)) 28 | print(ifs1(11)) 29 | print('ifs2') 30 | print(ifs2(0)) 31 | print(ifs2(10)) 32 | print('ifs3') 33 | print(ifs3([0])) 34 | print(ifs3([1])) 35 | -------------------------------------------------------------------------------- /tests/numpy/asarray.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def print_matrix(data): 4 | data_i = [] 5 | for i in list(data): 6 | data_j = [] 7 | for j in i: 8 | data_j.append(int("%d" % j)) 9 | data_i.append(data_j) 10 | print(data_i) 11 | 12 | def print_array(data): 13 | datas = [] 14 | for i in data: 15 | datas.append(float("%.3f" % i)) 16 | print(datas) 17 | 18 | x = np.asarray([[1.,2.],[3.,4.]]) 19 | print_matrix(x) 20 | 21 | x = np.asarray([1.,2.]) 22 | print_array(x) 23 | 24 | y = np.asarray([3.,4.]) 25 | print_array(y) 26 | 27 | z = (x + y)[0] 28 | print(z) 29 | -------------------------------------------------------------------------------- /tests/numpy/maximum_minimum.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_array(data): 5 | datas = [] 6 | for i in data: 7 | if float("%.3f" % abs(i)) == 0: 8 | datas.append(float("%.3f" % abs(i))) 9 | else: 10 | datas.append(float("%.3f" % i)) 11 | print(datas) 12 | 13 | x = np.arange(-5.0, 5.0, 0.1) 14 | print(len(x)) 15 | print_array(list(x)) 16 | 17 | """ 18 | maximum 19 | """ 20 | y = np.maximum(0, x) 21 | print(len(y)) 22 | print_array(list(y)) 23 | 24 | """ 25 | minimum 26 | """ 27 | y = np.minimum(0, x) 28 | print(len(y)) 29 | print_array(list(y)) 30 | -------------------------------------------------------------------------------- /tests/modules/rng.py: -------------------------------------------------------------------------------- 1 | 2 | from mtrandom import * 3 | 4 | def float2str(v,dp): 5 | s = str(v) 6 | dotpos = s.find(".") 7 | if dotpos >= 0: 8 | return s[:dotpos+dp+1] 9 | return s 10 | 11 | class RNG: 12 | def __init__(self): 13 | init = [0x123, 0x234, 0x345, 0x456] 14 | self.r = MersenneTwister() 15 | self.r.init_by_array(init,4) 16 | 17 | def __next__(self): 18 | return self.r.genrand_res53() 19 | 20 | if __name__ == "__main__": 21 | r = RNG() 22 | print(float2str(next(r),9)) 23 | print(float2str(next(r),9)) 24 | print(float2str(next(r),9)) 25 | 26 | -------------------------------------------------------------------------------- /tests/numpy/product.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | x = np.prod([1.,2.]) 3 | print(x) 4 | x = np.prod([[1.,2.],[3.,4.]]) 5 | print(x) 6 | x = np.prod([1.,2.], dtype= np.int32) 7 | print(int(x)) 8 | x = np.prod([1.,2.], None, np.int32) 9 | print(int(x)) 10 | x = np.prod([1.,2.], None, dtype= np.int32) 11 | print(int(x)) 12 | x = np.prod(dtype= np.int32, a=[1.,2.]) 13 | print(int(x)) 14 | x = np.prod([[1.,2.],[3.,4.]], axis=0) 15 | print(list(x)) 16 | x = np.prod([[1.,2.],[3.,4.]], axis=1) 17 | print(list(x)) 18 | x = np.prod([3.,4.], keepdims=True) 19 | print(list(x)) 20 | a = [3.,4.] 21 | x = np.prod(a, dtype= np.int32) 22 | print(int(x)) 23 | -------------------------------------------------------------------------------- /tests/basic/generator.py: -------------------------------------------------------------------------------- 1 | 2 | class generator: 3 | 4 | class iterator: 5 | def __init__(self,parent): 6 | self.parent = parent 7 | self.value = parent.min 8 | 9 | def __next__(self): 10 | val = self.value 11 | if val > self.parent.max: 12 | raise StopIteration 13 | self.value += 1 14 | return val 15 | 16 | def __init__(self,min,max): 17 | self.min = min 18 | self.max = max 19 | 20 | def __iter__(self): 21 | return self.iterator(self) 22 | 23 | g = generator(5,10) 24 | for v in g: 25 | print(v) 26 | -------------------------------------------------------------------------------- /tests/basic/oo_inherit3.py: -------------------------------------------------------------------------------- 1 | def show(o): 2 | """ 3 | This tests that the proper method is called. 4 | """ 5 | o.msg() 6 | 7 | def show2(o): 8 | """ 9 | This tests oo inheritance. 10 | """ 11 | o.print_msg() 12 | 13 | class A(object): 14 | 15 | def __init__(self): 16 | self._a = 5 17 | 18 | def msg(self): 19 | print("A.msg()") 20 | 21 | def print_msg(self): 22 | self.msg() 23 | print(self._a) 24 | 25 | class B(A): 26 | 27 | def msg(self): 28 | print("B.msg()") 29 | 30 | 31 | a = A() 32 | show(a) 33 | show2(a) 34 | b = B() 35 | show(b) 36 | show2(b) 37 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: python 3 | python: 4 | - 3.5 5 | - 3.6 6 | before_install: 7 | - gem update bundler 8 | install: 9 | - pip install numpy PyYAML 10 | - gem install numo-narray 11 | script: 12 | - python --version 13 | - ruby --version 14 | - python run_tests.py -a 15 | - for f in `\find tests/* -maxdepth 1 -name '*.py.comp.err'`; do if [ -s $f ];then base=`echo $f | sed 's/\.py.comp.err$//'`; echo "[$base.cmd.txt]"; cat $base.cmd.txt; echo ""; echo "[$f]"; cat $f; echo ""; fi done 16 | - for f in `\find tests/* -maxdepth 1 -name '*.py.err'`; do if [ -s $f ];then echo ""; echo "[$f]"; cat $f; fi done 17 | -------------------------------------------------------------------------------- /tests/basic/hasattr1.py: -------------------------------------------------------------------------------- 1 | class AttrTest(): 2 | def __init__(self): 3 | self.base = -1 4 | 5 | def __call__(self): 6 | if hasattr(self, 'base'): 7 | print("Class :base is True") 8 | else: 9 | print("Class :base is False") 10 | 11 | attr_test = AttrTest() 12 | if hasattr(attr_test, 'base'): 13 | print("base is True") 14 | else: 15 | print("base is False") 16 | 17 | if hasattr(attr_test, 'foo'): 18 | print("foo is True") 19 | else: 20 | print("foo is False") 21 | 22 | if hasattr(attr_test, 'bar'): 23 | print("bar is True") 24 | else: 25 | print("bar is False") 26 | attr_test() 27 | -------------------------------------------------------------------------------- /tests/decorator/decorator.py: -------------------------------------------------------------------------------- 1 | 2 | class wrapper: 3 | 4 | def __init__(self,fn): 5 | self.fn = fn 6 | 7 | def __call__(self,*args): 8 | return "("+self.fn(*args)+")" 9 | 10 | def mydecorator(x): 11 | print("decorating " + str(x)) 12 | return wrapper(x) 13 | 14 | class myclass: 15 | 16 | def __init__(self,val): 17 | self.val = val 18 | 19 | @mydecorator 20 | def describe(self): 21 | return self.val 22 | 23 | @mydecorator 24 | def describe(): 25 | return "world" 26 | describe = mydecorator(describe) 27 | 28 | m = myclass("hello") 29 | print(m.describe(m)) 30 | 31 | print(describe()) 32 | -------------------------------------------------------------------------------- /tests/basic/oo_diamond.py: -------------------------------------------------------------------------------- 1 | 2 | class foobar(object): 3 | 4 | def m1(self): 5 | print("foobar.m1") 6 | 7 | def m2(self): 8 | print("foobar.m2") 9 | 10 | def m3(self): 11 | print("foobar.m3") 12 | 13 | def m4(self): 14 | print("foobar.m4") 15 | 16 | 17 | class foo(foobar): 18 | 19 | def m2(self): 20 | print("foo.m2") 21 | 22 | def m4(self): 23 | print("foo.m4") 24 | 25 | class bar(foobar): 26 | 27 | def m3(self): 28 | print("bar.m3") 29 | 30 | class myfb(foo,bar): 31 | 32 | def m4(self): 33 | print("myfb.m4") 34 | 35 | x = myfb() 36 | x.m1() 37 | x.m2() 38 | x.m3() 39 | x.m4() 40 | -------------------------------------------------------------------------------- /tests/basic/raise2.py: -------------------------------------------------------------------------------- 1 | try: 2 | raise 3 | except: 4 | pass 5 | 6 | try: 7 | foo 8 | except NameError: 9 | print('NameError :') 10 | except: 11 | print('Error :') 12 | 13 | try: 14 | raise NameError 15 | except NameError: 16 | print('NameError :') 17 | except: 18 | print('Error :') 19 | 20 | try: 21 | raise NameError('User Defined Error Message.') 22 | except NameError as err: 23 | print('NameError :', err) 24 | except: 25 | print('Error :') 26 | 27 | try: 28 | raise NotImplementedError('User Defined Error Message.') 29 | except NotImplementedError as err: 30 | print('NotImplementedError :', err) 31 | except: 32 | print('Error :') 33 | -------------------------------------------------------------------------------- /tests/basic/for_in2.py: -------------------------------------------------------------------------------- 1 | # iterating over a list 2 | print('-- list --') 3 | a = [1,2,3,4,5] 4 | for x in a: 5 | print(x) 6 | 7 | # iterating over a tuple 8 | print('-- tuple --') 9 | a = ('cats','dogs','squirrels') 10 | for x in a: 11 | print(x) 12 | 13 | # iterating over a dictionary 14 | # sort order in python is undefined, so need to sort the results 15 | # explictly before comparing output 16 | 17 | print('-- dict --') 18 | a = {'a':1,'b':2,'c':3 } 19 | 20 | keys = [] 21 | for x in a: 22 | keys.append(x) 23 | 24 | keys.sort() 25 | for k in keys: 26 | print(k) 27 | 28 | # iterating over a string 29 | print('-- string --') 30 | a = 'defabc' 31 | for x in a: 32 | print(x) 33 | 34 | -------------------------------------------------------------------------------- /tests/decorator/class.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class foobar(object): 4 | 5 | x = 1 6 | 7 | def __init__(self): 8 | self.foovar = 1 9 | 10 | def foo(self,x): 11 | self.foovar = self.foovar + x 12 | 13 | def bar(self): 14 | print(self.foovar) 15 | 16 | @property 17 | def x(self): 18 | return self._x 19 | 20 | @x.setter 21 | def x(self, data): 22 | self._x = data 23 | 24 | def set_x(self, x): 25 | self.x = x 26 | 27 | f = foobar() 28 | f.bar() 29 | f.foo(1) 30 | f.foo(2) 31 | f.bar() 32 | f.bar() 33 | f.foo(-1) 34 | f.bar() 35 | f.foo(7) 36 | f.bar() 37 | 38 | f.x = 5 39 | print(f.x) 40 | 41 | f.set_x = 10 42 | print(f.x) 43 | 44 | -------------------------------------------------------------------------------- /tests/numpy/like.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_matrix(data): 5 | data_i = [] 6 | for i in list(data): 7 | data_j = [] 8 | for j in i: 9 | data_j.append(int("%d" % j)) 10 | data_i.append(data_j) 11 | print(data_i) 12 | 13 | x = np.arange(6) 14 | x = x.reshape(2, 3) 15 | print_matrix(x) 16 | 17 | x = np.ones_like(x) 18 | print_matrix(x) 19 | 20 | x = np.zeros_like(x) 21 | print_matrix(x) 22 | 23 | x = np.full_like(x, 1) 24 | print_matrix(x) 25 | 26 | a = ([1,2,3], [4,5,6]) 27 | x = np.empty_like(a) 28 | print(list(x.shape)) 29 | 30 | a = np.array([[1., 2., 3.],[4.,5.,6.]]) 31 | x = np.empty_like(a) 32 | print(list(x.shape)) 33 | -------------------------------------------------------------------------------- /tests/numpy/abs.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_matrix(data): 5 | data_i = [] 6 | for i in list(data): 7 | data_j = [] 8 | for j in i: 9 | data_j.append(j) 10 | data_i.append(data_j) 11 | print(data_i) 12 | 13 | def print_array(data): 14 | datas = [] 15 | for i in data: 16 | datas.append(i) 17 | print(datas) 18 | 19 | 20 | """ 21 | 1-dim 22 | """ 23 | x = np.array([2,-3,4]) 24 | print_array(x) 25 | 26 | y = np.abs(x) 27 | print_array(y) 28 | 29 | y = np.absolute(x) 30 | print_array(y) 31 | """ 32 | 2-dim 33 | """ 34 | z = np.array([[-2,3,-6],[3,-4,5]]) 35 | print_matrix(z) 36 | 37 | y = np.abs(z) 38 | print_matrix(y) 39 | 40 | -------------------------------------------------------------------------------- /tests/numpy/insert.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def print_array(data): 4 | datas = [] 5 | for i in data: 6 | datas.append(i) 7 | print(datas) 8 | def print_matrix(data): 9 | data_i = [] 10 | for i in list(data): 11 | data_j = [] 12 | for j in i: 13 | data_j.append(j) 14 | data_i.append(data_j) 15 | print(data_i) 16 | 17 | x = np.array([[1, 1], [2, 2], [3, 3]], dtype=np.int8) 18 | """[[1, 1], [2, 2], [3, 3]] => [1, 5, 1, 2, 2, 3, 3]""" 19 | x = np.insert(x, 1, 5) 20 | print_array(x) 21 | 22 | x = np.array([[1, 1], [2, 2], [3, 3]]) 23 | """[[1, 1], [2, 2], [3, 3]] => [[1, 5, 1], [2, 5, 2], [3, 5, 3]]""" 24 | x = np.insert(x, 1, 5, axis=1) 25 | print_matrix(x) 26 | -------------------------------------------------------------------------------- /tests/basic/oo.py: -------------------------------------------------------------------------------- 1 | 2 | class foo(object): 3 | 4 | registered = [] 5 | 6 | def __init__(self,val): 7 | self.fval = val 8 | self.register(self) 9 | 10 | def inc(self): 11 | self.fval += 1 12 | 13 | def msg(self): 14 | return "foo says:"+str(self.fval) 15 | 16 | @staticmethod 17 | def register(f): 18 | foo.registered.append(f) 19 | 20 | @staticmethod 21 | def printregistered(): 22 | for r in foo.registered: 23 | print(r.msg()) 24 | 25 | a = foo(10) 26 | b = foo(20) 27 | c = foo(30) 28 | 29 | a.inc() 30 | a.inc() 31 | c.inc() 32 | 33 | print(a.msg()) 34 | print(b.msg()) 35 | print(c.msg()) 36 | 37 | print("---") 38 | 39 | foo.printregistered() 40 | -------------------------------------------------------------------------------- /tests/basic/del_attr.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class spam: 4 | 5 | def __init__(self): 6 | self.eggs = 0 7 | 8 | def addegg(self): 9 | try: 10 | if self.eggs: 11 | self.eggs += 1 12 | else: 13 | self.eggs = 1 14 | except: 15 | self.eggs = 1 16 | 17 | def printit(self): 18 | try: 19 | if self.eggs: 20 | print(self.eggs) 21 | else: 22 | print("no eggs") 23 | except: 24 | print("no eggs") 25 | 26 | 27 | s = spam() 28 | s.addegg() 29 | s.addegg() 30 | s.printit() 31 | s.addegg() 32 | s.printit() 33 | del s.eggs 34 | s.printit() 35 | s.addegg() 36 | s.addegg() 37 | s.printit() 38 | -------------------------------------------------------------------------------- /tests/numpy/not_like.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_matrix(data): 5 | data_i = [] 6 | for i in list(data): 7 | data_j = [] 8 | for j in i: 9 | data_j.append(int("%d" % j)) 10 | data_i.append(data_j) 11 | print(data_i) 12 | 13 | def print_array(data): 14 | datas = [] 15 | for i in data: 16 | if float("%.3f" % abs(i)) == 0: 17 | datas.append(float("%.3f" % abs(i))) 18 | else: 19 | datas.append(float("%.3f" % i)) 20 | print(datas) 21 | 22 | x = np.ones(5) 23 | print_array(x) 24 | 25 | x = np.zeros(5) 26 | print_array(x) 27 | 28 | x = np.full((2, 2), 1) 29 | print_matrix(x) 30 | 31 | #x = np.empty([2, 2]) 32 | #print(list(x.shape)) 33 | 34 | 35 | -------------------------------------------------------------------------------- /tests/basic/super1.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class baseklass(object): 4 | 5 | def __init__(self,bval): 6 | self.bval = bval 7 | 8 | def describe(self,arg): 9 | print("baseklass.describe:"+self.bval+":"+str(arg)) 10 | 11 | def describe2(self,**kwargs): 12 | print("baseklass.describe2:"+self.bval+":"+kwargs['string']) 13 | 14 | class klass(baseklass): 15 | 16 | def __init__(self,val,bval): 17 | baseklass.__init__(self,bval) 18 | self.val = val 19 | 20 | def describe(self): 21 | super(klass,self).describe(10) 22 | super(klass,self).describe2(string='somestring') 23 | self.describe2(string='somestring') 24 | print("klass.describe:"+self.val) 25 | 26 | k = klass("world","hello") 27 | k.describe() 28 | -------------------------------------------------------------------------------- /tests/basic/try.py: -------------------------------------------------------------------------------- 1 | 2 | class MyException(Exception): 3 | 4 | def __init__(self,msg): 5 | self.msg = msg 6 | 7 | def message(self): 8 | return self.msg 9 | 10 | class MyOtherException(Exception): 11 | 12 | def __init__(self,msg): 13 | self.msg = msg 14 | 15 | def message(self): 16 | return self.msg 17 | 18 | for index in [1,2]: 19 | try: 20 | print('raising exception...') 21 | if index==1: 22 | raise MyException('bar') 23 | elif index==2: 24 | raise MyOtherException('foo') 25 | except MyOtherException as ex2: 26 | print('caught other exception:' + ex2.message()) 27 | except MyException as ex: 28 | print('caught exception:' + ex.message()) 29 | finally: 30 | print('and finally...') 31 | -------------------------------------------------------------------------------- /tests/algorithms/sqrt.py: -------------------------------------------------------------------------------- 1 | def abs(x): 2 | if x > 0: 3 | return x 4 | else: 5 | return -x 6 | 7 | def sqrt(x): 8 | eps = 1e-10 9 | x = float(x) 10 | r = x/2 11 | residual = r**2 - x 12 | while abs(residual) > eps: 13 | r_d = -residual/(2*r) 14 | r += r_d 15 | residual = r**2 - x 16 | return r 17 | 18 | def p(x): 19 | prec = 11 20 | l = list(iter(str(x)))[:prec] 21 | if not "." in l: 22 | l.append(".") 23 | l.append("0") 24 | while len(l) < prec: 25 | l.append("0") 26 | s = "" 27 | for c in l: 28 | s += c 29 | return s 30 | 31 | print((p(sqrt(1)))) 32 | print((p(sqrt(2)))) 33 | print((p(sqrt(3)))) 34 | print((p(sqrt(4)))) 35 | print((p(sqrt(5)))) 36 | print((p(sqrt(6)))) 37 | print((p(sqrt(7000)))) 38 | -------------------------------------------------------------------------------- /tests/basic/augassign2.py: -------------------------------------------------------------------------------- 1 | def f1(x): 2 | return x 3 | 4 | def f2(x): 5 | return x + 5 6 | 7 | def f3(x): 8 | a = x + 1 9 | return a - 5 10 | 11 | def f3b(x): 12 | a = x + 1 13 | a -= 5 14 | return a 15 | 16 | def f3c(x): 17 | a = float(x) + 1 18 | a /= 5 19 | return a 20 | 21 | def f3d(x): 22 | a = x + 1 23 | a *= 5 24 | return a 25 | 26 | def f3e(x): 27 | a = x + 1 28 | a += 5 29 | return a 30 | 31 | def f4(x): 32 | if x: 33 | return 5 34 | else: 35 | return 6 36 | 37 | def f5(x): 38 | a = 1 39 | if x: 40 | a = a + 1 41 | else: 42 | a = a - 1 43 | return a 44 | 45 | print(f1(3)) 46 | print(f2(3)) 47 | print(f3(3)) 48 | print(f3b(3)) 49 | print(f3c(3)) 50 | print(f3d(3)) 51 | print(f3e(3)) 52 | print(f4(True)) 53 | print(f4(False)) 54 | print(f5(True)) 55 | print(f5(False)) 56 | -------------------------------------------------------------------------------- /tests/numpy/trigonometric_funcitons.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_array(data): 5 | datas = [] 6 | for i in data: 7 | if float("%.3f" % abs(i)) == 0: 8 | datas.append(float("%.3f" % abs(i))) 9 | else: 10 | datas.append(float("%.3f" % i)) 11 | print(datas) 12 | 13 | """ Trigonometric functions """ 14 | 15 | x1 = np.arange(0, 6, 0.1) 16 | x2 = np.arange(-0.9, 1, 0.1) 17 | x3 = np.arange(1, 6, 0.1) 18 | 19 | y1 = np.sin(x1) 20 | y2 = np.cos(x1) 21 | y3 = np.tan(x1) 22 | 23 | yh1 = np.sinh(x1) 24 | yh2 = np.cosh(x1) 25 | yh3 = np.tanh(x1) 26 | 27 | ay1 = np.arcsin(x2) 28 | ay2 = np.arccos(x2) 29 | ay3 = np.arctan(x1) 30 | 31 | ayh1 = np.arcsinh(x1) 32 | ayh2 = np.arccosh(x3) 33 | ayh3 = np.arctanh(x2) 34 | 35 | for y in [x1, x2, x3, y1, y2, y3, yh1, yh2, yh3, ay1, ay2, ay3, ayh1, ayh2, ayh3]: 36 | print(len(y)) 37 | print_array(list(y)) 38 | -------------------------------------------------------------------------------- /tests/basic/ifs.py: -------------------------------------------------------------------------------- 1 | def ifs1(x): 2 | a = 1 3 | if x: 4 | a = a + 1 5 | a *= 2 6 | else: 7 | a = a - 1 8 | a *= 4 9 | return a 10 | 11 | def ifs2(x): 12 | a = 1 13 | if x > 0: 14 | a = a + 1 15 | a *= 2 16 | else: 17 | a = a - 1 18 | a *= 4 19 | return a 20 | 21 | def ifs3(x): 22 | a = 1 23 | if x > 0: 24 | if x > 10: 25 | a = 3 26 | else: 27 | a = 4 28 | a = 5 29 | return a 30 | 31 | def ifs4(x): 32 | a = 1 33 | if x > 0: 34 | if x > 10: 35 | a = 3 36 | else: 37 | a = 4 38 | else: 39 | a = 5 40 | return a 41 | 42 | print(ifs1(True)) 43 | print(ifs1(False)) 44 | print(ifs2(1)) 45 | print(ifs2(-1)) 46 | print(ifs3(1)) 47 | print(ifs3(20)) 48 | print(ifs3(-1)) 49 | print(ifs4(1)) 50 | print(ifs4(20)) 51 | print(ifs4(-1)) 52 | -------------------------------------------------------------------------------- /tests/functions/isinstance.py: -------------------------------------------------------------------------------- 1 | 2 | class Spam(object): 3 | 4 | def __init__(self,value): 5 | self.value = value 6 | 7 | class Eggs(object): 8 | 9 | def __init__(self,value): 10 | self.value = value 11 | 12 | s = Spam(1) 13 | e = Eggs(2) 14 | 15 | if isinstance(s,Spam): 16 | print("s is Spam - correct") 17 | 18 | if isinstance(s,Eggs): 19 | print("s is Eggs - incorrect") 20 | 21 | if isinstance(e,Spam): 22 | print("e is Spam - incorrect") 23 | 24 | if isinstance(e,Eggs): 25 | print("e is Eggs - correct") 26 | 27 | if isinstance(1, int): 28 | print("int - correct") 29 | 30 | if isinstance(0.1, float): 31 | print("float - correct") 32 | 33 | if isinstance('str', str): 34 | print("str - correct") 35 | 36 | if isinstance([0], list): 37 | print("list - correct") 38 | 39 | if isinstance((0, 1), tuple): 40 | print("tuple - correct") 41 | 42 | if isinstance({'a': 1}, dict): 43 | print("dict - correct") 44 | -------------------------------------------------------------------------------- /tests/basic/super2.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class baseklass(object): 4 | 5 | def __init__(self,bval): 6 | self.bval = bval 7 | 8 | def describe(self,arg): 9 | print("baseklass.describe:"+self.bval+":"+str(arg)) 10 | 11 | def describe2(self,**kwargs): 12 | print("baseklass.describe2:"+self.bval+":"+kwargs['string']) 13 | print("baseklass.describe2:"+self.bval+":"+kwargs['string2']) 14 | kwargs['string2'] = kwargs['string3'] 15 | print("baseklass.describe2:"+self.bval+":"+kwargs['string2']) 16 | 17 | class klass(baseklass): 18 | 19 | def __init__(self,val,bval): 20 | baseklass.__init__(self,bval) 21 | self.val = val 22 | 23 | def describe(self): 24 | super(klass,self).describe(10) 25 | super(klass,self).describe2(string='somestring', string2='anystring', string3='changestring') 26 | print("klass.describe:"+self.val) 27 | 28 | def describe2(self,**kwargs): 29 | print("klass.describe2:"+self.bval+":"+kwargs['string']) 30 | 31 | k = klass("world","hello") 32 | k.describe() 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2017 NAITOH Jun 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in 11 | all copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /tests/basic/oo_inherit.py: -------------------------------------------------------------------------------- 1 | 2 | class bar(object): 3 | 4 | def __init__(self,name): 5 | self.name = name 6 | 7 | def setname(self,name): 8 | self.name = name 9 | 10 | class foo(bar): 11 | 12 | registered = [] 13 | 14 | def __init__(self,val,name): 15 | self.fval = val 16 | self.register(self) 17 | bar.__init__(self,name) 18 | 19 | def inc(self): 20 | self.fval += 1 21 | 22 | def msg(self,*varargs): 23 | txt = '' 24 | for arg in varargs: 25 | txt += str(arg) 26 | txt += "," 27 | return txt + self.name + " says:"+str(self.fval) 28 | 29 | @staticmethod 30 | def register(f): 31 | foo.registered.append(f) 32 | 33 | @staticmethod 34 | def printregistered(): 35 | for r in foo.registered: 36 | print(r.msg()) 37 | 38 | a = foo(10,'a') 39 | a.setname('aaa') 40 | b = foo(20,'b') 41 | c = foo(30,'c') 42 | 43 | a.inc() 44 | a.inc() 45 | c.inc() 46 | 47 | print(a.msg()) 48 | print(b.msg()) 49 | print(c.msg(2,3,4)) 50 | 51 | print("---") 52 | 53 | foo.printregistered() 54 | -------------------------------------------------------------------------------- /tests/numpy/ext_slice.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | def print_matrix(data): 4 | data_i = [] 5 | for i in list(data): 6 | data_j = [] 7 | for j in i: 8 | data_j.append(int("%d" % j)) 9 | data_i.append(data_j) 10 | print(data_i) 11 | 12 | def print_array(data): 13 | datas = [] 14 | for i in data: 15 | datas.append(int("%d" % i)) 16 | print(datas) 17 | 18 | x = np.asarray([[1,2,3],[4,5,6]]) 19 | print_matrix(x) 20 | 21 | """ 22 | x[0,:] 23 | """ 24 | print_array(x[0,:]) 25 | 26 | """ 27 | x[1,1:] 28 | """ 29 | y = x[1,1:] 30 | print_array(y) 31 | 32 | """ 33 | x[1,:2] 34 | """ 35 | x[1,:2] = 5 36 | print_array(y) 37 | print_matrix(x) 38 | 39 | x = np.asarray([[1,2,3],[4,5,6]]) 40 | print_matrix(x) 41 | 42 | """ 43 | x[:,0] 44 | """ 45 | print_array(x[:,0]) 46 | 47 | """ 48 | x[:,1] 49 | """ 50 | print_array(x[:,1]) 51 | 52 | x = np.asarray([[[1,2,3],[4,5,6]],[[11,12,13],[14,15,16]]]) 53 | #print_matrix(x) 54 | 55 | """ 56 | x[0,:] Not Support 57 | 58 | It is not supportable if the number of arguments and the number of dimensions are different. 59 | 60 | print_matrix(x[0,:]) 61 | """ 62 | 63 | """ 64 | x[0,1,:] 65 | """ 66 | print_array(x[0,1,:]) 67 | -------------------------------------------------------------------------------- /tests/basic/tuple2.py: -------------------------------------------------------------------------------- 1 | def tuple1(x): 2 | t = (x, x+1, x+2) 3 | a, b, c = t 4 | return a+b+c 5 | 6 | def tuple2(n): 7 | a = 0 8 | for i in (1, 2, n): 9 | a += i 10 | return a 11 | 12 | def tuple3(): 13 | a = (1, 3, 5, 4, 9, 1, 2, 3) 14 | return len(a) 15 | 16 | def tuple4(n): 17 | a = (1, 3, 3, 4, 9, 1, 2, 3) 18 | return a.count(n) 19 | 20 | def tuple5(n): 21 | a = (1, 3, 3, 4, 9, 1, 2, 3) 22 | return a.index(n) 23 | 24 | def tuple6(): 25 | a = (8, 9, 10, 11, 12, 13, 14) 26 | return a[2:4] 27 | 28 | def tuple7(): 29 | a = (8, 9, 10, 11, 12, 13, 14) 30 | return a[:4] 31 | 32 | def tuple8(): 33 | a = (8, 9, 10, 11, 12, 13, 14) 34 | return a[1:6:2] 35 | 36 | def tuple9(): 37 | a = (8, 9, 10, 11, 12, 13, 14) 38 | return a[:] 39 | 40 | def tuple10(): 41 | a = (8, 9, 10, 11, 12, 13, 14) 42 | return a[4:] 43 | 44 | 45 | print(tuple1(3)) 46 | print(tuple2(3)) 47 | print(tuple2(4)) 48 | print(tuple3()) 49 | print(tuple4(1)) 50 | print(tuple4(3)) 51 | print(tuple4(4)) 52 | print(tuple4(5)) 53 | print(tuple5(1)) 54 | print(tuple5(4)) 55 | print(tuple6()) 56 | print(tuple7()) 57 | print(tuple8()) 58 | print(tuple9()) 59 | print(tuple10()) 60 | -------------------------------------------------------------------------------- /tests/basic/oo_inherit_simple.py: -------------------------------------------------------------------------------- 1 | 2 | class bar(object): 3 | 4 | def __init__(self,name): 5 | self.name = name 6 | 7 | def setname(self,name): 8 | self.name = name 9 | 10 | class foo(bar): 11 | 12 | registered = [] 13 | 14 | def __init__(self,val,name): 15 | self.fval = val 16 | self.register(self) 17 | self.name = name 18 | 19 | def inc(self): 20 | self.fval += 1 21 | 22 | def msg(self, a=None, b=None, c=None): 23 | txt = '' 24 | varargs = a, b, c 25 | for arg in varargs: 26 | if arg is None: 27 | continue 28 | txt += str(arg) 29 | txt += "," 30 | return txt + self.name + " says:"+str(self.fval) 31 | 32 | @staticmethod 33 | def register(f): 34 | foo.registered.append(f) 35 | 36 | @staticmethod 37 | def printregistered(): 38 | for r in foo.registered: 39 | print(r.msg()) 40 | 41 | a = foo(10,'a') 42 | a.setname('aaa') 43 | b = foo(20,'b') 44 | c = foo(30,'c') 45 | 46 | a.inc() 47 | a.inc() 48 | c.inc() 49 | 50 | print(a.msg()) 51 | print(b.msg()) 52 | print(c.msg(2,3,4)) 53 | 54 | print("---") 55 | 56 | foo.printregistered() 57 | -------------------------------------------------------------------------------- /tests/basic/oo_inherit_simple_super1.py: -------------------------------------------------------------------------------- 1 | 2 | class bar(object): 3 | 4 | def __init__(self,name): 5 | self.name = name 6 | 7 | def setname(self,name): 8 | self.name = name 9 | 10 | class foo(bar): 11 | 12 | registered = [] 13 | 14 | def __init__(self,val,name): 15 | self.fval = val 16 | self.register(self) 17 | bar.__init__(self,name) 18 | 19 | def inc(self): 20 | self.fval += 1 21 | 22 | def msg(self, a=None, b=None, c=None): 23 | txt = '' 24 | varargs = a, b, c 25 | for arg in varargs: 26 | if arg is None: 27 | continue 28 | txt += str(arg) 29 | txt += "," 30 | return txt + self.name + " says:"+str(self.fval) 31 | 32 | @staticmethod 33 | def register(f): 34 | foo.registered.append(f) 35 | 36 | @staticmethod 37 | def printregistered(): 38 | for r in foo.registered: 39 | print(r.msg()) 40 | 41 | a = foo(10,'a') 42 | a.setname('aaa') 43 | b = foo(20,'b') 44 | c = foo(30,'c') 45 | 46 | a.inc() 47 | a.inc() 48 | c.inc() 49 | 50 | print(a.msg()) 51 | print(b.msg()) 52 | print(c.msg(2,3,4)) 53 | 54 | print("---") 55 | 56 | foo.printregistered() 57 | -------------------------------------------------------------------------------- /tests/basic/oo_inherit_simple_super3.py: -------------------------------------------------------------------------------- 1 | 2 | class bar(object): 3 | 4 | def __init__(self,name): 5 | self.name = name 6 | 7 | def setname(self,name): 8 | self.name = name 9 | 10 | class foo(bar): 11 | 12 | registered = [] 13 | 14 | def __init__(self,val,name): 15 | self.fval = val 16 | self.register(self) 17 | super().__init__(name) 18 | 19 | def inc(self): 20 | self.fval += 1 21 | 22 | def msg(self, a=None, b=None, c=None): 23 | txt = '' 24 | varargs = a, b, c 25 | for arg in varargs: 26 | if arg is None: 27 | continue 28 | txt += str(arg) 29 | txt += "," 30 | return txt + self.name + " says:"+str(self.fval) 31 | 32 | @staticmethod 33 | def register(f): 34 | foo.registered.append(f) 35 | 36 | @staticmethod 37 | def printregistered(): 38 | for r in foo.registered: 39 | print(r.msg()) 40 | 41 | a = foo(10,'a') 42 | a.setname('aaa') 43 | b = foo(20,'b') 44 | c = foo(30,'c') 45 | 46 | a.inc() 47 | a.inc() 48 | c.inc() 49 | 50 | print(a.msg()) 51 | print(b.msg()) 52 | print(c.msg(2,3,4)) 53 | 54 | print("---") 55 | 56 | foo.printregistered() 57 | -------------------------------------------------------------------------------- /tests/basic/oo_inherit_simple_super2.py: -------------------------------------------------------------------------------- 1 | 2 | class bar(object): 3 | 4 | def __init__(self,name): 5 | self.name = name 6 | 7 | def setname(self,name): 8 | self.name = name 9 | 10 | class foo(bar): 11 | 12 | registered = [] 13 | 14 | def __init__(self,val,name): 15 | self.fval = val 16 | self.register(self) 17 | super(foo, self).__init__(name) 18 | 19 | def inc(self): 20 | self.fval += 1 21 | 22 | def msg(self, a=None, b=None, c=None): 23 | txt = '' 24 | varargs = a, b, c 25 | for arg in varargs: 26 | if arg is None: 27 | continue 28 | txt += str(arg) 29 | txt += "," 30 | return txt + self.name + " says:"+str(self.fval) 31 | 32 | @staticmethod 33 | def register(f): 34 | foo.registered.append(f) 35 | 36 | @staticmethod 37 | def printregistered(): 38 | for r in foo.registered: 39 | print(r.msg()) 40 | 41 | a = foo(10,'a') 42 | a.setname('aaa') 43 | b = foo(20,'b') 44 | c = foo(30,'c') 45 | 46 | a.inc() 47 | a.inc() 48 | c.inc() 49 | 50 | print(a.msg()) 51 | print(b.msg()) 52 | print(c.msg(2,3,4)) 53 | 54 | print("---") 55 | 56 | foo.printregistered() 57 | -------------------------------------------------------------------------------- /tests/basic/for_in.py: -------------------------------------------------------------------------------- 1 | # iterating over a list 2 | print('-- list --') 3 | a = [1,2,3,4,5] 4 | for x in a: 5 | print(x) 6 | 7 | # iterating over a tuple 8 | print('-- tuple else case --') 9 | a = ('cats','dogs','squirrels') 10 | for x in a: 11 | print(x) 12 | else: 13 | print('ok') 14 | 15 | print('-- tuple else break case --') 16 | for x in a: 17 | print(x) 18 | if x == 'squirrels': 19 | break 20 | else: 21 | print('ok') 22 | 23 | # iterating over a dictionary 24 | # sort order in python is undefined, so need to sort the results 25 | # explictly before comparing output 26 | 27 | print('-- dict keys --') 28 | a = {'a':1,'b':2,'c':3 } 29 | 30 | keys = [] 31 | for x in a.keys(): 32 | keys.append(x) 33 | 34 | keys.sort() 35 | for k in keys: 36 | print(k) 37 | 38 | print('-- dict values --') 39 | values = list() 40 | for v in a.values(): 41 | values.append(v) 42 | 43 | values.sort() 44 | for v in values: 45 | print(v) 46 | 47 | items = dict() 48 | for k, v in a.items(): 49 | items[k] = v 50 | 51 | print('-- dict item --') 52 | print(items['a']) 53 | print(items['b']) 54 | print(items['c']) 55 | 56 | # iterating over a string 57 | print('-- string --') 58 | a = 'defabc' 59 | for x in a: 60 | print(x) 61 | 62 | -------------------------------------------------------------------------------- /tests/numpy/arg_max_min.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_matrix(data): 5 | data_i = [] 6 | for i in list(data): 7 | data_j = [] 8 | for j in i: 9 | data_j.append(int("%d" % j)) 10 | data_i.append(data_j) 11 | print(data_i) 12 | 13 | def print_array(data): 14 | datas = [] 15 | for i in data: 16 | datas.append(int("%d" % i)) 17 | print(datas) 18 | 19 | a = np.asarray([[1,2,3],[4,5,6]]) 20 | print_matrix(a) 21 | 22 | x = np.argmax(a) 23 | print(x) 24 | 25 | """ 26 | 27 | Python argmax : [1, 1, 1] 28 | Ruby max_index : [3, 4, 5] (flat Array index) 29 | """ 30 | x = np.argmax(a, axis=0) 31 | print_array(x) 32 | 33 | """ 34 | 35 | Python argmax : [2, 2] 36 | Ruby max_index : [2, 5] (flat Array index) 37 | """ 38 | x = np.argmax(a, axis=1) 39 | print_array(x) 40 | 41 | x = np.argmin(a) 42 | print(x) 43 | 44 | """ 45 | 46 | Python argmax : [0, 0, 0] 47 | Ruby max_index : [0, 1, 2] (flat Array index) 48 | """ 49 | x = np.argmin(a, axis=0) 50 | print_array(x) 51 | 52 | """ 53 | 54 | Python argmax : [0, 0] 55 | Ruby max_index : [0, 3] (flat Array index) 56 | """ 57 | x = np.argmin(a, axis=1) 58 | print_array(x) 59 | 60 | -------------------------------------------------------------------------------- /tests/deep-learning-from-scratch/LICENSE.md: -------------------------------------------------------------------------------- 1 | This folder contains sample code for "https://github.com/oreilly-japan/deep-learning-from-scratch". 2 | For copyright and license, please read the following description. 3 | 4 | -- 5 | The MIT License (MIT) 6 | 7 | Copyright (c) 2016 Koki Saitoh 8 | 9 | Permission is hereby granted, free of charge, to any person obtaining a copy 10 | of this software and associated documentation files (the "Software"), to deal 11 | in the Software without restriction, including without limitation the rights 12 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 13 | copies of the Software, and to permit persons to whom the Software is 14 | furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in all 17 | copies or substantial portions of the Software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 20 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 21 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 22 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 23 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 24 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 25 | SOFTWARE. 26 | -------------------------------------------------------------------------------- /tests/basic/list2.py: -------------------------------------------------------------------------------- 1 | def list1(n): 2 | a = [] 3 | a.append(1) 4 | a.append(2) 5 | a.append(3) 6 | a.append(n) 7 | return a[0] + a[1] + a[2] + a[3] 8 | 9 | def list2(): 10 | a = list(range(5)) 11 | return str(a) 12 | 13 | def list3(): 14 | a = list(range(5)) 15 | a[0] = 5 16 | a[4] = 0 17 | return str(a) 18 | 19 | def list4(): 20 | a = [8, 9, 10, 11, 12, 13, 14] 21 | return a[2:4] 22 | 23 | def list5(): 24 | a = [8, 9, 10, 11, 12, 13, 14] 25 | return a[:4] 26 | 27 | def list6(): 28 | a = [8, 9, 10, 11, 12, 13, 14] 29 | return a[1:6:2] 30 | 31 | def list7(): 32 | a = [8, 9, 10, 11, 12, 13, 14] 33 | return a[:] 34 | 35 | def list8(): 36 | a = [8, 9, 10, 11, 12, 13, 14] 37 | return a[::] 38 | 39 | def list9(): 40 | a = [8, 9, 10, 11, 12, 13, 14] 41 | return a[4:] 42 | 43 | def list10(): 44 | a = [8, 9, 10, 11, 12, 13, 14] 45 | return a[::2] 46 | 47 | def list11(): 48 | a = [8, 9, 10, 11, 12, 13, 14] 49 | return a[1::2] 50 | 51 | def list12(): 52 | a = [8, 9, 10, 11, 12, 13, 14] 53 | return a[:4:2] 54 | 55 | print(list1(4)) 56 | print(list1(5)) 57 | print(list2()) 58 | print(list3()) 59 | print(list4()) 60 | print(list5()) 61 | print(list6()) 62 | print(list7()) 63 | print(list8()) 64 | print(list9()) 65 | print(list10()) 66 | print(list11()) 67 | print(list12()) 68 | -------------------------------------------------------------------------------- /tests/numpy/max_min.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | import numpy as np 3 | 4 | def print_matrix(data): 5 | data_i = [] 6 | for i in list(data): 7 | data_j = [] 8 | for j in i: 9 | data_j.append(j) 10 | data_i.append(data_j) 11 | print(data_i) 12 | 13 | def print_array(data): 14 | datas = [] 15 | for i in data: 16 | datas.append(i) 17 | print(datas) 18 | 19 | 20 | x = np.array([2,3,4]) 21 | print_array(x) 22 | 23 | z = np.array([[2,3,6],[3,4,5]]) 24 | print_matrix(z) 25 | 26 | """ 27 | max 28 | """ 29 | y = x.max() 30 | print(y) 31 | y = np.max([2, 3, 4]) 32 | print(y) 33 | 34 | """ 35 | amax 36 | """ 37 | y = np.amax([2, 3, 4]) 38 | print(y) 39 | 40 | """ 41 | max axis=0 42 | """ 43 | y = z.max(axis=0) 44 | print_array(y) 45 | 46 | """ 47 | max axis=1 48 | """ 49 | y = np.max([[2,3,6],[3,4,5]], axis=1) 50 | print_array(y) 51 | 52 | """ 53 | min 54 | """ 55 | y = x.min() 56 | print(y) 57 | y = np.min([2, 3, 4]) 58 | print(y) 59 | 60 | """ 61 | amin 62 | """ 63 | y = np.amin([2, 3, 4]) 64 | print(y) 65 | 66 | """ 67 | min axis=0 68 | """ 69 | y = z.min(axis=0) 70 | print_array(y) 71 | 72 | """ 73 | min axis=1 74 | """ 75 | y = np.min([[2,3,6],[3,4,5]], axis=1) 76 | print_array(y) 77 | 78 | """ 79 | max axis=0 keepdims 80 | """ 81 | y = np.max([[2,3,6],[3,4,5]], axis=0, keepdims=True) 82 | print_matrix(y) 83 | 84 | """ 85 | min keepdims 86 | """ 87 | y = np.min([[2,3,6],[3,4,5]], keepdims=True) 88 | print_matrix(y) 89 | -------------------------------------------------------------------------------- /testtools/env_tests.py: -------------------------------------------------------------------------------- 1 | """\ 2 | Includes tests that check the setup for the tests. 3 | If the library is compiled and if there is a ruby interpreter. 4 | """ 5 | import os 6 | import sys 7 | if sys.version_info < (2, 7): 8 | import unittest2 as unittest 9 | else: 10 | import unittest 11 | import tempfile 12 | class EnviromentTest(unittest.TestCase): 13 | "Test case that makes sure that the environment is up and working" 14 | def reportProgres(self): 15 | """Should be overloaded by the test result class""" 16 | 17 | def stop(self): 18 | """Should be overloaded by the test result class""" 19 | 20 | def runTest(self): 21 | """The actual test goes here.""" 22 | if os.system( 23 | "ruby --help > %s" % 24 | os.path.join( 25 | tempfile.gettempdir(), 26 | tempfile.gettempprefix() 27 | ) 28 | ): 29 | self.stop() 30 | raise RuntimeError("""Can't find the "ruby" command.""") 31 | self.reportProgres() 32 | if not os.path.exists("py2rb/builtins/module.rb"): 33 | self.stop() 34 | raise RuntimeError("""Can't find the "py2rb/builtins/module.rb" command.""") 35 | if not os.path.exists("py2rb/builtins/require.rb"): 36 | self.stop() 37 | raise RuntimeError("""Can't find the "py2rb/builtins/require.rb" command.""") 38 | self.reportProgres() 39 | 40 | def __str__(self): 41 | return 'Looking for "ruby", "py2rb/builtins/module.rb", "py2rb/builtins/require.rb" [3]:' 42 | 43 | 44 | -------------------------------------------------------------------------------- /run_tests.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | 3 | import optparse 4 | import testtools.runner 5 | import testtools.util 6 | import testtools.tests 7 | 8 | def main(): 9 | option_parser = optparse.OptionParser( 10 | usage="%prog [options] [filenames]", 11 | description="py2rb unittests script." 12 | ) 13 | option_parser.add_option( 14 | "-a", 15 | "--run-all", 16 | action="store_true", 17 | dest="run_all", 18 | default=False, 19 | help="run all tests (including the known-to-fail)" 20 | ) 21 | option_parser.add_option( 22 | "-x", 23 | "--no-error", 24 | action="store_true", 25 | dest="no_error", 26 | default=False, 27 | help="ignores error( don't display them after tests)" 28 | ) 29 | options, args = option_parser.parse_args() 30 | runner = testtools.runner.Py2RbTestRunner(verbosity=2) 31 | results = None 32 | if options.run_all: 33 | results = runner.run(testtools.tests.ALL) 34 | elif args: 35 | results = runner.run(testtools.tests.get_tests(args)) 36 | else: 37 | results = runner.run(testtools.tests.NOT_KNOWN_TO_FAIL) 38 | if not options.no_error and results.errors: 39 | print 40 | print("errors:") 41 | print(" (use -x to skip this part)") 42 | for test, error in results.errors: 43 | print 44 | print("*", str(test), "*") 45 | print(error) 46 | if results.errors or results.failures: 47 | exit(1) 48 | 49 | if __name__ == "__main__": 50 | main() 51 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | """ 2 | A code translator using AST from Python to Ruby. 3 | This is basically a NodeVisitor with ruby output. 4 | See: 5 | https://docs.python.org/3/library/ast.html 6 | """ 7 | 8 | from setuptools import setup, find_packages 9 | from codecs import open 10 | from os import path 11 | 12 | here = path.abspath(path.dirname(__file__)) 13 | 14 | with open(path.join(here, 'README.rst'), encoding='utf-8') as f: 15 | long_description = f.read() 16 | 17 | setup( 18 | name='py2rb', 19 | version='0.1.2', 20 | description='A code translator using AST from Python to Ruby', 21 | long_description=long_description, 22 | url='https://github.com/naitoh/py2rb', 23 | author='NAITOH Jun', 24 | author_email='naitoh@gmail.com', 25 | license='MIT', 26 | classifiers=[ 27 | 'Development Status :: 4 - Beta', 28 | 'Intended Audience :: Developers', 29 | 'Topic :: Software Development', 30 | 'License :: OSI Approved :: MIT License', 31 | 'Programming Language :: Python :: 3', 32 | 'Programming Language :: Python :: 3.5', 33 | 'Programming Language :: Python :: 3.6', 34 | ], 35 | keywords='python ruby', 36 | packages=['py2rb'], 37 | package_data = { 38 | 'py2rb': ['modules/lib.yaml', 39 | 'modules/numpy.yaml', 40 | 'modules/unittest.yaml', 41 | 'builtins/require.rb', 42 | 'builtins/module.rb', ] 43 | }, 44 | install_requires=[ 45 | 'pyyaml', 46 | 'numpy', 47 | ], 48 | entry_points={ 49 | 'console_scripts': [ 50 | 'py2rb=py2rb:main' 51 | ] 52 | } 53 | ) 54 | -------------------------------------------------------------------------------- /testtools/known_to_fail.py: -------------------------------------------------------------------------------- 1 | """lists all the tests that are known to fail""" 2 | KNOWN_TO_FAIL = [ 3 | "tests/basic/nestedclass.py", 4 | "tests/basic/listcomp2.py", 5 | "tests/basic/del_local.py", 6 | "tests/basic/valueerror.py", 7 | "tests/basic/del_global.py", 8 | "tests/basic/generator.py", 9 | "tests/basic/default.py", # Can't call local valiable in arguments. 10 | "tests/basic/for_in2.py", # Can't support dict (not use items()/keys()/values()) case. 11 | "tests/basic/hasattr2.py", 12 | "tests/basic/oo_super.py", # Multiple inheritance can not be supported 13 | "tests/basic/oo_diamond.py", # Multiple inheritance can not be supported 14 | "tests/basic/oo_static_inherit2.py", # A class method of the lowercase name class is unsupported. 15 | "tests/basic/vars.py", # Can't match variable scope 16 | "tests/basic/vars2.py", # Can't match variable scope 17 | "tests/basic/yield.py", # Difficult 18 | 19 | "tests/functions/sort_cmp.py", 20 | "tests/functions/sort23.py", 21 | 22 | "tests/decorator/class.py", 23 | "tests/decorator/decorator.py", 24 | 25 | "tests/lists/reduce.py", 26 | 27 | "tests/libraries/xmlwriter.py", 28 | 29 | "tests/modules/import_diamond.py", 30 | "tests/modules/module_name.py", 31 | "tests/modules/rng.py", 32 | 33 | "tests/strings/other_strings.py", # not support 34 | "tests/strings/replace2.py", # not support 3rd argument. 35 | "tests/strings/string_format_efg.py", 36 | "tests/strings/string_format_o.py", # not support 37 | "tests/strings/string_format_x.py", # not support 38 | 39 | "tests/numpy/arg_max_min.py", # Not Compatible with axis case 40 | ] 41 | 42 | 43 | -------------------------------------------------------------------------------- /tests/unittest/assertRaises.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | class MyException(Exception): 4 | pass 5 | 6 | class MyException2(Exception): 7 | pass 8 | 9 | class MyException3(Exception): 10 | pass 11 | 12 | class Foo: 13 | def test(self): 14 | raise MyException 15 | 16 | class Bar: 17 | def test(self, a, b, c=1, d=2): 18 | if a != 'a': 19 | raise MyException 20 | 21 | if c == 1: 22 | raise MyException2 23 | else: 24 | raise MyException3 25 | 26 | def test(a, b, c=1, d=2): 27 | if a != 'a': 28 | raise MyException 29 | 30 | if c == 1: 31 | raise MyException2 32 | else: 33 | raise MyException3 34 | 35 | def test2(): 36 | raise MyException 37 | 38 | class TestRunnable(unittest.TestCase): 39 | 40 | def bar(self): 41 | assert False 42 | 43 | def test_runnable(self): 44 | ''' NameError: name 'foo' is not defined ''' 45 | with self.assertRaises(NameError): 46 | foo 47 | 48 | foo = Foo() 49 | self.assertRaises(MyException, foo.test) 50 | 51 | bar = Bar() 52 | self.assertRaises(MyException, bar.test,'aa', 'b') 53 | self.assertRaises(MyException2, bar.test,'a', 'b') 54 | self.assertRaises(MyException2, bar.test,'a', 'b', d=20) 55 | self.assertRaises(MyException3, bar.test,'a', 'b', c=10, d=20) 56 | 57 | self.assertRaises(MyException, test, 'aa', 'b', c=10, d=20) 58 | self.assertRaises(MyException2, test, 'a', 'b') 59 | self.assertRaises(MyException3, test, 'a', 'b', c=10, d=20) 60 | self.assertRaises(MyException, test2) 61 | self.assertRaises(AssertionError, self.bar) 62 | 63 | class TestRunnable2(TestRunnable): 64 | 65 | def test_runnable2(self): 66 | self.assertRaises(AssertionError, self.bar) 67 | 68 | unittest.main() 69 | -------------------------------------------------------------------------------- /py2rb/modules/lib.yaml: -------------------------------------------------------------------------------- 1 | # 2 | # Usage 3 | # -------- 4 | # Python library name: 5 | # Ruby library name: # import weakref => require 'weakref' 6 | # id: Ruby module name 7 | # e.g. id: numo/narray # import numpy as np => require 'numo/narray' 8 | # 9 | # order_methods_with_bracket: 10 | # Python method name: Ruby method name # Case independent of the number of arguments. 11 | # 12 | # e.g. os.path.dirnam(name) => File.dirname(name) 13 | # 14 | # reverse_methods: 15 | # arg_count_1: Ruby method name # Case with only one argument. 16 | # arg_count_2: Ruby method name # Case with two arguments. 17 | # e.g. heapq.heappop(list) => list.pop 18 | # e.g. heapq.heappush(list, item) => list.push(item) 19 | # 20 | 21 | os: 22 | id: 23 | order_methods_with_bracket: 24 | path.dirname: 'File.dirname' 25 | path.basename: 'File.basename' 26 | path.join: 'File.join' 27 | walk: 'PyLib.walk' 28 | 29 | copy: 30 | id: 31 | reverse_methods: 32 | copy: 'dup' # copy(foo) => (foo).dup 33 | 34 | six: 35 | id: 36 | reverse_methods: 37 | itervalues: 'values' 38 | iteritems: 'to_a' 39 | attribute_map: 40 | PY2: 'false' 41 | PY3: 'true' 42 | integer_types: '[Integer]' 43 | range_map: 44 | moves.range: '' 45 | 46 | functools: 47 | id: 48 | 49 | collections: 50 | id: 51 | dict_map: 52 | OrderedDict: '' 53 | 54 | warnings: 55 | id: 56 | order_methods_with_bracket: 57 | warn: 'warn' 58 | 59 | weakref: 60 | id: weakref 61 | order_methods_with_bracket: 62 | ref: 'WeakRef.new' 63 | 64 | random: 65 | id: 66 | order_methods_with_bracket: 67 | random: 'Random.rand' 68 | 69 | # Provisional implementation. 70 | heapq: 71 | id: 72 | reverse_methods: 73 | heappush: 74 | arg_count_2: 'push' 75 | heappop: 76 | arg_count_1: 'pop' 77 | 78 | # Provisional implementation. 79 | traceback: 80 | id: 81 | reverse_methods: 82 | format_list: to_a 83 | 84 | -------------------------------------------------------------------------------- /testtools/runner.py: -------------------------------------------------------------------------------- 1 | """\ 2 | The special runners that look for progress in a test and have nicer output than 3 | the original.""" 4 | import sys 5 | if sys.version_info < (2, 7): 6 | import unittest2 as unittest 7 | else: 8 | import unittest 9 | 10 | class Py2RbTestResult(unittest.TestResult): 11 | """Test result class, handling all the results reported by the tests""" 12 | 13 | def __init__(self, *a, **k): 14 | import testtools.writer 15 | super(Py2RbTestResult, self).__init__(*a, **k) 16 | self.__writer = testtools.writer.Writer(a[0]) 17 | self.__faild = False 18 | self.__color = "" 19 | self.__state = "" 20 | 21 | def startTest(self, test): 22 | super(Py2RbTestResult, self).startTest(test) 23 | test.reportProgres = self.addProgress 24 | test.stop = self.stop 25 | self.__writer.write(str(test)) 26 | self.__state = "[Error]" 27 | self.__color = "Red" 28 | 29 | def stopTest(self, test): 30 | super(Py2RbTestResult, self).stopTest(test) 31 | self.__writer.write(self.__state, align="right", color=self.__color) 32 | 33 | def addProgress(self): 34 | """Part of tests done""" 35 | self.__writer.write(".") 36 | 37 | def addSuccess(self, test): 38 | super(Py2RbTestResult, self).addSuccess(test) 39 | self.__color = "Green" 40 | self.__state = "[OK]" 41 | 42 | def addUnexpectedSuccess(self, test): 43 | super(Py2RbTestResult, self).addUnexpectedSuccess(test) 44 | self.__color = "Green" 45 | self.__state = "should fail but [OK]" 46 | 47 | def addExpectedFailure(self, test, err): 48 | super(Py2RbTestResult, self).addExpectedFailure(test, err) 49 | self.__color = "Purple" 50 | self.__state = "known to [FAIL]" 51 | 52 | def addFailure(self, test, err): 53 | super(Py2RbTestResult, self).addFailure(test, err) 54 | self.__color = "Red" 55 | self.__state = "[FAIL]" 56 | 57 | def stopTestRun(self): 58 | super(Py2RbTestResult, self).stopTestRun() 59 | self.__writer.write("\n") 60 | 61 | class Py2RbTestRunner(unittest.TextTestRunner): 62 | """Test runner with Py2RbTestResult as result class""" 63 | resultclass = Py2RbTestResult 64 | 65 | -------------------------------------------------------------------------------- /tests/libraries/xmlwriter.py: -------------------------------------------------------------------------------- 1 | 2 | class StringWriter(object): 3 | 4 | def __init__(self): 5 | self.contents = '' 6 | 7 | def write(self,text): 8 | self.contents += text 9 | 10 | def getContents(self): 11 | return self.contents 12 | 13 | class XmlWriter(object): 14 | 15 | class Node(object): 16 | 17 | def __init__(self): 18 | pass 19 | 20 | class TextNode(Node): 21 | 22 | def __init__(self,text): 23 | self.text = text 24 | 25 | def write(self,writer,indent): 26 | writer.write(self.text) 27 | 28 | class Element(Node): 29 | 30 | def __init__(self,tag): 31 | self.tag = tag 32 | self.children = [] 33 | self.attributes = {} 34 | self.hastext = False 35 | 36 | def addElement(self,tag): 37 | child = XmlWriter.Element(tag) 38 | self.children.append(child) 39 | return child 40 | 41 | def addTextNode(self,text): 42 | child = XmlWriter.TextNode(text) 43 | self.children.append(child) 44 | self.hastext = True 45 | return child 46 | 47 | def addAttribute(self,name,value): 48 | self.attributes[name] = value 49 | 50 | def write(self,writer,indent): 51 | if indent > 0: 52 | XmlWriter.indent(writer,indent) 53 | writer.write("<"+self.tag) 54 | for k in self.attributes: 55 | writer.write(" "+k+'="'+self.attributes[k]+'"') 56 | if len(self.children) == 0: 57 | writer.write(" />") 58 | return 59 | writer.write(">") 60 | for c in self.children: 61 | c.write(writer,indent+1) 62 | if not self.hastext: 63 | XmlWriter.indent(writer,indent) 64 | writer.write("") 65 | 66 | @staticmethod 67 | def indent(writer,indent): 68 | writer.write("\n") 69 | for x in range(0,indent): 70 | writer.write(" ") 71 | 72 | def createRoot(self,tag): 73 | self.root = self.Element(tag) 74 | return self.root 75 | 76 | def write(self,writer): 77 | self.root.write(writer,0) 78 | 79 | 80 | if __name__ == '__main__': 81 | w = XmlWriter() 82 | r = w.createRoot("foo") 83 | r1 = r.addElement("r1") 84 | r1.addAttribute("spam","eggs") 85 | r2 = r1.addElement("r2") 86 | r2.addAttribute("eggs","spam") 87 | r2.addTextNode("This is some text") 88 | s = StringWriter() 89 | w.write(s) 90 | print(s.getContents()) 91 | 92 | -------------------------------------------------------------------------------- /py2rb/formater.py: -------------------------------------------------------------------------------- 1 | """ A formater module that keeps trac of indentation 2 | """ 3 | class Formater(object): 4 | """ 5 | A very simple code formater that handles efficient concatenation and indentation of lines. 6 | """ 7 | 8 | def __init__(self, indent_string=" "): 9 | self.__buffer = [] 10 | self.__indentation = 0 11 | self.__indent_string = indent_string 12 | self.__indent_temp = "" 13 | self.__string_buffer = "" 14 | 15 | def dedent(self): 16 | """ 17 | Subtracts one indentation level. 18 | """ 19 | self.__indentation -= 1 20 | self.__indent_temp = self.__indent_string*self.__indentation 21 | 22 | def indent(self): 23 | """ 24 | Adds one indentation level. 25 | """ 26 | self.__indentation += 1 27 | self.__indent_temp = self.__indent_string*self.__indentation 28 | 29 | def indent_string(self): 30 | """ 31 | return current indentation string. 32 | """ 33 | return self.__indent_temp 34 | 35 | def clear(self): 36 | self.__buffer = [] 37 | 38 | def write(self, text, indent=True, newline=True): 39 | """ 40 | Writes the string text to the buffer with indentation and a newline if not specified otherwise. 41 | """ 42 | if text == None: 43 | raise RubyError("Convert Error.") 44 | if indent: 45 | self.__buffer.append(self.__indent_temp) 46 | self.__buffer.append(text) 47 | if newline: 48 | self.__buffer.append("\n") 49 | 50 | def read(self, size=None): 51 | """ 52 | Returns a string representation of the buffer. 53 | """ 54 | if size == None: 55 | text = self.__string_buffer + "".join(self.__buffer) 56 | self.__buffer = [] 57 | self.__string_buffer = "" 58 | return text 59 | else: 60 | if len(self.__string_buffer) < size: 61 | self.__string_buffer += "".join(self.__buffer) 62 | self.__buffer = [] 63 | if len(self.__string_buffer) < size: 64 | text, self.__string_buffer = self.__string_buffer, "" 65 | return text 66 | else: 67 | text, self.__string_buffer = self.__string_buffer[:size], \ 68 | self.__string_buffer[size:] 69 | return text 70 | else: 71 | text, self.__string_buffer = self.__string_buffer[:size], \ 72 | self.__string_buffer[size:] 73 | return text 74 | 75 | def capitalize(self, text): 76 | """ 77 | Returns a capitalize string. 78 | """ 79 | if text == '': 80 | return '' 81 | return text[0].upper() + text[1:] 82 | 83 | -------------------------------------------------------------------------------- /testtools/tests.py: -------------------------------------------------------------------------------- 1 | """module which finds tests from the test directory and converts them to 2 | the unittest framework classes.""" 3 | 4 | import testtools.env_tests as env_tests 5 | import testtools.known_to_fail as known_to_fail 6 | import testtools.util as util 7 | import unittest 8 | import glob 9 | import os 10 | 11 | def create_cases(): 12 | """Helper function to find all tests in the test folders 13 | and wrapping them into the correct test class""" 14 | 15 | test_cases = unittest.TestSuite() 16 | test_cases.addTest( 17 | unittest.TestLoader().loadTestsFromTestCase( 18 | env_tests.EnviromentTest 19 | ) 20 | ) 21 | 22 | failing_test_cases = unittest.TestSuite() 23 | 24 | test_paths = glob.glob("tests/test_*.py") 25 | test_paths.sort() 26 | for test_path in test_paths: 27 | test_cases.addTest( 28 | unittest.TestLoader().loadTestsFromTestCase( 29 | util.compile_file_test(test_path, os.path.basename(test_path)) 30 | ) 31 | ) 32 | 33 | test_paths = glob.glob("tests/test_*.rb") 34 | test_paths.sort() 35 | for test_path in test_paths: 36 | test_cases.addTest( 37 | unittest.TestLoader().loadTestsFromTestCase( 38 | util.run_with_stdlib(test_path, os.path.basename(test_path)) 39 | ) 40 | ) 41 | 42 | test_paths = glob.glob("tests/*/*.py") 43 | test_paths.sort() 44 | for test_path in test_paths: 45 | if ( 46 | test_path.replace("\\","/") not 47 | in known_to_fail.KNOWN_TO_FAIL 48 | ): 49 | test_cases.addTest( 50 | unittest.TestLoader().loadTestsFromTestCase( 51 | util.compile_and_run_file_test( 52 | test_path, 53 | os.path.basename(test_path) 54 | ) 55 | ) 56 | ) 57 | else: 58 | failing_test_cases.addTest( 59 | unittest.TestLoader().loadTestsFromTestCase( 60 | util.compile_and_run_file_failing_test( 61 | test_path, 62 | os.path.basename(test_path) 63 | ) 64 | ) 65 | ) 66 | return test_cases , failing_test_cases 67 | 68 | NOT_KNOWN_TO_FAIL, KNOWN_TO_FAIL = create_cases() 69 | ALL = unittest.TestSuite((NOT_KNOWN_TO_FAIL, KNOWN_TO_FAIL)) 70 | 71 | def get_tests(names): 72 | """filters out all tests that don't exist in names and 73 | adds them to a new test suite""" 74 | def flatten(itr): 75 | """tries to flatten out a suite to the individual tests""" 76 | import itertools 77 | try: 78 | return itertools.chain.from_iterable(flatten(item) for item in iter) 79 | except TypeError: 80 | return itertools.chain(*itr) 81 | 82 | return_suite = unittest.TestSuite() 83 | return_suite.addTest( 84 | unittest.TestLoader().loadTestsFromTestCase( 85 | env_tests.EnviromentTest 86 | ) 87 | ) 88 | for suite in flatten(iter(ALL)): 89 | test_name = str(suite._tests[0]) 90 | if any(True for name in names if name in test_name): 91 | return_suite.addTest(suite) 92 | return return_suite 93 | 94 | def load_tests(_loader, standard_tests, _search_pattern): 95 | """function called by the unittest framework to find tests in a module""" 96 | suite = standard_tests 97 | suite.addTests(ALL) 98 | return suite 99 | -------------------------------------------------------------------------------- /testtools/writer.py: -------------------------------------------------------------------------------- 1 | """module with the Writer class that helps write colorful output""" 2 | 3 | class Writer(object): 4 | "Class which helps to print in color and with alignment and width" 5 | 6 | color_templates = ( 7 | ("Black" , "0;30"), 8 | ("Red" , "0;31"), 9 | ("Green" , "0;32"), 10 | ("Brown" , "0;33"), 11 | ("Blue" , "0;34"), 12 | ("Purple" , "0;35"), 13 | ("Cyan" , "0;36"), 14 | ("LightGray" , "0;37"), 15 | ("DarkGray" , "1;30"), 16 | ("LightRed" , "1;31"), 17 | ("LightGreen" , "1;32"), 18 | ("Yellow" , "1;33"), 19 | ("LightBlue" , "1;34"), 20 | ("LightPurple" , "1;35"), 21 | ("LightCyan" , "1;36"), 22 | ("White" , "1;37"), ) 23 | 24 | colors = dict(color_templates) 25 | 26 | c_normal = '\033[0m' 27 | 28 | c_color = '\033[%sm' 29 | 30 | def __init__(self, in_file = None): 31 | import sys 32 | self._line_wrap = False 33 | self._write_pos = 0 34 | self._file = in_file or sys.stdout 35 | #self._file = sys.stdout 36 | if not (hasattr(self._file, 'isatty') and self._file.isatty()): 37 | # the stdout is not a terminal, this for example happens if the 38 | # output is piped to less, e.g. "bin/test | less". In this case, 39 | # the terminal control sequences would be printed verbatim, so 40 | # don't use any colors. 41 | self.write = self.normal_write 42 | elif sys.platform != "win32": 43 | # We are on *nix system we can use ansi 44 | self.write = self.ansi_write 45 | else: 46 | try: 47 | import colorama 48 | colorama.init(wrap=False) 49 | self._file = colorama.AnsiToWin32(self._file).stream 50 | self.write = self.ansi_write 51 | except ImportError: 52 | self.write = self.normal_write 53 | 54 | def write(self, text, color="", align="left", width=80): 55 | """ 56 | Prints a text on the screen. 57 | 58 | It uses file.write(), so no readline library is necessary. 59 | 60 | color ... choose from the colors below, "" means default color 61 | align ... left/right, left is a normal print, right is aligned on the 62 | right hand side of the screen, filled with " " if necessary 63 | width ... the screen width 64 | """ 65 | 66 | def normal_write(self, text, color="", align="left", width=80): 67 | "Ignores color but uses alignment and width" 68 | _color = color 69 | if align == "right": 70 | if self._write_pos + len(text) > width: 71 | # we don't fit on the current line, create a new line 72 | self.write("\n") 73 | self.write(" " * (width - self._write_pos - len(text))) 74 | 75 | if self._line_wrap: 76 | if text != "" and text[0] != "\n": 77 | self._file.write("\n") 78 | 79 | self._file.write(text) 80 | self._file.flush() 81 | 82 | next_new_line = text.rfind("\n") 83 | 84 | if next_new_line == -1: 85 | self._write_pos += len(text) 86 | else: 87 | self._write_pos = len(text) - next_new_line - 1 88 | self._line_wrap = self._write_pos >= width 89 | self._write_pos %= width 90 | 91 | 92 | def ansi_write(self, text, color="", align="left", width=80): 93 | "Writes with color, alignment and width" 94 | try: 95 | return self.normal_write( 96 | text=( 97 | "%s%s%s" % ( 98 | self.c_color % self.colors[color], 99 | text, 100 | self.c_normal 101 | ) 102 | if color in self.colors 103 | else text 104 | ), 105 | color=color, 106 | align=align, 107 | width=width 108 | ) 109 | except AssertionError: 110 | return self.normal_write( 111 | text=text, 112 | color=color, 113 | align=align, 114 | width=width 115 | ) 116 | -------------------------------------------------------------------------------- /tests/test_builtins.rb: -------------------------------------------------------------------------------- 1 | # TESTS for the py2rb/builtins/module.rb module 2 | 3 | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..')) 4 | require 'test/unit' 5 | require 'module' 6 | 7 | class PyBultinsTest < Test::Unit::TestCase 8 | using PythonZipEx 9 | def test_zip_p 10 | vals = [[[[0]], [0]], 11 | [[[0,5]], [0], [5]], 12 | [[[0,5],[1,6]], [0,1], [5,6]], 13 | [[[0,5],[1,6],[2,7]], [0,1,2],[5,6,7]], 14 | [[[0,5,8],[1,6,9]], [0,1], [5,6], [8,9]]] 15 | vals.each{|expect, base, second, third| 16 | if !third.nil? 17 | ret = zip_p(base, second, third) 18 | elsif !second.nil? 19 | ret = zip_p(base, second) 20 | else 21 | ret = zip_p(base) 22 | end 23 | assert_equal expect, ret, "base:#{base}, second:#{second}" 24 | } 25 | end 26 | 27 | using PythonIsBoolEx 28 | def test_is_bool_true 29 | vals = [1, true, -1, 'a', [1], {a: 1}] 30 | vals.each{|val| 31 | ret = is_bool(val) 32 | assert_equal true, ret, val 33 | } 34 | end 35 | 36 | def test_is_bool_false 37 | vals = [nil, false, 0, [], '', {}] 38 | vals.each{|val| 39 | ret = is_bool(val) 40 | assert_equal false, ret, val 41 | } 42 | end 43 | 44 | # Python 45 | # str.find(sub[, start]) 46 | # Ruby 47 | # str.index(sub[, start]) 48 | using PythonIndexEx 49 | def test_index 50 | # result, str, sub, start 51 | vals = [[0, 'aiueo', 'ai', 0], 52 | [0, 'aiueoai', 'ai', nil], 53 | [1, 'aiueo', 'iu', nil], 54 | [-1, 'aiueo', 'iu', 2], 55 | [1, 'aiueo', 'iu', 1], 56 | [-1, 'aiueo', 'hoge', nil]] 57 | vals.each{|expect, str, substr, start_pos| 58 | if !start_pos.nil? 59 | ret = str.index(substr, start_pos) 60 | else 61 | ret = str.index(substr) 62 | end 63 | assert_equal expect, ret, "str:#{str} substr:#{substr} start_pos:#{start_pos}" 64 | } 65 | end 66 | 67 | # Python 68 | # str.find(sub[, start[, end]]) 69 | # Ruby 70 | # str.find(sub[, start[, end]]) 71 | using PythonIndexEx 72 | def test_find 73 | # result, str, sub, start, end 74 | vals = [[0, 'aiueo', 'ai', 0, nil], 75 | [0, 'aiueoai', 'ai', nil, nil], 76 | [1, 'aiueo', 'iu', nil, nil], 77 | [-1, 'aiueo', 'iu', 2, nil], 78 | [1, 'aiueo', 'iu', 1, 3], 79 | [-1, 'aiueo', 'iu', 1, 2], 80 | [-1, 'aiueo', 'hoge', nil, nil]] 81 | vals.each{|expect, str, substr, start_pos, end_pos| 82 | if !end_pos.nil? 83 | ret = str.find(substr, start_pos, end_pos) 84 | elsif !start_pos.nil? 85 | ret = str.find(substr, start_pos) 86 | else 87 | ret = str.find(substr) 88 | end 89 | assert_equal expect, ret, "str:#{str} substr:#{substr} start_pos:#{start_pos} end_pos:#{end_pos}" 90 | } 91 | end 92 | 93 | # Python 94 | # str.rindex(sub) 95 | # Ruby 96 | # str.rindex(sub) 97 | def test_rindex 98 | # result, str, sub 99 | vals = [[0, 'aiueo', 'ai'], 100 | [5, 'aiueoai', 'ai'], 101 | [1, 'aiueo', 'iu'], 102 | [-1, 'aiueo', 'hoge']] 103 | vals.each{|expect, str, substr| 104 | ret = str.rindex(substr) 105 | assert_equal expect, ret, "str:#{str} substr:#{substr}" 106 | } 107 | end 108 | 109 | # Python 110 | # str.rfind(sub[, start[, end]]) 111 | # Ruby 112 | # str.rfind(sub[, start[, end]]) 113 | def test_rfind 114 | # result, str, sub, start, end 115 | vals = [[0, 'aiueo', 'ai', 0, nil], 116 | [5, 'aiueoai', 'ai', nil, nil], 117 | [1, 'aiueo', 'iu', nil, nil], 118 | [-1, 'aiueo', 'iu', 2, nil], 119 | [1, 'aiueo', 'iu', 1, 3], 120 | [-1, 'aiueo', 'iu', 1, 2], 121 | [1, 'aiueo', 'iu', 1, -1], 122 | [-1, 'aiueo', 'hoge', nil, nil]] 123 | vals.each{|expect, str, substr, start_pos, end_pos| 124 | if !end_pos.nil? 125 | ret = str.rfind(substr, start_pos, end_pos) 126 | elsif !start_pos.nil? 127 | ret = str.rfind(substr, start_pos) 128 | else 129 | ret = str.rfind(substr) 130 | end 131 | assert_equal expect, ret, "str:#{str} substr:#{substr} start_pos:#{start_pos} end_pos:#{end_pos}" 132 | } 133 | end 134 | end 135 | -------------------------------------------------------------------------------- /ast.txt: -------------------------------------------------------------------------------- 1 | -- ASDL's 7 builtin types are: 2 | -- identifier, int, string, bytes, object, singleton, constant 3 | -- 4 | -- singleton: None, True or False 5 | -- constant can be None, whereas None means "no value" for object. 6 | 7 | module Python 8 | { 9 | mod = Module(stmt* body) 10 | | Interactive(stmt* body) 11 | | Expression(expr body) 12 | 13 | -- not really an actual node but useful in Jython's typesystem. 14 | | Suite(stmt* body) 15 | 16 | stmt = FunctionDef(identifier name, arguments args, 17 | stmt* body, expr* decorator_list, expr? returns) 18 | | AsyncFunctionDef(identifier name, arguments args, 19 | stmt* body, expr* decorator_list, expr? returns) 20 | 21 | | ClassDef(identifier name, 22 | expr* bases, 23 | keyword* keywords, 24 | stmt* body, 25 | expr* decorator_list) 26 | | Return(expr? value) 27 | 28 | | Delete(expr* targets) 29 | | Assign(expr* targets, expr value) 30 | | AugAssign(expr target, operator op, expr value) 31 | -- 'simple' indicates that we annotate simple name without parens 32 | | AnnAssign(expr target, expr annotation, expr? value, int simple) 33 | 34 | -- use 'orelse' because else is a keyword in target languages 35 | | For(expr target, expr iter, stmt* body, stmt* orelse) 36 | | AsyncFor(expr target, expr iter, stmt* body, stmt* orelse) 37 | | While(expr test, stmt* body, stmt* orelse) 38 | | If(expr test, stmt* body, stmt* orelse) 39 | | With(withitem* items, stmt* body) 40 | | AsyncWith(withitem* items, stmt* body) 41 | 42 | | Raise(expr? exc, expr? cause) 43 | | Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody) 44 | | Assert(expr test, expr? msg) 45 | 46 | | Import(alias* names) 47 | | ImportFrom(identifier? module, alias* names, int? level) 48 | 49 | | Global(identifier* names) 50 | | Nonlocal(identifier* names) 51 | | Expr(expr value) 52 | | Pass | Break | Continue 53 | 54 | -- XXX Jython will be different 55 | -- col_offset is the byte offset in the utf8 string the parser uses 56 | attributes (int lineno, int col_offset) 57 | 58 | -- BoolOp() can use left & right? 59 | expr = BoolOp(boolop op, expr* values) 60 | | BinOp(expr left, operator op, expr right) 61 | | UnaryOp(unaryop op, expr operand) 62 | | Lambda(arguments args, expr body) 63 | | IfExp(expr test, expr body, expr orelse) 64 | | Dict(expr* keys, expr* values) 65 | | Set(expr* elts) 66 | | ListComp(expr elt, comprehension* generators) 67 | | SetComp(expr elt, comprehension* generators) 68 | | DictComp(expr key, expr value, comprehension* generators) 69 | | GeneratorExp(expr elt, comprehension* generators) 70 | -- the grammar constrains where yield expressions can occur 71 | | Await(expr value) 72 | | Yield(expr? value) 73 | | YieldFrom(expr value) 74 | -- need sequences for compare to distinguish between 75 | -- x < 4 < 3 and (x < 4) < 3 76 | | Compare(expr left, cmpop* ops, expr* comparators) 77 | | Call(expr func, expr* args, keyword* keywords) 78 | | Num(object n) -- a number as a PyObject. 79 | | Str(string s) -- need to specify raw, unicode, etc? 80 | | FormattedValue(expr value, int? conversion, expr? format_spec) 81 | | JoinedStr(expr* values) 82 | | Bytes(bytes s) 83 | | NameConstant(singleton value) 84 | | Ellipsis 85 | | Constant(constant value) 86 | 87 | -- the following expression can appear in assignment context 88 | | Attribute(expr value, identifier attr, expr_context ctx) 89 | | Subscript(expr value, slice slice, expr_context ctx) 90 | | Starred(expr value, expr_context ctx) 91 | | Name(identifier id, expr_context ctx) 92 | | List(expr* elts, expr_context ctx) 93 | | Tuple(expr* elts, expr_context ctx) 94 | 95 | -- col_offset is the byte offset in the utf8 string the parser uses 96 | attributes (int lineno, int col_offset) 97 | 98 | expr_context = Load | Store | Del | AugLoad | AugStore | Param 99 | 100 | slice = Slice(expr? lower, expr? upper, expr? step) 101 | | ExtSlice(slice* dims) 102 | | Index(expr value) 103 | 104 | boolop = And | Or 105 | 106 | operator = Add | Sub | Mult | MatMult | Div | Mod | Pow | LShift 107 | | RShift | BitOr | BitXor | BitAnd | FloorDiv 108 | 109 | unaryop = Invert | Not | UAdd | USub 110 | 111 | cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn 112 | 113 | comprehension = (expr target, expr iter, expr* ifs, int is_async) 114 | 115 | excepthandler = ExceptHandler(expr? type, identifier? name, stmt* body) 116 | attributes (int lineno, int col_offset) 117 | 118 | arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults, 119 | arg? kwarg, expr* defaults) 120 | 121 | arg = (identifier arg, expr? annotation) 122 | attributes (int lineno, int col_offset) 123 | 124 | -- keyword arguments supplied to call (NULL identifier for **kwargs) 125 | keyword = (identifier? arg, expr value) 126 | 127 | -- import name with optional 'as' alias. 128 | alias = (identifier name, identifier? asname) 129 | 130 | withitem = (expr context_expr, expr? optional_vars) 131 | } 132 | -------------------------------------------------------------------------------- /tests/algorithms/triangulation.py: -------------------------------------------------------------------------------- 1 | def abs(x): 2 | if x > 0: 3 | return x 4 | else: 5 | return -x 6 | 7 | def sqrt(x): 8 | eps = 1e-10 9 | x = float(x) 10 | r = x/2 11 | residual = r**2 - x 12 | while abs(residual) > eps: 13 | r_d = -residual/(2*r) 14 | r += r_d 15 | residual = r**2 - x 16 | return r 17 | 18 | def is_on_the_left(c, a, b, pts_list): 19 | ax, ay = pts_list[a] 20 | bx, by = pts_list[b] 21 | cx, cy = pts_list[c] 22 | ux = float(bx - ax) 23 | uy = float(by - ay) 24 | vx = float(cx - ax) 25 | vy = float(cy - ay) 26 | return (ux*vy - uy*vx > 0) 27 | 28 | def criterion(a, b, c, pts_list): 29 | ax, ay = pts_list[a] 30 | bx, by = pts_list[b] 31 | cx, cy = pts_list[c] 32 | ux = float(ax - cx) 33 | uy = float(ay - cy) 34 | vx = float(bx - cx) 35 | vy = float(by - cy) 36 | len_u = sqrt(ux*ux + uy*uy) 37 | len_v = sqrt(vx*vx + vy*vy) 38 | return (ux*vx + uy*vy)/(len_u*len_v) 39 | 40 | def find_third_point(a, b, pts_list, edges): 41 | """ 42 | Take a boundary edge (a,b), and in the list of points 43 | find a point 'c' that lies on the left of ab and maximizes 44 | the angle acb 45 | """ 46 | found = 0 47 | minimum = 10**8 #this is dirty 48 | c_index = -1 49 | pt_index = -1 50 | for c_point in pts_list: 51 | c_index += 1 52 | if c_index != a and c_index != b and is_on_the_left(c_index, a, b, pts_list): 53 | edge_intersects = \ 54 | edge_intersects_edges((a, c_index), pts_list, edges) or \ 55 | edge_intersects_edges((b, c_index), pts_list, edges) 56 | if not edge_intersects: 57 | crit = criterion(a, b, c_index, pts_list) 58 | if crit < minimum: 59 | minimum = crit 60 | pt_index = c_index 61 | found = 1 62 | if found == 0: 63 | raise TriangulationError("ERROR: Optimal point not found in find_third_point().") 64 | return pt_index 65 | 66 | def lies_inside(c, bdy_edges): 67 | for edge in bdy_edges: 68 | a,b = edge 69 | if c == a or c == b: return False 70 | return True 71 | 72 | def is_boundary_edge(a, b, bdy_edges): 73 | """ 74 | Checks whether edge (a, b) is in the list of boundary edges 75 | """ 76 | for edge in bdy_edges: 77 | a0, b0 = edge 78 | if a == a0 and b == b0: 79 | return True 80 | return False 81 | 82 | def triangulate_af(pts_list, bdy_edges): 83 | """ 84 | Create a triangulation using the advancing front method. 85 | """ 86 | # create empty list of elements 87 | elems = [] 88 | bdy_edges = bdy_edges[:] 89 | # main loop 90 | while bdy_edges != []: 91 | # take the last item from the list of bdy edges (and remove it) 92 | a,b = bdy_edges.pop() 93 | c = find_third_point(a, b, pts_list, bdy_edges) 94 | elems.append((a,b,c)) 95 | if is_boundary_edge(c, a, bdy_edges): 96 | bdy_edges.remove((c,a)) 97 | else: 98 | bdy_edges.append((a,c)) 99 | if is_boundary_edge(b, c, bdy_edges): 100 | bdy_edges.remove((b,c)) 101 | else: 102 | bdy_edges.append((c,b)) 103 | return elems 104 | 105 | def ccw(a, b, c): 106 | return (c[1]-a[1])*(b[0]-a[0]) > (b[1]-a[1])*(c[0]-a[0]) 107 | 108 | def intersect(a, b, c, d): 109 | return ccw(a, c, d) != ccw(b, c, d) and ccw(a, b, c) != ccw(a, b, d) 110 | 111 | def two_edges_intersect(nodes, e1, e2): 112 | """ 113 | Checks whether the two edges intersect. 114 | 115 | It assumes that e1 and e2 are tuples of (a_id, b_id) of ids into the nodes. 116 | """ 117 | a = nodes[e1[0]] 118 | b = nodes[e1[1]] 119 | c = nodes[e2[0]] 120 | d = nodes[e2[1]] 121 | return intersect(a, b, c, d) 122 | 123 | def any_edges_intersect(nodes, edges): 124 | """ 125 | Returns True if any two edges intersect. 126 | """ 127 | for i in range(len(edges)): 128 | for j in range(i+1, len(edges)): 129 | e1 = edges[i] 130 | e2 = edges[j] 131 | if e1[1] == e2[0] or e1[0] == e2[1]: 132 | continue 133 | if two_edges_intersect(nodes, e1, e2): 134 | return True 135 | return False 136 | 137 | def edge_intersects_edges(e1, nodes, edges): 138 | """ 139 | Returns True if "e1" intersects any edge from "edges". 140 | """ 141 | for i in range(len(edges)): 142 | e2 = edges[i] 143 | if e1[1] == e2[0] or e1[0] == e2[1]: 144 | continue 145 | if two_edges_intersect(nodes, e1, e2): 146 | return True 147 | return False 148 | 149 | def example1(): 150 | nodes = [ 151 | (0, 0), 152 | (1, 0), 153 | (1, 1), 154 | (0, 1), 155 | ] 156 | edges = [(0, 1), (1, 2), (2, 3), (3, 0)] 157 | elems = triangulate_af(nodes, edges) 158 | return nodes, edges, elems 159 | 160 | def example2(): 161 | nodes = [ 162 | (0, 0), 163 | (1, 0), 164 | (2, 1), 165 | (2, 2), 166 | (1, 2), 167 | (0.5, 1.5), 168 | (0, 1), 169 | ] 170 | edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 0)] 171 | elems = triangulate_af(nodes, edges) 172 | return nodes, edges, elems 173 | 174 | nodes, edges, elems = example1() 175 | print("nodes", nodes) 176 | print("edges", edges) 177 | print("elems", elems) 178 | if not any_edges_intersect(nodes, edges): 179 | print("ok") 180 | 181 | print() 182 | nodes, edges, elems = example2() 183 | print("nodes", nodes) 184 | print("edges", edges) 185 | print("elems", elems) 186 | if not any_edges_intersect(nodes, edges): 187 | print("ok") 188 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | py2rb.py 2 | ======== 3 | 4 | A code translator using AST from Python to Ruby. 5 | This is basically a NodeVisitor with ruby output. 6 | See ast documentation (https://docs.python.org/3/library/ast.html) for more information. 7 | 8 | Installation 9 | ------------ 10 | 11 | Execute the following:: 12 | 13 | pip install py2rb 14 | 15 | or 16 | 17 | git clone git://github.com/naitoh/py2rb.git 18 | 19 | Dependencies 20 | ------------ 21 | 22 | - Python 3.5, 3.6 23 | - Ruby 2.4 or later 24 | 25 | 26 | Usage 27 | -------- 28 | 29 | Sample 1:: 30 | 31 | $ cat tests/basic/oo_inherit_simple.py 32 | class bar(object): 33 | 34 | def __init__(self,name): 35 | self.name = name 36 | 37 | def setname(self,name): 38 | self.name = name 39 | 40 | class foo(bar): 41 | 42 | registered = [] 43 | 44 | def __init__(self,val,name): 45 | self.fval = val 46 | self.register(self) 47 | self.name = name 48 | 49 | def inc(self): 50 | self.fval += 1 51 | 52 | def msg(self, a=None, b=None, c=None): 53 | txt = '' 54 | varargs = a, b, c 55 | for arg in varargs: 56 | if arg is None: 57 | continue 58 | txt += str(arg) 59 | txt += "," 60 | return txt + self.name + " says:"+str(self.fval) 61 | 62 | @staticmethod 63 | def register(f): 64 | foo.registered.append(f) 65 | 66 | @staticmethod 67 | def printregistered(): 68 | for r in foo.registered: 69 | print(r.msg()) 70 | 71 | a = foo(10,'a') 72 | a.setname('aaa') 73 | b = foo(20,'b') 74 | c = foo(30,'c') 75 | 76 | a.inc() 77 | a.inc() 78 | c.inc() 79 | 80 | print(a.msg()) 81 | print(b.msg()) 82 | print(c.msg(2,3,4)) 83 | 84 | print("---") 85 | 86 | foo.printregistered() 87 | 88 | The above will result in :: 89 | 90 | $ py2rb tests/basic/oo_inherit_simple.py 91 | class Bar 92 | def initialize(name) 93 | @name = name 94 | end 95 | def setname(name) 96 | @name = name 97 | end 98 | end 99 | class Foo < Bar 100 | def method_missing(method, *args) 101 | self.class.__send__ method, *args 102 | end 103 | @@registered = [] 104 | def initialize(val, name) 105 | @fval = val 106 | Foo.register(self) 107 | @name = name 108 | end 109 | def inc() 110 | @fval += 1 111 | end 112 | def msg(a: nil, b: nil, c: nil) 113 | txt = "" 114 | varargs = [a, b, c] 115 | for arg in varargs 116 | if arg === nil 117 | next 118 | end 119 | txt += arg.to_s 120 | txt += "," 121 | end 122 | return ((txt + @name) + " says:") + @fval.to_s 123 | end 124 | def self.register(f) 125 | @@registered.push(f) 126 | end 127 | def self.printregistered() 128 | for r in @@registered 129 | print(r.msg()) 130 | end 131 | end 132 | def self.registered; @@registered; end 133 | def self.registered=(val); @@registered=val; end 134 | def registered; @registered = @@registered if @registered.nil?; @registered; end 135 | def registered=(val); @registered=val; end 136 | end 137 | a = Foo.new(10, "a") 138 | a.setname("aaa") 139 | b = Foo.new(20, "b") 140 | c = Foo.new(30, "c") 141 | a.inc() 142 | a.inc() 143 | c.inc() 144 | print(a.msg()) 145 | print(b.msg()) 146 | print(c.msg(a: 2, b: 3, c: 4)) 147 | print("---") 148 | Foo.printregistered() 149 | 150 | Sample 2:: 151 | 152 | $ cat tests/deep-learning-from-scratch/and_gate.py 153 | # coding: utf-8 154 | import numpy as np 155 | 156 | def AND(x1, x2): 157 | x = np.array([x1, x2]) 158 | w = np.array([0.5, 0.5]) 159 | b = -0.7 160 | tmp = np.sum(w*x) + b 161 | if tmp <= 0: 162 | return 0 163 | else: 164 | return 1 165 | 166 | if __name__ == '__main__': 167 | for xs in [(0, 0), (1, 0), (0, 1), (1, 1)]: 168 | y = AND(xs[0], xs[1]) 169 | print(str(xs) + " -> " + str(y)) 170 | 171 | The above will result in :: 172 | 173 | $ py2rb tests/deep-learning-from-scratch/and_gate.py 174 | require 'numo/narray' 175 | def AND(x1, x2) 176 | x = Numo::NArray.cast([x1, x2]) 177 | w = Numo::NArray.cast([0.5, 0.5]) 178 | b = -0.7 179 | tmp = ((w * x).sum()) + b 180 | if tmp <= 0 181 | return 0 182 | else 183 | return 1 184 | end 185 | end 186 | 187 | if __FILE__ == $0 188 | for xs in [[0, 0], [1, 0], [0, 1], [1, 1]] 189 | y = AND(xs[0], xs[1]) 190 | print((xs.to_s + (" -> ")) + y.to_s) 191 | end 192 | end 193 | 194 | Sample 3 (Convert all local dependent module files of specified Python file):: 195 | 196 | $ git clone git://github.com/chainer/chainer.git 197 | $ py2rb chainer/chainer/__init__.py -m -p chainer -r -w -f 198 | Try : chainer/chainer/__init__.py -> chainer/chainer/__init__.rb : [OK] 199 | Warning : yield is not supported : 200 | Warning : yield is not supported : 201 | Try : chainer/chainer/configuration.py -> chainer/chainer/configuration.rb : [Warning] 202 | Try : chainer/chainer/cuda.py -> chainer/chainer/cuda.rb : [OK] 203 | : 204 | : 205 | Try : chainer/chainer/utils/array.py -> chainer/chainer/utils/array.rb : [OK] 206 | 207 | Tests 208 | ----- 209 | 210 | $ ./run_tests.py 211 | 212 | Will run all tests, that are supposed to work. If any test fails, it's a bug. 213 | 214 | $ ./run_tests.py -a 215 | 216 | Will run all tests including those that are known to fail (currently). It 217 | should be understandable from the output. 218 | 219 | $ ./run_tests.py -x 220 | or 221 | $ ./run_tests.py --no-error 222 | 223 | Will run tests but ignore if an error is raised by the test. This is not 224 | affecting the error generated by the test files in the tests directory. 225 | 226 | For more flags then described here 227 | 228 | ./run_tests.py -h 229 | 230 | 231 | License 232 | ------- 233 | 234 | MIT, see the LICENSE file for exact details. 235 | -------------------------------------------------------------------------------- /py2rb/builtins/module.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | module PythonZipEx 3 | refine Object do 4 | # python : zip(l1, l2, [l3, ..]) 5 | # array : l1 6 | def zip_p(*args) 7 | args.collect!{|i| i.is_a?(String) ? i.split(''): i} 8 | a = args.shift 9 | return a.zip(*args).select{|i| !i.include?(nil)} 10 | end 11 | end 12 | end 13 | 14 | module PythonMethodEx 15 | refine Object do 16 | def getattr(*a) 17 | if singleton_class.class_variables.include? "@@#{a[0]}".to_sym 18 | send(a[0]) 19 | elsif public_methods.include? a[0].to_sym 20 | method(a[0]) 21 | elsif a.size == 2 22 | return a[1] 23 | else 24 | raise NoMethodError, "undefined method `#{a[0]}'" 25 | end 26 | end 27 | end 28 | end 29 | 30 | module PythonPrintEx 31 | refine Object do 32 | def print(*args) 33 | $, = ' ';$\ = "\n" 34 | super(*args) 35 | end 36 | end 37 | end 38 | 39 | module PythonIsBoolEx 40 | refine Object do 41 | def is_bool(a) 42 | case a 43 | when nil, false, 0, '', [], {} 44 | return false 45 | else 46 | return true 47 | end 48 | end 49 | end 50 | end 51 | 52 | module PythonIndexEx 53 | refine String do 54 | def index(substr, offset=0) 55 | ret = super(substr, offset) 56 | return ret.nil? ? -1 : ret 57 | end 58 | 59 | def rindex(substr) 60 | ret = super(substr) 61 | return ret.nil? ? -1 : ret 62 | end 63 | end 64 | end 65 | 66 | module PythonFindEx 67 | refine String do 68 | def find(substr, start_pos=0, end_pos=nil) 69 | if end_pos.nil? 70 | ret = index(substr, start_pos) 71 | else 72 | ret = self[0...end_pos].public_method(:index).call(substr, start_pos) 73 | end 74 | return ret.nil? ? -1 : ret 75 | end 76 | 77 | def rfind(substr, start_pos=0, end_pos=nil) 78 | if end_pos.nil? 79 | ret = self[start_pos..-1].public_method(:rindex).call(substr) 80 | unless ret.nil? 81 | ret = self[0..-1].public_method(:rindex).call(substr) 82 | end 83 | else 84 | ret = self[start_pos...end_pos].public_method(:rindex).call(substr) 85 | unless ret.nil? 86 | ret = self[0...end_pos].public_method(:rindex).call(substr) 87 | end 88 | end 89 | return ret.nil? ? -1 : ret 90 | end 91 | end 92 | end 93 | 94 | module PythonSplitEx 95 | refine String do 96 | def split_p(sep = '', limit=0) 97 | case sep 98 | when ' ' 99 | sep = / / 100 | when '' 101 | sep = $; 102 | end 103 | if limit > 0 104 | limit +=1 105 | end 106 | self.split(sep, limit) 107 | end 108 | end 109 | end 110 | 111 | module PythonStripEx 112 | refine String do 113 | def strip(chars='') 114 | if chars == '' 115 | super() 116 | else 117 | self.gsub(/(^[#{chars}]*)|([#{chars}]*$)/, '') 118 | end 119 | end 120 | 121 | def lstrip(chars='') 122 | if chars == '' 123 | super() 124 | else 125 | self.gsub(/(^[#{chars}]*)/, '') 126 | end 127 | end 128 | 129 | def rstrip(chars='') 130 | if chars == '' 131 | super() 132 | else 133 | self.gsub(/([#{chars}]*$)/, '') 134 | end 135 | end 136 | end 137 | end 138 | 139 | module PythonStringCountEx 140 | refine String do 141 | # Replace to Python String#count 142 | alias :count_r :count 143 | def count(substr, start_pos=nil, end_pos=nil) 144 | if start_pos.nil? 145 | self.scan(substr).size 146 | elsif end_pos.nil? 147 | self[start_pos..-1].scan(substr).size 148 | else 149 | self[start_pos...end_pos].scan(substr).size 150 | end 151 | end 152 | 153 | alias :each :chars 154 | end 155 | end 156 | 157 | module PythonRemoveEx 158 | refine Array do 159 | def remove(obj) 160 | i = self.index(obj) 161 | self.delete_at(i) 162 | return 163 | end 164 | end 165 | end 166 | 167 | module EnumerableEx 168 | refine Enumerable do 169 | def is_all?() 170 | result = true 171 | self.each do |a| 172 | case a 173 | when nil, false, 0, '', [], {} 174 | result = false 175 | end 176 | end 177 | return result 178 | end 179 | 180 | def is_any?() 181 | result = false 182 | self.each do |a| 183 | case a 184 | when nil, false, 0, '', [], {} 185 | else 186 | result = true 187 | end 188 | end 189 | return result 190 | end 191 | end 192 | end 193 | 194 | module PyLib 195 | require 'pathname' 196 | 197 | # tests/os/testdir/ 198 | # test_file1.txt 199 | # test_file2.txt 200 | # test_child_dir/ 201 | # test_child_file1.txt 202 | # test_child_file2.txt 203 | # tests/os/testdir 204 | # ['test_child_dir'] 205 | #['test_file1.txt', 'test_file2.txt'] 206 | # 207 | # tests/os/testdir/test_child_dir 208 | # [] 209 | #['test_child_file1.txt', 'test_child_file2.txt'] 210 | 211 | # tests/os/testdir 212 | # ["tests/os/testdir/test_child_dir"] 213 | # ["tests/os/testdir/test_child_dir/test_child_file1.txt", "tests/os/testdir/test_child_dir/test_child_file2.txt", "tests/os/testdir/test_file1.txt", "tests/os/testdir/test_file2.txt"] 214 | 215 | def self.walk(dir) 216 | dirpath = Pathname(dir) 217 | rootnames = [] 218 | Pathname(dirpath).find do |path| 219 | if path.directory? 220 | rootnames << path.to_s 221 | end 222 | end 223 | 224 | walks = [] 225 | rootnames.each{|root| 226 | dirnames = [] 227 | filenames = [] 228 | 229 | Dir.foreach(root){|f| 230 | path = File.join(root, f) 231 | case File.ftype(path) 232 | when 'directory' 233 | if ('.' != f) and ('..' != f) 234 | dirnames << f 235 | end 236 | when 'file' 237 | filenames << f 238 | end 239 | } 240 | walks << [root, dirnames, filenames] 241 | } 242 | 243 | return walks 244 | end 245 | end 246 | 247 | # 248 | # Foo.call() or Foo.() is nothing => Foo.new() call. 249 | # 250 | class Class 251 | def method_missing(method, *args) 252 | if method == :call 253 | self.new(*args) 254 | else 255 | super 256 | end 257 | end 258 | end 259 | 260 | require 'set' 261 | class Set 262 | def remove(x) 263 | self.delete(x) 264 | return 265 | end 266 | end 267 | -------------------------------------------------------------------------------- /testtools/util.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module that defines Tool functions and test runners/result for use with 3 | the unittest library. 4 | """ 5 | import sys 6 | if sys.version_info < (2, 7): 7 | import unittest2 as unittest 8 | else: 9 | import unittest 10 | import os 11 | import posixpath 12 | import re 13 | 14 | def get_posix_path(path): 15 | """translates path to a posix path""" 16 | heads = [] 17 | tail = path 18 | while tail != '': 19 | tail, head = os.path.split(tail) 20 | heads.append(head) 21 | return posixpath.join(*heads[::-1]) 22 | 23 | def run_with_stdlib(file_path, file_name=None): 24 | """Creates a test that runs a ruby file with the stdlib.""" 25 | file_name = file_name if file_name else file_path 26 | 27 | class TestStdLib(unittest.TestCase): 28 | """Tests ruby code with the stdlib""" 29 | templ = { 30 | "rb_path": file_path, 31 | "rb_unix_path": get_posix_path(file_path), 32 | "rb_out_path": file_path + ".out", 33 | "rb_error": file_path + ".err", 34 | "name": file_name, 35 | } 36 | def reportProgres(self): 37 | """Should be overloaded by the test result class.""" 38 | 39 | def runTest(self): 40 | """The actual test goes here.""" 41 | cmd = ( 42 | 'ruby "py2rb/builtins/module.rb" ' 43 | ' "%(rb_path)s" > "%(rb_out_path)s" 2> "%(rb_error)s"' 44 | )% self.templ 45 | self.assertEqual(0, os.system(cmd)) 46 | self.reportProgres() 47 | 48 | def __str__(self): 49 | return "%(rb_unix_path)s [1]: " % self.templ 50 | 51 | return TestStdLib 52 | 53 | def compile_file_test(file_path, file_name=None): 54 | """Creates a test that tests if a file can be compiled by python""" 55 | file_name = file_name if file_name else file_path 56 | 57 | class CompileFile(unittest.TestCase): 58 | """Test if a file can be compiled by python.""" 59 | 60 | templ = { 61 | "py_path": file_path, 62 | "py_unix_path": get_posix_path(file_path), 63 | "py_out_path": file_path + ".out", 64 | "py_error": file_path + ".err", 65 | "name": file_name, 66 | } 67 | def reportProgres(self): 68 | """Should be overloaded by the test result class""" 69 | 70 | def runTest(self): 71 | """The actual test goes here.""" 72 | commands = ( 73 | ( 74 | 'python "%(py_path)s" > ' 75 | '"%(py_out_path)s" 2> "%(py_error)s"' 76 | ) % self.templ, 77 | ) 78 | for cmd in commands: 79 | self.assertEqual(0, os.system(cmd)) 80 | self.reportProgres() 81 | def __str__(self): 82 | return "%(py_unix_path)s [1]: " % self.templ 83 | return CompileFile 84 | 85 | 86 | 87 | 88 | def compile_and_run_file_test(file_path, file_name=None): 89 | """Creates a test that compiles and runs the python file as ruby""" 90 | file_name = file_name if file_name else file_path 91 | 92 | class CompileAndRunFile(unittest.TestCase): 93 | """Tests that a file can be compiled and run as ruby""" 94 | name_path, ext = os.path.splitext(file_path) 95 | templ = { 96 | "py_path": file_path, 97 | "py_dir_path": os.path.dirname(file_path), 98 | "py_unix_path": get_posix_path(file_path), 99 | "py_out_path": file_path + ".out", 100 | "rb_path": name_path + ".rb", 101 | "rb_out_path": name_path + ".rb.out", 102 | "rb_out_expected_path": name_path + ".rb.expected_out", 103 | "rb_out_expected_in_path": name_path + ".rb.expected_in_out", 104 | "py_error": file_path + ".err", 105 | "rb_error": name_path + ".rb.err", 106 | "compiler_error": file_path + ".comp.err", 107 | "name": file_name, 108 | "cmd_out": name_path + ".cmd.txt", 109 | } 110 | def reportProgres(self): 111 | """Should be overloaded by the test result class""" 112 | 113 | def runTest(self): 114 | """The actual test goes here.""" 115 | commands = [] 116 | python_command = ( 117 | 'python "%(py_path)s" > "%(py_out_path)s" 2> ' 118 | '"%(py_error)s"' 119 | ) % self.templ 120 | commands.append(python_command) 121 | compile_command = ( 122 | 'python py2rb.py -p "%(py_dir_path)s" -r "%(py_path)s" -m -f -w -s 2> "%(compiler_error)s"' 123 | ) % self.templ 124 | commands.append(compile_command) 125 | ruby_command = ( 126 | 'ruby -I py2rb/builtins "%(rb_path)s" > "%(rb_out_path)s" 2> ' 127 | '"%(rb_error)s"' 128 | ) % self.templ 129 | commands.append(ruby_command) 130 | with open(self.templ['cmd_out'], mode = 'w') as fh: 131 | for cmd in commands: 132 | fh.write(cmd + '\n') 133 | #print(cmd) # debug 134 | self.assertEqual(0, os.system(cmd)) 135 | self.reportProgres() 136 | # Partial Match 137 | if os.path.exists(self.templ["rb_out_expected_in_path"]): 138 | # Fixed statement partial match 139 | f = open(self.templ["rb_out_expected_in_path"]) 140 | g = open(self.templ["rb_out_path"]) 141 | self.assertIn( 142 | f.read(), 143 | g.read() 144 | ) 145 | f.close() 146 | g.close() 147 | else: # Full text match 148 | # Fixed sentence matching 149 | if os.path.exists(self.templ["rb_out_expected_path"]): 150 | expected_file_path = self.templ["rb_out_expected_path"] 151 | else: # Dynamic sentence matching 152 | expected_file_path = self.templ["py_out_path"] 153 | f = open(expected_file_path, 'r') 154 | g = open(self.templ["rb_out_path"]) 155 | self.assertEqual( 156 | f.readlines(), 157 | g.readlines() 158 | ) 159 | f.close() 160 | g.close() 161 | self.reportProgres() 162 | 163 | def __str__(self): 164 | return "%(py_unix_path)s [4]: " % self.templ 165 | 166 | return CompileAndRunFile 167 | 168 | def compile_and_run_file_failing_test(*a, **k): 169 | """Turn a test to a failing test""" 170 | _class = compile_and_run_file_test(*a, **k) 171 | 172 | class FailingTest(_class): 173 | """Failing test""" 174 | @unittest.expectedFailure 175 | def runTest(self): 176 | return super(FailingTest, self).runTest() 177 | 178 | return FailingTest 179 | 180 | -------------------------------------------------------------------------------- /py2rb/modules/unittest.yaml: -------------------------------------------------------------------------------- 1 | # 2 | # Usage 3 | # -------- 4 | # Python module name: 5 | # id: Ruby module name 6 | # e.g. id: numo/narray # import numpy as np => require 'numo/narray' 7 | # mod_name: Ruby module namespace : %(mod)s 8 | # e.g. mod_name: Numo # from numpy import array => require 'numo/narray'; include Numo # mod: mod_name + '::' 9 | # mod_class_name: 10 | # Pyth n class name: Ruby class name # For class inheritance 11 | # e.g. TestCase: 'Test::Unit::TestCase' 12 | # 13 | # methods_map: 14 | # Python method name: 15 | # bracket: False => argument bracket 16 | # True: use bracket(default) # e.g. Numo::NArray.cast([3.0, 4.0]).prod(keepdims: true) 17 | # False: not use bracket ^^^^^^^^^^^^^^^^ 18 | # key: 19 | # - ['second'] => argument count 1 (len(key[..]) == 1) case 20 | # - ['first', 'second'..] => argument count 2 (len(key[..]) == 2) or not match (key[-1]) case 21 | # key_order: => key order change setting 22 | # - ['second'] => argument count 1 (len(key_order[..]) == 1) case 23 | # - ['second', 'first'..] => argument count 2 (len(key_order[..]) == 2) or not match (key[-1]) case 24 | # main_data_key: object => Main data key name : %(data)s 25 | # 26 | # main_func: '(%(data)s).sum' # convert to Ruby method 27 | # or 28 | # main_func_key: dtype => convert function key name 29 | # main_func_hash_nm: 'NArray' => convert function name (not match(default) case) 30 | # main_func_hash: *func_hash => convert function name (match case) 31 | # 32 | # option: 'no_method' => The method passed to the argument when converting to Ruby is processed as it is without objectization. 33 | # 34 | # def foo(x,y): 35 | # return x*y 36 | # 37 | # z = reduce(foo,y,10) 38 | # no use 'no_method' option 39 | # def foo(x, y) 40 | # return (x)*(y) 41 | # end 42 | # z = reduce(method(:foo), y, 10) 43 | # use 'no_method' option 44 | # def foo(x, y) 45 | # return (x)*(y) 46 | # end 47 | # z = reduce(foo(), y, 10) 48 | # 49 | # val: => arguments dict 50 | # object: False => Not use argument data 51 | # dtype: '%(mod)s%(main_func)s.cast(%(data)s)' # convert to Ruby method 52 | # axis: axis => Use keyword argument data 53 | # places: '1e-%(places)s' => String conversion processing. (Same key only) 54 | # '*args': True => Use star argument data 55 | # '**kwds': True => Use star keyword argument data 56 | # rtn: 57 | # - "" => rtn[0] : customize return string (main_func + rtn) : argument count 0 case 58 | # - "%(start)s" => rtn[1] : customize return string (main_func + rtn) : argument count 1 case 59 | # - "%(start)s %(second)s" => rtn[2] : customize return string (main_func + rtn) : argument count 2 or over (rtn[-1]) case 60 | # rtn_star: 61 | # - "" => rtn_star[0] : customize return string (main_func + rtn_star) : key (argument) count 0 case 62 | # - "%(one)s" => rtn_star[1] : customize return string (main_func + rtn_star) : key (argument) count 1 case 63 | # - "%(one)s,%(*args)s" => rtn_star[2] : customize return string (main_func + rtn_star) : key (argument) count 2 case 64 | # - "%(one)s,%(*args)s,%(**kwds)s" => rtn_star[3] : customize return string (main_func + rtn_star) : key (argument) count 3 or over (rtn[-1]) case 65 | # 66 | # ignore: 67 | # Python method name: # ignore case 68 | # e.g. main: '' 69 | # 70 | 71 | unittest: 72 | id: test/unit 73 | mod_name: Test::Unit 74 | mod_class_name: 75 | TestCase: 'Test::Unit::TestCase' 76 | methods_map: 77 | TestCase.assertIn: 78 | # (first, second, msg=None) 79 | main_func: 'assert_include' 80 | key: 81 | - [first, second, msg] 82 | key_order: 83 | # self.assertIn('foo', ['foo', 'bar'], 'message test') 84 | # assert_include(['foo', 'bar'],'foo','message test') 85 | - [second, first, msg] 86 | val: 87 | first: True 88 | second: True 89 | msg: True 90 | TestCase.assertEqual: 91 | # (first, second, msg=None) 92 | main_func: 'assert_equal' 93 | key: 94 | - [first, second, msg] 95 | key_order: 96 | - [second, first, msg] 97 | val: 98 | first: True 99 | second: True 100 | msg: True 101 | TestCase.assertAlmostEqual: 102 | # (first, second, places=7, msg=None, delta=None) 103 | main_func: 'assert_in_delta' 104 | key: 105 | - [first, second, places, msg, delta] 106 | key_order: 107 | # - places case 108 | # self.assertAlmostEqual(1.0, 1.00000001, 7, '''comment test''') 109 | # assert_in_delta(1.00000001, 1.0, 1e-1*1e-7, "comment test") 110 | # - delta case 111 | # self.assertAlmostEqual(1.0, 1.00000001, msg='''comment test''', delta=1e-8) 112 | # assert_in_delta(1.00000001, 1.0, 1e-08, "comment test") 113 | - [second, first, places, delta, msg] 114 | val: 115 | first: True 116 | second: True 117 | places: '1e-1*1e-%(places)s' 118 | msg: True 119 | delta: True 120 | TestCase.assertIsInstance: 121 | # (obj, cls, msg=None) 122 | key: 123 | - [obj, cls] 124 | - [obj, cls, msg] 125 | val: 126 | obj: True # Use argument data 127 | cls: True # Use argument data 128 | msg: True # Use argument data 129 | main_func: 'assert_true' 130 | rtn: # rtn[0]-rtn[3] 131 | - '' 132 | - '' 133 | # assertIsInstance(obj, cls) 134 | # assert_true obj.is_a?(cls) 135 | - ' (%(obj)s).is_a?(%(cls)s)' 136 | # assertIsInstance(obj, cls, msg) 137 | # assert_true obj.is_a?(cls), msg 138 | - ' (%(obj)s).is_a?(%(cls)s), %(msg)s' 139 | TestCase.assertIs: 140 | # (first, second, msg=None) 141 | main_func: 'assert_equal' 142 | key: 143 | - [first, second, msg] 144 | key_order: 145 | - [second, first, msg] 146 | val: 147 | first: True 148 | second: True 149 | msg: True 150 | TestCase.assertTrue: 151 | # (expr, msg=None) 152 | main_func: 'assert' 153 | key: 154 | - [expr, msg] 155 | val: 156 | expr: True 157 | msg: True 158 | TestCase.assertRaises: 159 | # (exception, callable, *args, **kwds) 160 | main_func: 'assert_raise' 161 | option: 'no_method' 162 | key: 163 | - [exception] 164 | - [exception, callable, '*args', '**kwds'] 165 | val: 166 | exception: False 167 | callable: False 168 | '*args': True # Use star argument data 169 | '**kwds': True # Use star keyword argument data 170 | rtn_star: # rtn_star[0]-rtn_star[4] 171 | - "" 172 | # self.assertRaises(TypeError, msg=None) 173 | # assert_raise(klass1, klass2, ..., message = "") { ... } 174 | - "(%(exception)s)" 175 | # self.assertRaises(TypeError, foo, *args, **kwds) 176 | # assert_raise(klass1, klass2, ..., message = "") { foo(*args, **kwds) } 177 | - "(%(exception)s){%(callable)s()}" 178 | - "(%(exception)s){%(callable)s(%(*args)s)}" 179 | - "(%(exception)s){%(callable)s(%(*args)s, %(**kwds)s)}" 180 | ignore: 181 | main: '' 182 | 183 | -------------------------------------------------------------------------------- /test_results.txt: -------------------------------------------------------------------------------- 1 | Looking for "ruby", "py2rb/builtins/module.rb", "py2rb/builtins/require.rb" [3]: 2 | .. [OK] 3 | tests/test_builtins.rb [1]: . [OK] 4 | tests/algorithms/sqrt.py [4]: .... [OK] 5 | tests/algorithms/triangulation.py [4]: .... [OK] 6 | tests/basic/assert.py [4]: .... [OK] 7 | tests/basic/assign.py [4]: .... [OK] 8 | tests/basic/assign_slice.py [4]: .... [OK] 9 | tests/basic/augassign.py [4]: .... [OK] 10 | tests/basic/augassign2.py [4]: .... [OK] 11 | tests/basic/binaryops.py [4]: .... [OK] 12 | tests/basic/break.py [4]: .... [OK] 13 | tests/basic/class.py [4]: .... [OK] 14 | tests/basic/class2.py [4]: .... [OK] 15 | tests/basic/class3.py [4]: .... [OK] 16 | tests/basic/class4.py [4]: .... [OK] 17 | tests/basic/class5.py [4]: .... [OK] 18 | tests/basic/class6.py [4]: .... [OK] 19 | tests/basic/closure.py [4]: .... [OK] 20 | tests/basic/closure_in_class.py [4]: .... [OK] 21 | tests/basic/continue.py [4]: .... [OK] 22 | tests/basic/del_array.py [4]: .... [OK] 23 | tests/basic/del_attr.py [4]: .... [OK] 24 | tests/basic/del_dict.py [4]: .... [OK] 25 | tests/basic/del_slice.py [4]: .... [OK] 26 | tests/basic/dictcomp1.py [4]: .... [OK] 27 | tests/basic/dictcomp2.py [4]: .... [OK] 28 | tests/basic/dictionary.py [4]: .... [OK] 29 | tests/basic/dictionary2.py [4]: .... [OK] 30 | tests/basic/dictionary3.py [4]: .... [OK] 31 | tests/basic/docstring.py [4]: .... [OK] 32 | tests/basic/embedding.py [4]: .... [OK] 33 | tests/basic/fib.py [4]: .... [OK] 34 | tests/basic/float2int.py [4]: .... [OK] 35 | tests/basic/for_in.py [4]: .... [OK] 36 | tests/basic/for_range1.py [4]: .... [OK] 37 | tests/basic/for_range2.py [4]: .... [OK] 38 | tests/basic/for_step.py [4]: .... [OK] 39 | tests/basic/getattr.py [4]: .... [OK] 40 | tests/basic/globalvar.py [4]: .... [OK] 41 | tests/basic/hasattr1.py [4]: .... [OK] 42 | tests/basic/helloworld.py [4]: .... [OK] 43 | tests/basic/ifelse.py [4]: .... [OK] 44 | tests/basic/ifs.py [4]: .... [OK] 45 | tests/basic/ifs2.py [4]: .... [OK] 46 | tests/basic/keys.py [4]: .... [OK] 47 | tests/basic/kwargs.py [4]: .... [OK] 48 | tests/basic/kwargs2.py [4]: .... [OK] 49 | tests/basic/kwargs3.py [4]: .... [OK] 50 | tests/basic/lambda.py [4]: .... [OK] 51 | tests/basic/lambda2.py [4]: .... [OK] 52 | tests/basic/lambda3.py [4]: .... [OK] 53 | tests/basic/lambda_map.py [4]: .... [OK] 54 | tests/basic/list.py [4]: .... [OK] 55 | tests/basic/list2.py [4]: .... [OK] 56 | tests/basic/list3.py [4]: .... [OK] 57 | tests/basic/listcomp1.py [4]: .... [OK] 58 | tests/basic/literals.py [4]: .... [OK] 59 | tests/basic/logicalops.py [4]: .... [OK] 60 | tests/basic/loops.py [4]: .... [OK] 61 | tests/basic/multiassign.py [4]: .... [OK] 62 | tests/basic/none.py [4]: .... [OK] 63 | tests/basic/numeric.py [4]: .... [OK] 64 | tests/basic/oo.py [4]: .... [OK] 65 | tests/basic/oo_attributes.py [4]: .... [OK] 66 | tests/basic/oo_inherit.py [4]: .... [OK] 67 | tests/basic/oo_inherit2.py [4]: .... [OK] 68 | tests/basic/oo_inherit3.py [4]: .... [OK] 69 | tests/basic/oo_inherit_simple.py [4]: .... [OK] 70 | tests/basic/oo_inherit_simple_super1.py [4]: .... [OK] 71 | tests/basic/oo_inherit_simple_super2.py [4]: .... [OK] 72 | tests/basic/oo_inherit_simple_super3.py [4]: .... [OK] 73 | tests/basic/oo_static_inherit.py [4]: .... [OK] 74 | tests/basic/pass.py [4]: .... [OK] 75 | tests/basic/print.py [4]: .... [OK] 76 | tests/basic/raise.py [4]: .... [OK] 77 | tests/basic/raise2.py [4]: .... [OK] 78 | tests/basic/scope.py [4]: .... [OK] 79 | tests/basic/set.py [4]: .... [OK] 80 | tests/basic/str1.py [4]: .... [OK] 81 | tests/basic/str_endswith.py [4]: .... [OK] 82 | tests/basic/sumcomp.py [4]: .... [OK] 83 | tests/basic/super1.py [4]: .... [OK] 84 | tests/basic/super2.py [4]: .... [OK] 85 | tests/basic/trueorfalse.py [4]: .... [OK] 86 | tests/basic/try.py [4]: .... [OK] 87 | tests/basic/tuple.py [4]: .... [OK] 88 | tests/basic/tuple2.py [4]: .... [OK] 89 | tests/basic/vargs.py [4]: .... [OK] 90 | tests/basic/while.py [4]: .... [OK] 91 | tests/basic/with.py [4]: .... [OK] 92 | tests/collections/ordered_dict.py [4]: .... [OK] 93 | tests/decorator/function1.py [4]: .... [OK] 94 | tests/decorator/function2.py [4]: .... [OK] 95 | tests/decorator/function3.py [4]: .... [OK] 96 | tests/decorator/property.py [4]: .... [OK] 97 | tests/decorator/setter.py [4]: .... [OK] 98 | tests/deep-learning-from-scratch/and_gate.py [4]: .... [OK] 99 | tests/deep-learning-from-scratch/relu.py [4]: .... [OK] 100 | tests/deep-learning-from-scratch/sigmoid.py [4]: .... [OK] 101 | tests/deep-learning-from-scratch/step_function.py [4]: .... [OK] 102 | tests/errors/py_collision.py [4]: .... [OK] 103 | tests/functions/and.py [4]: .... [OK] 104 | tests/functions/append.py [4]: .... [OK] 105 | tests/functions/aug.py [4]: .... [OK] 106 | tests/functions/bitand.py [4]: .... [OK] 107 | tests/functions/bitor.py [4]: .... [OK] 108 | tests/functions/bitxor.py [4]: .... [OK] 109 | tests/functions/divfloor.py [4]: .... [OK] 110 | tests/functions/float.py [4]: .... [OK] 111 | tests/functions/floatdiv.py [4]: .... [OK] 112 | tests/functions/gtge.py [4]: .... [OK] 113 | tests/functions/in.py [4]: .... [OK] 114 | tests/functions/int.py [4]: .... [OK] 115 | tests/functions/isinstance.py [4]: .... [OK] 116 | tests/functions/len.py [4]: .... [OK] 117 | tests/functions/lshift.py [4]: .... [OK] 118 | tests/functions/ltle.py [4]: .... [OK] 119 | tests/functions/ne.py [4]: .... [OK] 120 | tests/functions/or.py [4]: .... [OK] 121 | tests/functions/pop.py [4]: .... [OK] 122 | tests/functions/rshift.py [4]: .... [OK] 123 | tests/functions/sort.py [4]: .... [OK] 124 | tests/functions/str.py [4]: .... [OK] 125 | tests/functions/ubitcomp.py [4]: .... [OK] 126 | tests/functions/uminus.py [4]: .... [OK] 127 | tests/functions/uplus.py [4]: .... [OK] 128 | tests/lists/all.py [4]: .... [OK] 129 | tests/lists/any.py [4]: .... [OK] 130 | tests/lists/extend.py [4]: .... [OK] 131 | tests/lists/filter.py [4]: .... [OK] 132 | tests/lists/in.py [4]: .... [OK] 133 | tests/lists/insert.py [4]: .... [OK] 134 | tests/lists/map.py [4]: .... [OK] 135 | tests/lists/max.py [4]: .... [OK] 136 | tests/lists/min.py [4]: .... [OK] 137 | tests/lists/reverse.py [4]: .... [OK] 138 | tests/lists/subclass.py [4]: .... [OK] 139 | tests/lists/subclass2.py [4]: .... [OK] 140 | tests/lists/subclass3.py [4]: .... [OK] 141 | tests/lists/sum.py [4]: .... [OK] 142 | tests/lists/sum2.py [4]: .... [OK] 143 | tests/lists/xrange.py [4]: .... [OK] 144 | tests/lists/zip.py [4]: .... [OK] 145 | tests/modules/classname.py [4]: .... [OK] 146 | tests/modules/from_import.py [4]: .... [OK] 147 | tests/modules/from_import_as_module.py [4]: .... [OK] 148 | tests/modules/import.py [4]: .... [OK] 149 | tests/modules/import_alias.py [4]: .... [OK] 150 | tests/modules/import_as_module.py [4]: .... [OK] 151 | tests/modules/import_class.py [4]: .... [OK] 152 | tests/modules/import_global.py [4]: .... [OK] 153 | tests/modules/import_init.py [4]: .... [OK] 154 | tests/modules/import_multi.py [4]: .... [OK] 155 | tests/numpy/abs.py [4]: .... [OK] 156 | tests/numpy/all.py [4]: .... [OK] 157 | tests/numpy/any.py [4]: .... [OK] 158 | tests/numpy/arange.py [4]: .... [OK] 159 | tests/numpy/array2string.py [4]: .... [OK] 160 | tests/numpy/asarray.py [4]: .... [OK] 161 | tests/numpy/ellipsis.py [4]: .... [OK] 162 | tests/numpy/empty.py [4]: .... [OK] 163 | tests/numpy/ext_slice.py [4]: .... [OK] 164 | tests/numpy/full.py [4]: .... [OK] 165 | tests/numpy/insert.py [4]: .... [OK] 166 | tests/numpy/like.py [4]: .... [OK] 167 | tests/numpy/linspace.py [4]: .... [OK] 168 | tests/numpy/max_min.py [4]: .... [OK] 169 | tests/numpy/maximum_minimum.py [4]: .... [OK] 170 | tests/numpy/ndarray.py [4]: .... [OK] 171 | tests/numpy/ndarray2.py [4]: .... [OK] 172 | tests/numpy/ndarray3.py [4]: .... [OK] 173 | tests/numpy/not_like.py [4]: .... [OK] 174 | tests/numpy/np_copy.py [4]: .... [OK] 175 | tests/numpy/product.py [4]: .... [OK] 176 | tests/numpy/random_rand.py [4]: .... [OK] 177 | tests/numpy/random_randint.py [4]: .... [OK] 178 | tests/numpy/random_random.py [4]: .... [OK] 179 | tests/numpy/random_uniform.py [4]: .... [OK] 180 | tests/numpy/special_values.py [4]: .... [OK] 181 | tests/numpy/sqrt.py [4]: .... [OK] 182 | tests/numpy/sum.py [4]: .... [OK] 183 | tests/numpy/trigonometric_funcitons.py [4]: .... [OK] 184 | tests/numpy/type.py [4]: .... [OK] 185 | tests/os/path_basename.py [4]: .... [OK] 186 | tests/os/path_dirname.py [4]: .... [OK] 187 | tests/os/path_join.py [4]: .... [OK] 188 | tests/os/walk.py [4]: .... [OK] 189 | tests/random/random_random.py [4]: .... [OK] 190 | tests/six/integer_types.py [4]: .... [OK] 191 | tests/six/iteritems.py [4]: .... [OK] 192 | tests/six/itervalues.py [4]: .... [OK] 193 | tests/six/moves.range.py [4]: .... [OK] 194 | tests/six/py23.py [4]: .... [OK] 195 | tests/strings/count.py [4]: .... [OK] 196 | tests/strings/find.py [4]: .... [OK] 197 | tests/strings/join.py [4]: .... [OK] 198 | tests/strings/lstrip0.py [4]: .... [OK] 199 | tests/strings/lstrip1.py [4]: .... [OK] 200 | tests/strings/replace.py [4]: .... [OK] 201 | tests/strings/rfind.py [4]: .... [OK] 202 | tests/strings/rstrip0.py [4]: .... [OK] 203 | tests/strings/rstrip1.py [4]: .... [OK] 204 | tests/strings/split.py [4]: .... [OK] 205 | tests/strings/splitlines.py [4]: .... [OK] 206 | tests/strings/string_format_combined_simple.py [4]: .... [OK] 207 | tests/strings/string_format_d.py [4]: .... [OK] 208 | tests/strings/string_format_d_simple.py [4]: .... [OK] 209 | tests/strings/string_format_f_simple.py [4]: .... [OK] 210 | tests/strings/string_format_i.py [4]: .... [OK] 211 | tests/strings/string_format_s_simple.py [4]: .... [OK] 212 | tests/strings/string_format_u.py [4]: .... [OK] 213 | tests/strings/strings_in_strings.py [4]: .... [OK] 214 | tests/strings/strip.py [4]: .... [OK] 215 | tests/strings/strip1.py [4]: .... [OK] 216 | tests/strings/ulcase.py [4]: .... [OK] 217 | tests/strings/zipstring.py [4]: .... [OK] 218 | tests/unittest/assertAlmostEqual.py [4]: .... [OK] 219 | tests/unittest/assertEqual.py [4]: .... [OK] 220 | tests/unittest/assertIn.py [4]: .... [OK] 221 | tests/unittest/assertIs.py [4]: .... [OK] 222 | tests/unittest/assertIsInstance.py [4]: .... [OK] 223 | tests/unittest/assertRaises.py [4]: .... [OK] 224 | tests/unittest/assertTrue.py [4]: .... [OK] 225 | tests/unittest/class.py [4]: .... [OK] 226 | tests/basic/default.py [4]: .. known to [FAIL] 227 | tests/basic/del_global.py [4]: ... known to [FAIL] 228 | tests/basic/del_local.py [4]: ... known to [FAIL] 229 | tests/basic/for_in2.py [4]: ... known to [FAIL] 230 | tests/basic/generator.py [4]: .. known to [FAIL] 231 | tests/basic/hasattr2.py [4]: .. known to [FAIL] 232 | tests/basic/listcomp2.py [4]: .. known to [FAIL] 233 | tests/basic/nestedclass.py [4]: .. known to [FAIL] 234 | tests/basic/oo_diamond.py [4]: ... known to [FAIL] 235 | tests/basic/oo_static_inherit2.py [4]: .. known to [FAIL] 236 | tests/basic/oo_super.py [4]: ... known to [FAIL] 237 | tests/basic/valueerror.py [4]: ... known to [FAIL] 238 | tests/basic/vars.py [4]: ... known to [FAIL] 239 | tests/basic/vars2.py [4]: ... known to [FAIL] 240 | tests/basic/yield.py [4]: .. known to [FAIL] 241 | tests/decorator/class.py [4]: .. known to [FAIL] 242 | tests/decorator/decorator.py [4]: .. known to [FAIL] 243 | tests/functions/sort23.py [4]: known to [FAIL] 244 | tests/functions/sort_cmp.py [4]: known to [FAIL] 245 | tests/libraries/xmlwriter.py [4]: .. known to [FAIL] 246 | tests/lists/reduce.py [4]: .. known to [FAIL] 247 | tests/modules/import_diamond.py [4]: .. known to [FAIL] 248 | tests/modules/module_name.py [4]: .. known to [FAIL] 249 | tests/modules/rng.py [4]: known to [FAIL] 250 | tests/numpy/arg_max_min.py [4]: ... known to [FAIL] 251 | tests/strings/other_strings.py [4]: .. known to [FAIL] 252 | tests/strings/replace2.py [4]: .. known to [FAIL] 253 | tests/strings/string_format_efg.py [4]: .. known to [FAIL] 254 | tests/strings/string_format_o.py [4]: ... known to [FAIL] 255 | tests/strings/string_format_x.py [4]: ... known to [FAIL] 256 | Ran 254 tests in 157.455s 257 | 258 | OK (expected failures=30) 259 | --------------------------------------------------------------------------------