How to use py method in fast-check-monorepo

Best JavaScript code snippet using fast-check-monorepo

py.js

Source:py.js Github

copy

Full Screen

...332 'Expected "' + id + '", got "' + token.id + '"');333 }334 token = next();335 }336 function PY_ensurepy(val, name) {337 switch (val) {338 case undefined:339 throw new Error("NameError: name '" + name + "' is not defined");340 case null:341 return py.None;342 case true:343 return py.True;344 case false:345 return py.False;346 }347 var fn = function () {};348 fn.prototype = py.object;349 if (py.PY_isInstance(val, py.object)350 || py.PY_isSubclass(val, py.object)) {351 return val;352 }353 switch (typeof val) {354 case 'number':355 return py.float.fromJSON(val);356 case 'string':357 return py.str.fromJSON(val);358 case 'function':359 return py.PY_def.fromJSON(val);360 }361 switch(val.constructor) {362 case Object:363 // TODO: why py.object instead of py.dict?364 var o = py.PY_call(py.object);365 for (var prop in val) {366 if (val.hasOwnProperty(prop)) {367 o[prop] = val[prop];368 }369 }370 return o;371 case Array:372 return py.list.fromJSON(val);373 }374 throw new Error("Could not convert " + val + " to a pyval");375 }376 var typename = function (obj) {377 if (obj.__class__) { // py type378 return obj.__class__.__name__;379 } else if(typeof obj !== 'object') { // JS primitive380 return typeof obj;381 } else { // JS object382 return obj.constructor.name;383 }384 };385 // JSAPI, JS-level utility functions for implementing new py.js386 // types387 py.py = {};388 py.PY_parseArgs = function PY_parseArgs(argument, format) {389 var out = {};390 var args = argument[0];391 var kwargs = {};392 for (var k in argument[1]) {393 if (!argument[1].hasOwnProperty(k)) { continue; }394 kwargs[k] = argument[1][k];395 }396 if (typeof format === 'string') {397 format = format.split(/\s+/);398 }399 var name = function (spec) {400 if (typeof spec === 'string') {401 return spec;402 } else if (spec instanceof Array && spec.length === 2) {403 return spec[0];404 }405 throw new Error(406 "TypeError: unknown format specification " +407 JSON.stringify(spec));408 };409 var spec;410 // TODO: ensure all format arg names are actual names?411 for(var i=0; i<args.length; ++i) {412 spec = format[i];413 // spec list ended, or specs switching to keyword-only414 if (!spec || spec === '*') {415 throw new Error(416 "TypeError: function takes exactly " + (i-1) +417 " positional arguments (" + args.length +418 " given")419 } else if(/^\*\w/.test(spec)) {420 // *args, final421 out[name(spec.slice(1))] = args.slice(i);422 break;423 }424 out[name(spec)] = args[i];425 }426 for(var j=i; j<format.length; ++j) {427 spec = format[j];428 var n = name(spec);429 if (n in out) {430 throw new Error(431 "TypeError: function got multiple values " + 432 "for keyword argument '" + kwarg + "'");433 }434 if (/^\*\*\w/.test(n)) {435 // **kwarg436 out[n.slice(2)] = kwargs;437 kwargs = {};438 break;439 }440 if (n in kwargs) {441 out[n] = kwargs[n];442 // Remove from args map443 delete kwargs[n];444 }445 }446 // Ensure all keyword arguments were consumed447 for (var key in kwargs) {448 throw new Error(449 "TypeError: function got an unexpected keyword argument '"450 + key + "'");451 }452 // Fixup args count if there's a kwonly flag (or an *args)453 var kwonly = 0;454 for(var k = 0; k < format.length; ++k) {455 if (/^\*/.test(format[k])) { kwonly = 1; break; }456 }457 // Check that all required arguments have been matched, add458 // optional values459 for(var k = 0; k < format.length; ++k) {460 spec = format[k];461 var n = name(spec);462 // kwonly, va_arg or matched argument463 if (/^\*/.test(n) || n in out) { continue; }464 // Unmatched required argument465 if (!(spec instanceof Array)) {466 throw new Error(467 "TypeError: function takes exactly " + (format.length - kwonly)468 + " arguments");469 }470 // Set default value471 out[n] = spec[1];472 }473 474 return out;475 };476 py.PY_hasAttr = function (o, attr_name) {477 try {478 py.PY_getAttr(o, attr_name);479 return true;480 } catch (e) {481 return false;482 }483 };484 py.PY_getAttr = function (o, attr_name) {485 return PY_ensurepy(o.__getattribute__(attr_name));486 };487 py.PY_str = function (o) {488 var v = o.__str__();489 if (py.PY_isInstance(v, py.str)) {490 return v;491 }492 throw new Error(493 'TypeError: __str__ returned non-string (type '494 + typename(v)495 +')');496 };497 py.PY_isInstance = function (inst, cls) {498 var fn = function () {};499 fn.prototype = cls;500 return inst instanceof fn;501 };502 py.PY_isSubclass = function (derived, cls) {503 var fn = function () {};504 fn.prototype = cls;505 return derived === cls || derived instanceof fn;506 };507 py.PY_call = function (callable, args, kwargs) {508 if (!args) {509 args = []; kwargs = {};510 } else if (typeof args === 'object' && !(args instanceof Array)) {511 kwargs = args;512 args = [];513 } else if (!kwargs) {514 kwargs = {};515 }516 if (callable.__is_type) {517 // class hack518 var instance = callable.__new__.call(callable, args, kwargs);519 var typ = function () {};520 typ.prototype = callable;521 if (instance instanceof typ) {522 instance.__init__.call(instance, args, kwargs);523 }524 return instance525 }526 return callable.__call__(args, kwargs);527 };528 py.PY_isTrue = function (o) {529 var res = o.__nonzero__();530 if (res === py.True) {531 return true;532 }533 if (res === py.False) {534 return false;535 }536 throw new Error(537 "TypeError: __nonzero__ should return bool, returned "538 + typename(res));539 };540 py.PY_not = function (o) {541 return !py.PY_isTrue(o);542 };543 py.PY_size = function (o) {544 if (!o.__len__) {545 throw new Error(546 "TypeError: object of type '" +547 typename(o) +548 "' has no len()");549 }550 var v = o.__len__();551 if (typeof v !== 'number') {552 throw new Error("TypeError: a number is required");553 }554 return v;555 };556 py.PY_getItem = function (o, key) {557 if (!('__getitem__' in o)) {558 throw new Error(559 "TypeError: '" + typename(o) +560 "' object is unsubscriptable")561 }562 if (!py.PY_isInstance(key, py.object)) {563 throw new Error(564 "TypeError: '" + typename(key) +565 "' is not a py.js object");566 }567 var res = o.__getitem__(key);568 if (!py.PY_isInstance(key, py.object)) {569 throw new Error(570 "TypeError: __getitem__ must return a py.js object, got "571 + typename(res));572 }573 return res;574 };575 py.PY_setItem = function (o, key, v) {576 if (!('__setitem__' in o)) {577 throw new Error(578 "TypeError: '" + typename(o) +579 "' object does not support item assignment");580 }581 if (!py.PY_isInstance(key, py.object)) {582 throw new Error(583 "TypeError: '" + typename(key) +584 "' is not a py.js object");585 }586 if (!py.PY_isInstance(v, py.object)) {587 throw new Error(588 "TypeError: '" + typename(v) +589 "' is not a py.js object");590 }591 o.__setitem__(key, v);592 };593 py.PY_add = function (o1, o2) {594 return PY_op(o1, o2, '+');595 };596 py.PY_subtract = function (o1, o2) {597 return PY_op(o1, o2, '-');598 };599 py.PY_multiply = function (o1, o2) {600 return PY_op(o1, o2, '*');601 };602 py.PY_divide = function (o1, o2) {603 return PY_op(o1, o2, '/');604 };605 py.PY_negative = function (o) {606 if (!o.__neg__) {607 throw new Error(608 "TypeError: bad operand for unary -: '"609 + typename(o)610 + "'");611 }612 return o.__neg__();613 };614 py.PY_positive = function (o) {615 if (!o.__pos__) {616 throw new Error(617 "TypeError: bad operand for unary +: '"618 + typename(o)619 + "'");620 }621 return o.__pos__();622 };623 // Builtins624 py.type = function type(name, bases, dict) {625 if (typeof name !== 'string') {626 throw new Error("ValueError: a class name should be a string");627 }628 if (!bases || bases.length === 0) {629 bases = [py.object];630 } else if (bases.length > 1) {631 throw new Error("ValueError: can't provide multiple bases for a "632 + "new type");633 }634 var base = bases[0];635 var ClassObj = create(base);636 if (dict) {637 for (var k in dict) {638 if (!dict.hasOwnProperty(k)) { continue; }639 ClassObj[k] = dict[k];640 }641 }642 ClassObj.__class__ = ClassObj;643 ClassObj.__name__ = name;644 ClassObj.__bases__ = bases;645 ClassObj.__is_type = true;646 return ClassObj;647 };648 py.type.__call__ = function () {649 var args = py.PY_parseArgs(arguments, ['object']);650 return args.object.__class__;651 };652 var hash_counter = 0;653 py.object = py.type('object', [{}], {654 __new__: function () {655 // If ``this`` isn't the class object, this is going to be656 // beyond fucked up657 var inst = create(this);658 inst.__is_type = false;659 return inst;660 },661 __init__: function () {},662 // Basic customization663 __hash__: function () {664 if (this._hash) {665 return this._hash;666 }667 // tagged counter, to avoid collisions with e.g. number hashes668 return this._hash = '\0\0\0' + String(hash_counter++);669 },670 __eq__: function (other) {671 return (this === other) ? py.True : py.False;672 },673 __ne__: function (other) {674 if (py.PY_isTrue(this.__eq__(other))) {675 return py.False;676 } else {677 return py.True;678 }679 },680 __lt__: function () { return py.NotImplemented; },681 __le__: function () { return py.NotImplemented; },682 __ge__: function () { return py.NotImplemented; },683 __gt__: function () { return py.NotImplemented; },684 __str__: function () {685 return this.__unicode__();686 },687 __unicode__: function () {688 return py.str.fromJSON('<' + typename(this) + ' object>');689 },690 __nonzero__: function () {691 return py.True;692 },693 // Attribute access694 __getattribute__: function (name) {695 if (name in this) {696 var val = this[name];697 if (typeof val === 'object' && '__get__' in val) {698 // TODO: second argument should be class699 return val.__get__(this, py.PY_call(py.type, [this]));700 }701 if (typeof val === 'function' && !this.hasOwnProperty(name)) {702 // val is a method from the class703 return PY_instancemethod.fromJSON(val, this);704 }705 return val;706 }707 if ('__getattr__' in this) {708 return this.__getattr__(name);709 }710 throw new Error("AttributeError: object has no attribute '" + name +"'");711 },712 __setattr__: function (name, value) {713 if (name in this && '__set__' in this[name]) {714 this[name].__set__(this, value);715 }716 this[name] = value;717 },718 // no delattr, because no 'del' statement719 // Conversion720 toJSON: function () {721 throw new Error(this.constructor.name + ' can not be converted to JSON');722 }723 });724 var NoneType = py.type('NoneType', null, {725 __nonzero__: function () { return py.False; },726 toJSON: function () { return null; }727 });728 py.None = py.PY_call(NoneType);729 var NotImplementedType = py.type('NotImplementedType', null, {});730 py.NotImplemented = py.PY_call(NotImplementedType);731 var booleans_initialized = false;732 py.bool = py.type('bool', null, {733 __new__: function () {734 if (!booleans_initialized) {735 return py.object.__new__.apply(this);736 }737 var ph = {};738 var args = py.PY_parseArgs(arguments, [['value', ph]]);739 if (args.value === ph) {740 return py.False;741 }742 return py.PY_isTrue(args.value) ? py.True : py.False;743 },744 __str__: function () {745 return py.str.fromJSON((this === py.True) ? "True" : "False");746 },747 __nonzero__: function () { return this; },748 fromJSON: function (val) { return val ? py.True : py.False },749 toJSON: function () { return this === py.True; }750 });751 py.True = py.PY_call(py.bool);752 py.False = py.PY_call(py.bool);753 booleans_initialized = true;754 py.float = py.type('float', null, {755 __init__: function () {756 var placeholder = {};757 var args = py.PY_parseArgs(arguments, [['value', placeholder]]);758 var value = args.value;759 if (value === placeholder) {760 this._value = 0; return;761 }762 if (py.PY_isInstance(value, py.float)) {763 this._value = value._value;764 }765 if (py.PY_isInstance(value, py.object) && '__float__' in value) {766 var res = value.__float__();767 if (py.PY_isInstance(res, py.float)) {768 this._value = res._value;769 return;770 }771 throw new Error('TypeError: __float__ returned non-float (type ' +772 typename(res) + ')');773 }774 throw new Error('TypeError: float() argument must be a string or a number');775 },776 __str__: function () {777 return py.str.fromJSON(String(this._value));778 },779 __eq__: function (other) {780 return this._value === other._value ? py.True : py.False;781 },782 __lt__: function (other) {783 if (!py.PY_isInstance(other, py.float)) {784 return py.NotImplemented;785 }786 return this._value < other._value ? py.True : py.False;787 },788 __le__: function (other) {789 if (!py.PY_isInstance(other, py.float)) {790 return py.NotImplemented;791 }792 return this._value <= other._value ? py.True : py.False;793 },794 __gt__: function (other) {795 if (!py.PY_isInstance(other, py.float)) {796 return py.NotImplemented;797 }798 return this._value > other._value ? py.True : py.False;799 },800 __ge__: function (other) {801 if (!py.PY_isInstance(other, py.float)) {802 return py.NotImplemented;803 }804 return this._value >= other._value ? py.True : py.False;805 },806 __abs__: function () {807 return py.float.fromJSON(808 Math.abs(this._value));809 },810 __add__: function (other) {811 if (!py.PY_isInstance(other, py.float)) {812 return py.NotImplemented;813 }814 return py.float.fromJSON(this._value + other._value);815 },816 __neg__: function () {817 return py.float.fromJSON(-this._value);818 },819 __sub__: function (other) {820 if (!py.PY_isInstance(other, py.float)) {821 return py.NotImplemented;822 }823 return py.float.fromJSON(this._value - other._value);824 },825 __mul__: function (other) {826 if (!py.PY_isInstance(other, py.float)) {827 return py.NotImplemented;828 }829 return py.float.fromJSON(this._value * other._value);830 },831 __div__: function (other) {832 if (!py.PY_isInstance(other, py.float)) {833 return py.NotImplemented;834 }835 return py.float.fromJSON(this._value / other._value);836 },837 __nonzero__: function () {838 return this._value ? py.True : py.False;839 },840 fromJSON: function (v) {841 if (!(typeof v === 'number')) {842 throw new Error('py.float.fromJSON can only take numbers');843 }844 var instance = py.PY_call(py.float);845 instance._value = v;846 return instance;847 },848 toJSON: function () {849 return this._value;850 }851 });852 py.str = py.type('str', null, {853 __init__: function () {854 var placeholder = {};855 var args = py.PY_parseArgs(arguments, [['value', placeholder]]);856 var s = args.value;857 if (s === placeholder) { this._value = ''; return; }858 this._value = py.PY_str(s)._value;859 },860 __hash__: function () {861 return '\1\0\1' + this._value;862 },863 __str__: function () {864 return this;865 },866 __eq__: function (other) {867 if (py.PY_isInstance(other, py.str)868 && this._value === other._value) {869 return py.True;870 }871 return py.False;872 },873 __lt__: function (other) {874 if (py.PY_not(py.PY_call(py.isinstance, [other, py.str]))) {875 return py.NotImplemented;876 }877 return this._value < other._value ? py.True : py.False;878 },879 __le__: function (other) {880 if (!py.PY_isInstance(other, py.str)) {881 return py.NotImplemented;882 }883 return this._value <= other._value ? py.True : py.False;884 },885 __gt__: function (other) {886 if (!py.PY_isInstance(other, py.str)) {887 return py.NotImplemented;888 }889 return this._value > other._value ? py.True : py.False;890 },891 __ge__: function (other) {892 if (!py.PY_isInstance(other, py.str)) {893 return py.NotImplemented;894 }895 return this._value >= other._value ? py.True : py.False;896 },897 __add__: function (other) {898 if (!py.PY_isInstance(other, py.str)) {899 return py.NotImplemented;900 }901 return py.str.fromJSON(this._value + other._value);902 },903 __nonzero__: function () {904 return this._value.length ? py.True : py.False;905 },906 __contains__: function (s) {907 return (this._value.indexOf(s._value) !== -1) ? py.True : py.False;908 },909 fromJSON: function (s) {910 if (typeof s === 'string') {911 var instance = py.PY_call(py.str);912 instance._value = s;913 return instance;914 }915 throw new Error("str.fromJSON can only take strings");916 },917 toJSON: function () {918 return this._value;919 }920 });921 py.tuple = py.type('tuple', null, {922 __init__: function () {923 this._values = [];924 },925 __contains__: function (value) {926 for(var i=0, len=this._values.length; i<len; ++i) {927 if (py.PY_isTrue(this._values[i].__eq__(value))) {928 return py.True;929 }930 }931 return py.False;932 },933 __getitem__: function (index) {934 return this._values[index.toJSON()];935 },936 toJSON: function () {937 var out = [];938 for (var i=0; i<this._values.length; ++i) {939 out.push(this._values[i].toJSON());940 }941 return out;942 },943 fromJSON: function (ar) {944 if (!(ar instanceof Array)) {945 throw new Error("Can only create a py.tuple from an Array");946 }947 var t = py.PY_call(py.tuple);948 for(var i=0; i<ar.length; ++i) {949 t._values.push(PY_ensurepy(ar[i]));950 }951 return t;952 }953 });954 py.list = py.tuple;955 py.dict = py.type('dict', null, {956 __init__: function () {957 this._store = {};958 },959 __getitem__: function (key) {960 var h = key.__hash__();961 if (!(h in this._store)) {962 throw new Error("KeyError: '" + key.toJSON() + "'");963 }964 return this._store[h][1];965 },966 __setitem__: function (key, value) {967 this._store[key.__hash__()] = [key, value];968 },969 get: function () {970 var args = py.PY_parseArgs(arguments, ['k', ['d', py.None]]);971 var h = args.k.__hash__();972 if (!(h in this._store)) {973 return args.d;974 }975 return this._store[h][1];976 },977 fromJSON: function (d) {978 var instance = py.PY_call(py.dict);979 for (var k in (d || {})) {980 if (!d.hasOwnProperty(k)) { continue; }981 instance.__setitem__(982 py.str.fromJSON(k),983 PY_ensurepy(d[k]));984 }985 return instance;986 },987 toJSON: function () {988 var out = {};989 for(var k in this._store) {990 var item = this._store[k];991 out[item[0].toJSON()] = item[1].toJSON();992 }993 return out;994 }995 });996 py.PY_def = py.type('function', null, {997 __call__: function () {998 // don't want to rewrite __call__ for instancemethod999 return this._func.apply(this._inst, arguments);1000 },1001 fromJSON: function (nativefunc) {1002 var instance = py.PY_call(py.PY_def);1003 instance._inst = null;1004 instance._func = nativefunc;1005 return instance;1006 },1007 toJSON: function () {1008 return this._func;1009 }1010 });1011 py.classmethod = py.type('classmethod', null, {1012 __init__: function () {1013 var args = py.PY_parseArgs(arguments, 'function');1014 this._func = args['function'];1015 },1016 __get__: function (obj, type) {1017 return PY_instancemethod.fromJSON(this._func, type);1018 },1019 fromJSON: function (func) {1020 return py.PY_call(py.classmethod, [func]);1021 }1022 });1023 var PY_instancemethod = py.type('instancemethod', [py.PY_def], {1024 fromJSON: function (nativefunc, instance) {1025 var inst = py.PY_call(PY_instancemethod);1026 // could also use bind?1027 inst._inst = instance;1028 inst._func = nativefunc;1029 return inst;1030 }1031 });1032 py.abs = new py.PY_def.fromJSON(function abs() {1033 var args = py.PY_parseArgs(arguments, ['number']);1034 if (!args.number.__abs__) {1035 throw new Error(1036 "TypeError: bad operand type for abs(): '"1037 + typename(args.number)1038 + "'");1039 }1040 return args.number.__abs__();1041 });1042 py.len = new py.PY_def.fromJSON(function len() {1043 var args = py.PY_parseArgs(arguments, ['object']);1044 return py.float.fromJSON(py.PY_size(args.object));1045 });1046 py.isinstance = new py.PY_def.fromJSON(function isinstance() {1047 var args = py.PY_parseArgs(arguments, ['object', 'class']);1048 return py.PY_isInstance(args.object, args['class'])1049 ? py.True : py.False;1050 });1051 py.issubclass = new py.PY_def.fromJSON(function issubclass() {1052 var args = py.PY_parseArgs(arguments, ['C', 'B']);1053 return py.PY_isSubclass(args.C, args.B)1054 ? py.True : py.False;1055 });1056 /**1057 * Implements the decoding of Python string literals (embedded in1058 * JS strings) into actual JS strings. This includes the decoding1059 * of escapes into their corresponding JS1060 * characters/codepoints/whatever.1061 *1062 * The ``unicode`` flags notes whether the literal should be1063 * decoded as a bytestring literal or a unicode literal, which1064 * pretty much only impacts decoding (or not) of unicode escapes1065 * at this point since bytestrings are not technically handled1066 * (everything is decoded to JS "unicode" strings)1067 *1068 * Eventurally, ``str`` could eventually use typed arrays, that'd1069 * be interesting...1070 */1071 var PY_decode_string_literal = function (str, unicode) {1072 var out = [], code;1073 // Directly maps a single escape code to an output1074 // character1075 var direct_map = {1076 '\\': '\\',1077 '"': '"',1078 "'": "'",1079 'a': '\x07',1080 'b': '\x08',1081 'f': '\x0c',1082 'n': '\n',1083 'r': '\r',1084 't': '\t',1085 'v': '\v'1086 };1087 for (var i=0; i<str.length; ++i) {1088 if (str[i] !== '\\') {1089 out.push(str[i]);1090 continue;1091 }1092 var escape = str[i+1];1093 if (escape in direct_map) {1094 out.push(direct_map[escape]);1095 ++i;1096 continue;1097 }1098 switch (escape) {1099 // Ignored1100 case '\n': ++i; continue;1101 // Character named name in the Unicode database (Unicode only)1102 case 'N':1103 if (!unicode) { break; }1104 throw Error("SyntaxError: \\N{} escape not implemented");1105 case 'u':1106 if (!unicode) { break; }1107 var uni = str.slice(i+2, i+6);1108 if (!/[0-9a-f]{4}/i.test(uni)) {1109 throw new Error([1110 "SyntaxError: (unicode error) 'unicodeescape' codec",1111 " can't decode bytes in position ",1112 i, "-", i+4,1113 ": truncated \\uXXXX escape"1114 ].join(''));1115 }1116 code = parseInt(uni, 16);1117 out.push(String.fromCharCode(code));1118 // escape + 4 hex digits1119 i += 5;1120 continue;1121 case 'U':1122 if (!unicode) { break; }1123 // TODO: String.fromCodePoint1124 throw Error("SyntaxError: \\U escape not implemented");1125 case 'x':1126 // get 2 hex digits1127 var hex = str.slice(i+2, i+4);1128 if (!/[0-9a-f]{2}/i.test(hex)) {1129 if (!unicode) {1130 throw new Error('ValueError: invalid \\x escape');1131 }1132 throw new Error([1133 "SyntaxError: (unicode error) 'unicodeescape'",1134 " codec can't decode bytes in position ",1135 i, '-', i+2,1136 ": truncated \\xXX escape"1137 ].join(''))1138 }1139 code = parseInt(hex, 16);1140 out.push(String.fromCharCode(code));1141 // skip escape + 2 hex digits1142 i += 3;1143 continue;1144 default:1145 // Check if octal1146 if (!/[0-8]/.test(escape)) { break; }1147 var r = /[0-8]{1,3}/g;1148 r.lastIndex = i+1;1149 var m = r.exec(str);1150 var oct = m[0];1151 code = parseInt(oct, 8);1152 out.push(String.fromCharCode(code));1153 // skip matchlength1154 i += oct.length;1155 continue;1156 }1157 out.push('\\');1158 }1159 return out.join('');1160 };1161 // All binary operators with fallbacks, so they can be applied generically1162 var PY_operators = {1163 '==': ['eq', 'eq', function (a, b) { return a === b; }],1164 '!=': ['ne', 'ne', function (a, b) { return a !== b; }],1165 '<>': ['ne', 'ne', function (a, b) { return a !== b; }],1166 '<': ['lt', 'gt', function (a, b) {return a.__class__.__name__ < b.__class__.__name__;}],1167 '<=': ['le', 'ge', function (a, b) {return a.__class__.__name__ <= b.__class__.__name__;}],1168 '>': ['gt', 'lt', function (a, b) {return a.__class__.__name__ > b.__class__.__name__;}],1169 '>=': ['ge', 'le', function (a, b) {return a.__class__.__name__ >= b.__class__.__name__;}],1170 '+': ['add', 'radd'],1171 '-': ['sub', 'rsub'],1172 '*': ['mul', 'rmul'],1173 '/': ['div', 'rdiv'],1174 '//': ['floordiv', 'rfloordiv'],1175 '%': ['mod', 'rmod'],1176 '**': ['pow', 'rpow'],1177 '<<': ['lshift', 'rlshift'],1178 '>>': ['rshift', 'rrshift'],1179 '&': ['and', 'rand'],1180 '^': ['xor', 'rxor'],1181 '|': ['or', 'ror']1182 };1183 /**1184 * Implements operator fallback/reflection.1185 *1186 * First two arguments are the objects to apply the operator on,1187 * in their actual order (ltr).1188 *1189 * Third argument is the actual operator.1190 *1191 * If the operator methods raise exceptions, those exceptions are1192 * not intercepted.1193 */1194 var PY_op = function (o1, o2, op) {1195 var r;1196 var methods = PY_operators[op];1197 var forward = '__' + methods[0] + '__', reverse = '__' + methods[1] + '__';1198 var otherwise = methods[2];1199 if (forward in o1 && (r = o1[forward](o2)) !== py.NotImplemented) {1200 return r;1201 }1202 if (reverse in o2 && (r = o2[reverse](o1)) !== py.NotImplemented) {1203 return r;1204 }1205 if (otherwise) {1206 return PY_ensurepy(otherwise(o1, o2));1207 }1208 throw new Error(1209 "TypeError: unsupported operand type(s) for " + op + ": '"1210 + typename(o1) + "' and '" + typename(o2) + "'");1211 };1212 var PY_builtins = {1213 type: py.type,1214 None: py.None,1215 True: py.True,1216 False: py.False,1217 NotImplemented: py.NotImplemented,1218 object: py.object,1219 bool: py.bool,1220 float: py.float,1221 str: py.str,1222 unicode: py.unicode,1223 tuple: py.tuple,1224 list: py.list,1225 dict: py.dict,1226 abs: py.abs,1227 len: py.len,1228 isinstance: py.isinstance,1229 issubclass: py.issubclass,1230 classmethod: py.classmethod,1231 };1232 py.parse = function (toks) {1233 var index = 0;1234 token = toks[0];1235 next = function () { return toks[++index]; };1236 return expression();1237 };1238 var evaluate_operator = function (operator, a, b) {1239 switch (operator) {1240 case 'is': return a === b ? py.True : py.False;1241 case 'is not': return a !== b ? py.True : py.False;1242 case 'in':1243 return b.__contains__(a);1244 case 'not in':1245 return py.PY_isTrue(b.__contains__(a)) ? py.False : py.True;1246 case '==': case '!=': case '<>':1247 case '<': case '<=':1248 case '>': case '>=':1249 return PY_op(a, b, operator);1250 }1251 throw new Error('SyntaxError: unknown comparator [[' + operator + ']]');1252 };1253 py.evaluate = function (expr, context) {1254 context = context || {};1255 switch (expr.id) {1256 case '(name)':1257 var val = context[expr.value];1258 if (val === undefined && expr.value in PY_builtins) {1259 return PY_builtins[expr.value];1260 }1261 return PY_ensurepy(val, expr.value);1262 case '(string)':1263 return py.str.fromJSON(PY_decode_string_literal(1264 expr.value, expr.unicode));1265 case '(number)':1266 return py.float.fromJSON(expr.value);1267 case '(constant)':1268 switch (expr.value) {1269 case 'None': return py.None;1270 case 'False': return py.False;1271 case 'True': return py.True;1272 }1273 throw new Error("SyntaxError: unknown constant '" + expr.value + "'");1274 case '(comparator)':1275 var result, left = py.evaluate(expr.expressions[0], context);...

Full Screen

Full Screen

pyeval.js

Source:pyeval.js Github

copy

Full Screen

1/*2 * py.js helpers and setup3 */4openerp.web.pyeval = function (instance) {5 instance.web.pyeval = {};6 var obj = function () {};7 obj.prototype = py.object;8 var asJS = function (arg) {9 if (arg instanceof obj) {10 return arg.toJSON();11 }12 return arg;13 };14 var datetime = py.PY_call(py.object);15 /**16 * computes (Math.floor(a/b), a%b and passes that to the callback.17 *18 * returns the callback's result19 */20 var divmod = function (a, b, fn) {21 var mod = a%b;22 // in python, sign(a % b) === sign(b). Not in JS. If wrong side, add a23 // round of b24 if (mod > 0 && b < 0 || mod < 0 && b > 0) {25 mod += b;26 }27 return fn(Math.floor(a/b), mod);28 };29 /**30 * Passes the fractional and integer parts of x to the callback, returns31 * the callback's result32 */33 var modf = function (x, fn) {34 var mod = x%1;35 if (mod < 0) {36 mod += 1;37 }38 return fn(mod, Math.floor(x));39 };40 var zero = py.float.fromJSON(0);41 // Port from pypy/lib_pypy/datetime.py42 var DAYS_IN_MONTH = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];43 var DAYS_BEFORE_MONTH = [null];44 var dbm = 0;45 for (var i=1; i<DAYS_IN_MONTH.length; ++i) {46 DAYS_BEFORE_MONTH.push(dbm);47 dbm += DAYS_IN_MONTH[i];48 }49 var is_leap = function (year) {50 return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);51 };52 var days_before_year = function (year) {53 var y = year - 1;54 return y*365 + Math.floor(y/4) - Math.floor(y/100) + Math.floor(y/400);55 };56 var days_in_month = function (year, month) {57 if (month === 2 && is_leap(year)) {58 return 29;59 }60 return DAYS_IN_MONTH[month];61 };62 var days_before_month = function (year, month) {63 var post_leap_feb = month > 2 && is_leap(year);64 return DAYS_BEFORE_MONTH[month]65 + (post_leap_feb ? 1 : 0);66 };67 var ymd2ord = function (year, month, day) {68 var dim = days_in_month(year, month);69 if (!(1 <= day && day <= dim)) {70 throw new Error("ValueError: day must be in 1.." + dim);71 }72 return days_before_year(year)73 + days_before_month(year, month)74 + day;75 };76 var DI400Y = days_before_year(401);77 var DI100Y = days_before_year(101);78 var DI4Y = days_before_year(5);79 var assert = function (bool) {80 if (!bool) {81 throw new Error("AssertionError");82 }83 };84 var ord2ymd = function (n) {85 --n;86 var n400, n100, n4, n1, n0;87 divmod(n, DI400Y, function (_n400, n) {88 n400 = _n400;89 divmod(n, DI100Y, function (_n100, n) {90 n100 = _n100;91 divmod(n, DI4Y, function (_n4, n) {92 n4 = _n4;93 divmod(n, 365, function (_n1, n) {94 n1 = _n1;95 n0 = n;96 })97 });98 });99 });100 n = n0;101 var year = n400 * 400 + 1 + n100 * 100 + n4 * 4 + n1;102 if (n1 == 4 || n100 == 100) {103 assert(n0 === 0);104 return {105 year: year - 1,106 month: 12,107 day: 31108 };109 }110 var leapyear = n1 === 3 && (n4 !== 24 || n100 == 3);111 assert(leapyear == is_leap(year));112 var month = (n + 50) >> 5;113 var preceding = DAYS_BEFORE_MONTH[month] + ((month > 2 && leapyear) ? 1 : 0);114 if (preceding > n) {115 --month;116 preceding -= DAYS_IN_MONTH[month] + ((month === 2 && leapyear) ? 1 : 0);117 }118 n -= preceding;119 return {120 year: year,121 month: month,122 day: n+1123 };124 };125 /**126 * Converts the stuff passed in into a valid date, applying overflows as needed127 */128 var tmxxx = function (year, month, day, hour, minute, second, microsecond) {129 hour = hour || 0; minute = minute || 0; second = second || 0;130 microsecond = microsecond || 0;131 if (microsecond < 0 || microsecond > 999999) {132 divmod(microsecond, 1000000, function (carry, ms) {133 microsecond = ms;134 second += carry135 });136 }137 if (second < 0 || second > 59) {138 divmod(second, 60, function (carry, s) {139 second = s;140 minute += carry;141 });142 }143 if (minute < 0 || minute > 59) {144 divmod(minute, 60, function (carry, m) {145 minute = m;146 hour += carry;147 })148 }149 if (hour < 0 || hour > 23) {150 divmod(hour, 24, function (carry, h) {151 hour = h;152 day += carry;153 })154 }155 // That was easy. Now it gets muddy: the proper range for day156 // can't be determined without knowing the correct month and year,157 // but if day is, e.g., plus or minus a million, the current month158 // and year values make no sense (and may also be out of bounds159 // themselves).160 // Saying 12 months == 1 year should be non-controversial.161 if (month < 1 || month > 12) {162 divmod(month-1, 12, function (carry, m) {163 month = m + 1;164 year += carry;165 })166 }167 // Now only day can be out of bounds (year may also be out of bounds168 // for a datetime object, but we don't care about that here).169 // If day is out of bounds, what to do is arguable, but at least the170 // method here is principled and explainable.171 var dim = days_in_month(year, month);172 if (day < 1 || day > dim) {173 // Move day-1 days from the first of the month. First try to174 // get off cheap if we're only one day out of range (adjustments175 // for timezone alone can't be worse than that).176 if (day === 0) {177 --month;178 if (month > 0) {179 day = days_in_month(year, month);180 } else {181 --year; month=12; day=31;182 }183 } else if (day == dim + 1) {184 ++month;185 day = 1;186 if (month > 12) {187 month = 1;188 ++year;189 }190 } else {191 var r = ord2ymd(ymd2ord(year, month, 1) + (day - 1));192 year = r.year;193 month = r.month;194 day = r.day;195 }196 }197 return {198 year: year,199 month: month,200 day: day,201 hour: hour,202 minute: minute,203 second: second,204 microsecond: microsecond205 };206 };207 datetime.timedelta = py.type('timedelta', null, {208 __init__: function () {209 var args = py.PY_parseArgs(arguments, [210 ['days', zero], ['seconds', zero], ['microseconds', zero],211 ['milliseconds', zero], ['minutes', zero], ['hours', zero],212 ['weeks', zero]213 ]);214 var d = 0, s = 0, m = 0;215 var days = args.days.toJSON() + args.weeks.toJSON() * 7;216 var seconds = args.seconds.toJSON()217 + args.minutes.toJSON() * 60218 + args.hours.toJSON() * 3600;219 var microseconds = args.microseconds.toJSON()220 + args.milliseconds.toJSON() * 1000;221 // Get rid of all fractions, and normalize s and us.222 // Take a deep breath <wink>.223 var daysecondsfrac = modf(days, function (dayfrac, days) {224 d = days;225 if (dayfrac) {226 return modf(dayfrac * 24 * 3600, function (dsf, dsw) {227 s = dsw;228 return dsf;229 });230 }231 return 0;232 });233 var secondsfrac = modf(seconds, function (sf, s) {234 seconds = s;235 return sf + daysecondsfrac;236 });237 divmod(seconds, 24*3600, function (days, seconds) {238 d += days;239 s += seconds240 });241 // seconds isn't referenced again before redefinition242 microseconds += secondsfrac * 1e6;243 divmod(microseconds, 1000000, function (seconds, microseconds) {244 divmod(seconds, 24*3600, function (days, seconds) {245 d += days;246 s += seconds;247 m += Math.round(microseconds);248 });249 });250 // Carrying still possible here?251 this.days = d;252 this.seconds = s;253 this.microseconds = m;254 },255 __str__: function () {256 var hh, mm, ss;257 divmod(this.seconds, 60, function (m, s) {258 divmod(m, 60, function (h, m) {259 hh = h;260 mm = m;261 ss = s;262 });263 });264 var s = _.str.sprintf("%d:%02d:%02d", hh, mm, ss);265 if (this.days) {266 s = _.str.sprintf("%d day%s, %s",267 this.days,268 (this.days != 1 && this.days != -1) ? 's' : '',269 s);270 }271 if (this.microseconds) {272 s = _.str.sprintf("%s.%06d", s, this.microseconds);273 }274 return py.str.fromJSON(s);275 },276 __eq__: function (other) {277 if (!py.PY_isInstance(other, datetime.timedelta)) {278 return py.False;279 }280 return (this.days === other.days281 && this.seconds === other.seconds282 && this.microseconds === other.microseconds)283 ? py.True : py.False;284 },285 __add__: function (other) {286 if (!py.PY_isInstance(other, datetime.timedelta)) {287 return py.NotImplemented;288 }289 return py.PY_call(datetime.timedelta, [290 py.float.fromJSON(this.days + other.days),291 py.float.fromJSON(this.seconds + other.seconds),292 py.float.fromJSON(this.microseconds + other.microseconds)293 ]);294 },295 __radd__: function (other) { return this.__add__(other); },296 __sub__: function (other) {297 if (!py.PY_isInstance(other, datetime.timedelta)) {298 return py.NotImplemented;299 }300 return py.PY_call(datetime.timedelta, [301 py.float.fromJSON(this.days - other.days),302 py.float.fromJSON(this.seconds - other.seconds),303 py.float.fromJSON(this.microseconds - other.microseconds)304 ]);305 },306 __rsub__: function (other) {307 if (!py.PY_isInstance(other, datetime.timedelta)) {308 return py.NotImplemented;309 }310 return this.__neg__().__add__(other);311 },312 __neg__: function () {313 return py.PY_call(datetime.timedelta, [314 py.float.fromJSON(-this.days),315 py.float.fromJSON(-this.seconds),316 py.float.fromJSON(-this.microseconds)317 ]);318 },319 __pos__: function () { return this; },320 __mul__: function (other) {321 if (!py.PY_isInstance(other, py.float)) {322 return py.NotImplemented;323 }324 var n = other.toJSON();325 return py.PY_call(datetime.timedelta, [326 py.float.fromJSON(this.days * n),327 py.float.fromJSON(this.seconds * n),328 py.float.fromJSON(this.microseconds * n)329 ]);330 },331 __rmul__: function (other) { return this.__mul__(other); },332 __div__: function (other) {333 if (!py.PY_isInstance(other, py.float)) {334 return py.NotImplemented;335 }336 var usec = ((this.days * 24 * 3600) + this.seconds) * 1000000337 + this.microseconds;338 return py.PY_call(339 datetime.timedelta, [340 zero, zero, py.float.fromJSON(usec / other.toJSON())]);341 },342 __floordiv__: function (other) { return this.__div__(other); },343 total_seconds: function () {344 return py.float.fromJSON(345 this.days * 86400346 + this.seconds347 + this.microseconds / 1000000)348 },349 __nonzero__: function () {350 return (!!this.days || !!this.seconds || !!this.microseconds)351 ? py.True352 : py.False;353 }354 });355 datetime.datetime = py.type('datetime', null, {356 __init__: function () {357 var zero = py.float.fromJSON(0);358 var args = py.PY_parseArgs(arguments, [359 'year', 'month', 'day',360 ['hour', zero], ['minute', zero], ['second', zero],361 ['microsecond', zero], ['tzinfo', py.None]362 ]);363 for(var key in args) {364 if (!args.hasOwnProperty(key)) { continue; }365 this[key] = asJS(args[key]);366 }367 },368 strftime: function () {369 var self = this;370 var args = py.PY_parseArgs(arguments, 'format');371 return py.str.fromJSON(args.format.toJSON()372 .replace(/%([A-Za-z])/g, function (m, c) {373 switch (c) {374 case 'Y': return self.year;375 case 'm': return _.str.sprintf('%02d', self.month);376 case 'd': return _.str.sprintf('%02d', self.day);377 case 'H': return _.str.sprintf('%02d', self.hour);378 case 'M': return _.str.sprintf('%02d', self.minute);379 case 'S': return _.str.sprintf('%02d', self.second);380 }381 throw new Error('ValueError: No known conversion for ' + m);382 }));383 },384 now: py.classmethod.fromJSON(function () {385 var d = new Date();386 return py.PY_call(datetime.datetime,387 [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(),388 d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(),389 d.getUTCMilliseconds() * 1000]);390 }),391 combine: py.classmethod.fromJSON(function () {392 var args = py.PY_parseArgs(arguments, 'date time');393 return py.PY_call(datetime.datetime, [394 py.PY_getAttr(args.date, 'year'),395 py.PY_getAttr(args.date, 'month'),396 py.PY_getAttr(args.date, 'day'),397 py.PY_getAttr(args.time, 'hour'),398 py.PY_getAttr(args.time, 'minute'),399 py.PY_getAttr(args.time, 'second')400 ]);401 }),402 toJSON: function () {403 return new Date(404 this.year,405 this.month - 1,406 this.day,407 this.hour,408 this.minute,409 this.second,410 this.microsecond / 1000);411 },412 });413 datetime.date = py.type('date', null, {414 __init__: function () {415 var args = py.PY_parseArgs(arguments, 'year month day');416 this.year = asJS(args.year);417 this.month = asJS(args.month);418 this.day = asJS(args.day);419 },420 strftime: function () {421 var self = this;422 var args = py.PY_parseArgs(arguments, 'format');423 return py.str.fromJSON(args.format.toJSON()424 .replace(/%([A-Za-z])/g, function (m, c) {425 switch (c) {426 case 'Y': return self.year;427 case 'm': return _.str.sprintf('%02d', self.month);428 case 'd': return _.str.sprintf('%02d', self.day);429 }430 throw new Error('ValueError: No known conversion for ' + m);431 }));432 },433 __eq__: function (other) {434 return (this.year === other.year435 && this.month === other.month436 && this.day === other.day)437 ? py.True : py.False;438 },439 __add__: function (other) {440 if (!py.PY_isInstance(other, datetime.timedelta)) {441 return py.NotImplemented;442 }443 var s = tmxxx(this.year, this.month, this.day + other.days);444 return datetime.date.fromJSON(s.year, s.month, s.day);445 },446 __radd__: function (other) { return this.__add__(other); },447 __sub__: function (other) {448 if (py.PY_isInstance(other, datetime.timedelta)) {449 return this.__add__(other.__neg__());450 }451 if (py.PY_isInstance(other, datetime.date)) {452 // FIXME: getattr and sub API methods453 return py.PY_call(datetime.timedelta, [454 py.PY_subtract(455 py.PY_call(py.PY_getAttr(this, 'toordinal')),456 py.PY_call(py.PY_getAttr(other, 'toordinal')))457 ]);458 }459 return py.NotImplemented;460 },461 toordinal: function () {462 return py.float.fromJSON(ymd2ord(this.year, this.month, this.day));463 },464 fromJSON: function (year, month, day) {465 return py.PY_call(datetime.date, [year, month, day])466 }467 });468 /**469 Returns the current local date, which means the date on the client (which can be different470 compared to the date of the server).471 @return {datetime.date}472 */473 var context_today = function() {474 var d = new Date();475 return py.PY_call(476 datetime.date, [d.getFullYear(), d.getMonth() + 1, d.getDate()]);477 };478 datetime.time = py.type('time', null, {479 __init__: function () {480 var zero = py.float.fromJSON(0);481 var args = py.PY_parseArgs(arguments, [482 ['hour', zero], ['minute', zero], ['second', zero], ['microsecond', zero],483 ['tzinfo', py.None]484 ]);485 for(var k in args) {486 if (!args.hasOwnProperty(k)) { continue; }487 this[k] = asJS(args[k]);488 }489 }490 });491 var time = py.PY_call(py.object);492 time.strftime = py.PY_def.fromJSON(function () {493 var args = py.PY_parseArgs(arguments, 'format');494 var dt_class = py.PY_getAttr(datetime, 'datetime');495 var d = py.PY_call(py.PY_getAttr(dt_class, 'now'));496 return py.PY_call(py.PY_getAttr(d, 'strftime'), [args.format]);497 });498 var args = _.map(('year month day hour minute second microsecond '499 + 'years months weeks days hours minutes secondes microseconds '500 + 'weekday leakdays yearday nlyearday').split(' '), function (arg) {501 return [arg, null]502 });503 args.unshift('*');504 var relativedelta = py.type('relativedelta', null, {505 __init__: function () {506 this.ops = py.PY_parseArgs(arguments, args);507 },508 __add__: function (other) {509 if (!py.PY_isInstance(other, datetime.date)) {510 return py.NotImplemented;511 }512 // TODO: test this whole mess513 var year = asJS(this.ops.year) || asJS(other.year);514 if (asJS(this.ops.years)) {515 year += asJS(this.ops.years);516 }517 var month = asJS(this.ops.month) || asJS(other.month);518 if (asJS(this.ops.months)) {519 month += asJS(this.ops.months);520 // FIXME: no divmod in JS?521 while (month < 1) {522 year -= 1;523 month += 12;524 }525 while (month > 12) {526 year += 1;527 month -= 12;528 }529 }530 var lastMonthDay = new Date(year, month, 0).getDate();531 var day = asJS(this.ops.day) || asJS(other.day);532 if (day > lastMonthDay) { day = lastMonthDay; }533 var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);534 if (days_offset) {535 day = new Date(year, month-1, day + days_offset).getDate();536 }537 // TODO: leapdays?538 // TODO: hours, minutes, seconds? Not used in XML domains539 // TODO: weekday?540 // FIXME: use date.replace541 return py.PY_call(datetime.date, [542 py.float.fromJSON(year),543 py.float.fromJSON(month),544 py.float.fromJSON(day)545 ]);546 },547 __radd__: function (other) {548 return this.__add__(other);549 },550 __sub__: function (other) {551 if (!py.PY_isInstance(other, datetime.date)) {552 return py.NotImplemented;553 }554 // TODO: test this whole mess555 var year = asJS(this.ops.year) || asJS(other.year);556 if (asJS(this.ops.years)) {557 year -= asJS(this.ops.years);558 }559 var month = asJS(this.ops.month) || asJS(other.month);560 if (asJS(this.ops.months)) {561 month -= asJS(this.ops.months);562 // FIXME: no divmod in JS?563 while (month < 1) {564 year -= 1;565 month += 12;566 }567 while (month > 12) {568 year += 1;569 month -= 12;570 }571 }572 var lastMonthDay = new Date(year, month, 0).getDate();573 var day = asJS(this.ops.day) || asJS(other.day);574 if (day > lastMonthDay) { day = lastMonthDay; }575 var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0);576 if (days_offset) {577 day = new Date(year, month-1, day - days_offset).getDate();578 }579 // TODO: leapdays?580 // TODO: hours, minutes, seconds? Not used in XML domains581 // TODO: weekday?582 return py.PY_call(datetime.date, [583 py.float.fromJSON(year),584 py.float.fromJSON(month),585 py.float.fromJSON(day)586 ]);587 },588 __rsub__: function (other) {589 return this.__sub__(other);590 }591 });592 // recursively wraps JS objects passed into the context to attributedicts593 // which jsonify back to JS objects594 var wrap = function (value) {595 if (value === null) { return py.None; }596 switch (typeof value) {597 case 'undefined': throw new Error("No conversion for undefined");598 case 'boolean': return py.bool.fromJSON(value);599 case 'number': return py.float.fromJSON(value);600 case 'string': return py.str.fromJSON(value);601 }602 switch(value.constructor) {603 case Object: return wrapping_dict.fromJSON(value);604 case Array: return wrapping_list.fromJSON(value);605 }606 throw new Error("ValueError: unable to wrap " + value);607 };608 var wrapping_dict = py.type('wrapping_dict', null, {609 __init__: function () {610 this._store = {};611 },612 __getitem__: function (key) {613 var k = key.toJSON();614 if (!(k in this._store)) {615 throw new Error("KeyError: '" + k + "'");616 }617 return wrap(this._store[k]);618 },619 __getattr__: function (key) {620 return this.__getitem__(py.str.fromJSON(key));621 },622 get: function () {623 var args = py.PY_parseArgs(arguments, ['k', ['d', py.None]]);624 if (!(args.k.toJSON() in this._store)) { return args.d; }625 return this.__getitem__(args.k);626 },627 fromJSON: function (d) {628 var instance = py.PY_call(wrapping_dict);629 instance._store = d;630 return instance;631 },632 toJSON: function () {633 return this._store;634 },635 });636 var wrapping_list = py.type('wrapping_list', null, {637 __init__: function () {638 this._store = [];639 },640 __getitem__: function (index) {641 return wrap(this._store[index.toJSON()]);642 },643 fromJSON: function (ar) {644 var instance = py.PY_call(wrapping_list);645 instance._store = ar;646 return instance;647 },648 toJSON: function () {649 return this._store;650 },651 });652 var wrap_context = function (context) {653 for (var k in context) {654 if (!context.hasOwnProperty(k)) { continue; }655 var val = context[k];656 if (val === null) { continue; }657 if (val.constructor === Array) {658 context[k] = wrapping_list.fromJSON(val);659 } else if (val.constructor === Object660 && !py.PY_isInstance(val, py.object)) {661 context[k] = wrapping_dict.fromJSON(val);662 }663 }664 return context;665 };666 var eval_contexts = function (contexts, evaluation_context) {667 evaluation_context = _.extend(instance.web.pyeval.context(), evaluation_context || {});668 return _(contexts).reduce(function (result_context, ctx) {669 // __eval_context evaluations can lead to some of `contexts`'s670 // values being null, skip them as well as empty contexts671 if (_.isEmpty(ctx)) { return result_context; }672 if (_.isString(ctx)) {673 // wrap raw strings in context674 ctx = { __ref: 'context', __debug: ctx };675 }676 var evaluated = ctx;677 switch(ctx.__ref) {678 case 'context':679 evaluation_context.context = evaluation_context;680 evaluated = py.eval(ctx.__debug, wrap_context(evaluation_context));681 break;682 case 'compound_context':683 var eval_context = eval_contexts([ctx.__eval_context]);684 evaluated = eval_contexts(685 ctx.__contexts, _.extend({}, evaluation_context, eval_context));686 break;687 }688 // add newly evaluated context to evaluation context for following689 // siblings690 _.extend(evaluation_context, evaluated);691 return _.extend(result_context, evaluated);692 }, {});693 };694 var eval_domains = function (domains, evaluation_context) {695 evaluation_context = _.extend(instance.web.pyeval.context(), evaluation_context || {});696 var result_domain = [];697 _(domains).each(function (domain) {698 if (_.isString(domain)) {699 // wrap raw strings in domain700 domain = { __ref: 'domain', __debug: domain };701 }702 switch(domain.__ref) {703 case 'domain':704 evaluation_context.context = evaluation_context;705 result_domain.push.apply(706 result_domain, py.eval(domain.__debug, wrap_context(evaluation_context)));707 break;708 case 'compound_domain':709 var eval_context = eval_contexts([domain.__eval_context]);710 result_domain.push.apply(711 result_domain, eval_domains(712 domain.__domains, _.extend(713 {}, evaluation_context, eval_context)));714 break;715 default:716 result_domain.push.apply(result_domain, domain);717 }718 });719 return result_domain;720 };721 var eval_groupbys = function (contexts, evaluation_context) {722 evaluation_context = _.extend(instance.web.pyeval.context(), evaluation_context || {});723 var result_group = [];724 _(contexts).each(function (ctx) {725 if (_.isString(ctx)) {726 // wrap raw strings in context727 ctx = { __ref: 'context', __debug: ctx };728 }729 var group;730 var evaluated = ctx;731 switch(ctx.__ref) {732 case 'context':733 evaluation_context.context = evaluation_context;734 evaluated = py.eval(ctx.__debug, wrap_context(evaluation_context));735 break;736 case 'compound_context':737 var eval_context = eval_contexts([ctx.__eval_context]);738 evaluated = eval_contexts(739 ctx.__contexts, _.extend({}, evaluation_context, eval_context));740 break;741 }742 group = evaluated.group_by;743 if (!group) { return; }744 if (typeof group === 'string') {745 result_group.push(group);746 } else if (group instanceof Array) {747 result_group.push.apply(result_group, group);748 } else {749 throw new Error('Got invalid groupby {{'750 + JSON.stringify(group) + '}}');751 }752 _.extend(evaluation_context, evaluated);753 });754 return result_group;755 };756 instance.web.pyeval.context = function () {757 return _.extend({758 datetime: datetime,759 context_today: context_today,760 time: time,761 relativedelta: relativedelta,762 current_date: py.PY_call(763 time.strftime, [py.str.fromJSON('%Y-%m-%d')]),764 }, instance.session.user_context);765 };766 /**767 * @param {String} type "domains", "contexts" or "groupbys"768 * @param {Array} object domains or contexts to evaluate769 * @param {Object} [context] evaluation context770 */771 instance.web.pyeval.eval = function (type, object, context, options) {772 options = options || {};773 context = _.extend(instance.web.pyeval.context(), context || {});774 //noinspection FallthroughInSwitchStatementJS775 switch(type) {776 case 'context': object = [object];777 case 'contexts': return eval_contexts((options.no_user_context ? [] : [instance.session.user_context]).concat(object), context);778 case 'domain': object = [object];779 case 'domains': return eval_domains(object, context);780 case 'groupbys': return eval_groupbys(object, context);781 }782 throw new Error("Unknow evaluation type " + type)783 };784 var eval_arg = function (arg) {785 if (typeof arg !== 'object' || !arg.__ref) { return arg; }786 switch(arg.__ref) {787 case 'domain': case 'compound_domain':788 return instance.web.pyeval.eval('domains', [arg]);789 case 'context': case 'compound_context':790 return instance.web.pyeval.eval('contexts', [arg]);791 default:792 throw new Error(instance.web._t("Unknown nonliteral type " + arg.__ref));793 }794 };795 /**796 * If args or kwargs are unevaluated contexts or domains (compound or not),797 * evaluated them in-place.798 *799 * Potentially mutates both parameters.800 *801 * @param args802 * @param kwargs803 */804 instance.web.pyeval.ensure_evaluated = function (args, kwargs) {805 for (var i=0; i<args.length; ++i) {806 args[i] = eval_arg(args[i]);807 }808 for (var k in kwargs) {809 if (!kwargs.hasOwnProperty(k)) { continue; }810 kwargs[k] = eval_arg(kwargs[k]);811 }812 };813 instance.web.pyeval.eval_domains_and_contexts = function (source) {814 return new $.Deferred(function (d) {setTimeout(function () {815 try {816 var contexts = ([instance.session.user_context] || []).concat(source.contexts);817 // see Session.eval_context in Python818 d.resolve({819 context: instance.web.pyeval.eval('contexts', contexts),820 domain: instance.web.pyeval.eval('domains', source.domains),821 group_by: instance.web.pyeval.eval('groupbys', source.group_by_seq || [])822 });823 } catch (e) {824 d.resolve({ error: {825 code: 400,826 message: instance.web._t("Evaluation Error"),827 data: {828 type: 'local_exception',829 debug: _.str.sprintf(830 instance.web._t("Local evaluation failure\n%s\n\n%s"),831 e.message, JSON.stringify(source))832 }833 }});834 }835 }, 0); });836 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const fc = require('fast-check');2fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));3const fc = require('fast-check');4fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));5const fc = require('fast-check');6fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));7const fc = require('fast-check');8fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));9const fc = require('fast-check');10fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));11const fc = require('fast-check');12fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));13const fc = require('fast-check');14fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));15const fc = require('fast-check');16fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));17const fc = require('fast-check');18fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));19const fc = require('fast-check');20fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => a + b >= a));

Full Screen

Using AI Code Generation

copy

Full Screen

1import { check } from 'fast-check';2const isEven = (n: number) => n % 2 === 0;3check(4 check => check.nat().satisfy(isEven).shrink(n => n / 2),5 check => check.reporter((t, n) => console.log(`(${t}) ${n}`)),6 check => check.seed(42),7 check => check.verbose()8);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { check } = require('fast-check');2function pyMethod(n) {3 return Math.pow(2, n);4}5function jsMethod(n) {6 return 2 ** n;7}8check(9 {10 },11 (n) => {12 return jsMethod(n) === pyMethod(n);13 }14);15const { check } = require('fast-check');16function pyMethod(n) {17 return Math.pow(2, n);18}19function jsMethod(n) {20 return 2 ** n;21}22check(23 {24 },25 (n) => {26 return jsMethod(n) === pyMethod(n);27 }28);

Full Screen

Using AI Code Generation

copy

Full Screen

1const py = require('./py.js').py;2const fc = require('./fast-check.js').fc;3py('print("hello world")');4py('print("hello world")');5py('print("hello world")');6py('print("hello world")');7fc.configureGlobal({verbose: 1});8fc.assert(fc.property(fc.integer(), (n) => n >= 0));9fc.configureGlobal({verbose: 1});10fc.assert(fc.property(fc.integer(), (n) => n >= 0));

Full Screen

Using AI Code Generation

copy

Full Screen

1var py = require('fast-check-monorepo/Python');2var py2 = require('fast-check-monorepo/Python2');3console.log(py);4console.log(py2);5var py = require('fast-check-monorepo/Python');6var py2 = require('fast-check-monorepo/Python2');7console.log(py);8console.log(py2);9var py = require('fast-check-monorepo/Python');10var py2 = require('fast-check-monorepo/Python2');11console.log(py);12console.log(py2);13Yarn: 1.22.10 - C:\Program Files (x86)\Yarn\bin\yarn.CMD

Full Screen

Using AI Code Generation

copy

Full Screen

1const { check, property } = require('fast-check');2const { py } = require('fast-check-monorepo');3describe('py', () => {4 it('should return the same result as python', () => {5 check(6 property(py('1 + 1'), (res) => {7 expect(res).toBe(2);8 })9 );10 });11});12{13 "scripts": {14 },15 "dependencies": {16 },17 "devDependencies": {18 }19}20const { check, property } = require('fast-check');21const { py } = require('fast-check-monorepo');22describe('py', () => {23 it('should return the same result as python', () => {24 check(25 property(py('1 + 1'), (res) => {26 expect(res).toBe(2);27 })28 );29 });30});31module.exports = {32};33{34 "compilerOptions": {35 "paths": {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fast-check-monorepo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful