How to use Js2Py - 10 common examples

To help you get started, we’ve selected a few Js2Py examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PiotrDabkowski / Js2Py / js2py / constructors / jsdate.py View on Github external
l = len(args)
    dt = args[2].to_number() if l > 2 else Js(1)
    h = args[3].to_number() if l > 3 else Js(0)
    mi = args[4].to_number() if l > 4 else Js(0)
    sec = args[5].to_number() if l > 5 else Js(0)
    mili = args[6].to_number() if l > 6 else Js(0)
    if not y.is_nan() and 0 <= y.value <= 99:
        y = y + Js(1900)
    t = TimeClip(
        LocalToUTC(MakeDate(MakeDay(y, m, dt), MakeTime(h, mi, sec, mili))))
    return PyJsDate(t, prototype=DatePrototype)


Date.create = date_constructor

DatePrototype = PyJsDate(float('nan'), prototype=ObjectPrototype)


def check_date(obj):
    if obj.Class != 'Date':
        raise MakeError('TypeError', 'this is not a Date object')


class DateProto:
    def toString():
        check_date(this)
        if this.value is NaN:
            return 'Invalid Date'
        offset = (UTCToLocal(this.value) - this.value) // msPerHour
        return this.local_strftime(
            '%a %b %d %Y %H:%M:%S GMT') + '%s00 (%s)' % (pad(
                offset, 2, True), GetTimeZoneName(this.value))
github PiotrDabkowski / Js2Py / js2py / internals / base.py View on Github external
return self.pat.match(string, int(pos))


class PyJsError(PyJs):
    Class = 'Error'
    extensible = True

    def __init__(self, message=None, prototype=None):
        self.prototype = prototype
        self.own = {}
        if message is not None:
            self.put('message', to_string(message))
            self.own['message']['enumerable'] = False


class PyJsDate(PyJs):
    Class = 'Date'
    UTCToLocal = None  # todo UTC to local should be imported!

    def __init__(self, value, prototype=None):
        self.value = value
        self.own = {}
        self.prototype = prototype

    # todo fix this problematic datetime part
    def to_local_dt(self):
        return datetime.datetime.utcfromtimestamp(
            self.UTCToLocal(self.value) // 1000)

    def to_utc_dt(self):
        return datetime.datetime.utcfromtimestamp(self.value // 1000)
github PiotrDabkowski / Js2Py / js2py / translators / translator.py View on Github external
Q1 == 1 && name /* some comment */ == 'o\'Reilly'
       """

    match_increaser_str, match_increaser_num, compilation_plan = get_compilation_plan(
        js)

    cp_hash = hashlib.md5(compilation_plan.encode('utf-8')).digest()
    try:
        python_code = cache[cp_hash]['proto_python_code']
    except:
        parser = pyjsparser.PyJsParser()
        parsed = parser.parse(compilation_plan)  # js to esprima syntax tree
        # Another way of doing that would be with my auto esprima translation but its much slower and causes import problems:
        # parsed = esprima.parse(js).to_dict()
        translating_nodes.clean_stacks()
        python_code = translating_nodes.trans(
            parsed)  # syntax tree to python code
        cache[cp_hash] = {
            'compilation_plan': compilation_plan,
            'proto_python_code': python_code,
        }

    python_code = match_increaser_str.wrap_up(python_code)
    python_code = match_increaser_num.wrap_up(python_code)

    return HEADER + python_code
github PiotrDabkowski / Js2Py / tests / ES5Conform.py View on Github external
"TestCases/chapter15/15.7/15.7.3/15.7.3.1/15.7.3.1-2.js",
null,
"TestCases/chapter15/15.7/15.7.4/15.7.4-1.js",
null,
"TestCases/chapter15/15.9/15.9.4/15.9.4.4/15.9.4.4-0-1.js",
"TestCases/chapter15/15.9/15.9.4/15.9.4.4/15.9.4.4-0-2.js",
null,
"TestCases/chapter15/15.9/15.9.5/15.9.5.43/15.9.5.43-0-1.js",
"TestCases/chapter15/15.9/15.9.5/15.9.5.43/15.9.5.43-0-2.js",
null,
"TestCases/chapter15/15.9/15.9.5/15.9.5.44/15.9.5.44-0-1.js",
"TestCases/chapter15/15.9/15.9.5/15.9.5.44/15.9.5.44-0-2.js",
null,
];

e = js2py.EvalJs()
e.execute(Harness)
STATS = {'not_implemented': 0,
         'error': 0,
         'passed': 0,
         'wrong': 0}
PRINT_ERROR = 1
PRINT_WRONG = 0

def run_test_case(path):
    if path is None:
        return
    #print(path)
    with open(path, 'r', encoding='utf8') as f: #{'not_implemented': 128, 'wrong': 148, 'passed': 950, 'error': 4}
        test = f.read()
    try:
        result = e.eval(test)
github PiotrDabkowski / Js2Py / tests / test_cases / testCompilationPlan.py View on Github external
import js2py
import datetime
now = datetime.datetime.now

# the line below will
# - build a 'compilation plan' by substituting strings and constants with placeholders
# - then build the ast and emit the python code from that compilation plan
# - then substitute back in the constants
# This causes some regex overhead, but for js code with similar structure
# subsequent translate_js calls are 20 times faster
js2py.translate_js('name == "Robert" && age == 46', use_compilation_plan=True)

# this lines below will re-use the compilation plan already laid out by the
# statement above
js2py.translate_js('name == "Guido" && age == 50', use_compilation_plan=True)
js2py.translate_js('name == "Spam" && age == 25', use_compilation_plan=True)

# now we'll show off the performance gain:
start = now()
for cnt in range(10000):
	js2py.translate_js('name == "Robert" && age == %i'%cnt, use_compilation_plan=False)
print(('duration without compilation plan %i'%(now() - start).seconds))

start = now()
for cnt in range(10000):
	js2py.translate_js('name == "Robert" && age == %i'%cnt, use_compilation_plan=True)
print(('duration with compilation plan %i'%(now() - start).seconds))
github PiotrDabkowski / Js2Py / tests / test_cases / testCompilationPlan.py View on Github external
js2py.translate_js('name == "Robert" && age == 46', use_compilation_plan=True)

# this lines below will re-use the compilation plan already laid out by the
# statement above
js2py.translate_js('name == "Guido" && age == 50', use_compilation_plan=True)
js2py.translate_js('name == "Spam" && age == 25', use_compilation_plan=True)

# now we'll show off the performance gain:
start = now()
for cnt in range(10000):
	js2py.translate_js('name == "Robert" && age == %i'%cnt, use_compilation_plan=False)
print(('duration without compilation plan %i'%(now() - start).seconds))

start = now()
for cnt in range(10000):
	js2py.translate_js('name == "Robert" && age == %i'%cnt, use_compilation_plan=True)
print(('duration with compilation plan %i'%(now() - start).seconds))

# you can see how a compilation plan works with the lines below:
from js2py.translators.translator import get_compilation_plan
expression = "Age==1 && Gender==2 && JobTitle=='Decision maker'"
strings, numbers, plan = get_compilation_plan(expression)
print('strings:\n%s'%strings)
print('numbers:\n%s'%numbers)
print('plan:\n%s'%plan)
print(js2py.translate_js(expression))
github PiotrDabkowski / Js2Py / js2py / legecy_translators / nparser.py View on Github external
def __repr__(self):
        return str(self.__dict__)


class RegExp(object):
    def __init__(self, pattern, flags=''):
        self.flags = flags
        pyflags = 0 | re.M if 'm' in flags else 0 | re.I if 'i' in flags else 0
        self.source = pattern
        self.pattern = re.compile(pattern, pyflags)

    def test(self, s):
        return self.pattern.search(s) is not None


console = jsdict({"log": print})


def __temp__42(object=None, body=None):
    return jsdict({
        "type": Syntax.WithStatement,
        "object": object,
        "body": body,
    })


def __temp__41(test=None, body=None):
    return jsdict({
        "type": Syntax.WhileStatement,
        "test": test,
        "body": body,
    })
github qwIvan / microMsg-bot / micro_msg_bot / meme.py View on Github external
def jschl(tag, domain='www.doutula.com'):
    snippet, obj = '', None
    for line in tag.splitlines():
        if 's,t,o,p,b,r,e,a,k,i,n,g' in line and ' ' in line:
            define = line.rsplit(' ', maxsplit=1)[-1]
            if '=' in define and define.endswith(';'):
                obj = define.split('=')[0]
                snippet += define
        if 'submit()' in line:
            break
        if obj:
            for seg in line.split(';'):
                if seg.startswith(obj) and '=' in seg:
                    snippet += seg + ';'
    return js2py.eval_js(snippet) + len(domain)
github Godavaru / Godavaru / Godavaru Main / cog_owner.py View on Github external
async def eval(self, ctx):
        args = ctx.message.content
        args = args.split(' ')
        if ctx.message.author.id not in ownerids:
            await ctx.send(":x: You do not have permission to evaluate code.")
            return
        try:
            if args[1] != "":
                if args[1] == "py":
                    code = ctx.message.content.replace(args[0]+" "+args[1]+" ", "")
                    code = code.strip('` ')
                elif args[1] == "js":
                    code = ctx.message.content.replace(args[0]+" "+args[1]+" "+args[2]+" ", "")
                    javascript = 'Excecuted successfully and returned: {}'
                    try:
                        result = js2py.eval_js(str(code))
                        if result is None:
                            a = "Executed successfully with no objects returned."
                        else:
                            a = javascript.format(result)
                        await ctx.send(embed=discord.Embed(description=a,color=0x00ff00).set_author(name="Evaluated with success", icon_url=ctx.message.author.avatar_url.replace("?size=1024", "")).set_footer(text="Executed by: "+str(ctx.message.author)).set_thumbnail(url='http://www.iconsdb.com/icons/preview/green/checked-checkbox-xxl.png').add_field(name="Code",value="[See here.]({})".format(hastebin.post(code))))
                        return
                    except Exception as e:
                        await ctx.send(embed=discord.Embed(description="Excecuted and errored: {}".format(type(e).__name__ + ': ' + str(e)),color=0xff0000).set_author(name="Evaluated and errored", icon_url=ctx.message.author.avatar_url.replace("?size=1024", "")).set_footer(text="Executed by: "+str(ctx.message.author)).set_thumbnail(url='https://upload.wikimedia.org/wikipedia/commons/thumb/b/ba/Red_x.svg/480px-Red_x.svg.png').add_field(name="Code",value="[See here.]({}.js)".format(hastebin.post(code))))
                        return
                else:
                    code = ctx.message.content.replace(args[0]+" ", "")
                    code = code.strip('` ')
                python = 'Excecuted successfully and returned: {}'
                result = None
        
                env = {
github PiotrDabkowski / Js2Py / js2py / internals / opcodes.py View on Github external
]  # props are py string pairs (prop_name, kind): kind can be either i, g or s. (init, get, set)

    def __init__(self, props):
        self.num = len(props)
        self.props = props

    def eval(self, ctx):
        obj = ctx.space.NewObject()
        if self.num:
            obj._init(self.props, ctx.stack[-self.num:])
            del ctx.stack[-self.num:]

        ctx.stack.append(obj)


class LOAD_ARRAY(OP_CODE):
    _params = ['num']

    def __init__(self, num):
        self.num = num

    def eval(self, ctx):
        arr = ctx.space.NewArray(self.num)
        if self.num:
            arr._init(ctx.stack[-self.num:])
            del ctx.stack[-self.num:]
        ctx.stack.append(arr)


class LOAD_THIS(OP_CODE):
    def eval(self, ctx):
        ctx.stack.append(ctx.THIS_BINDING)