Exemple #1
0
def convert_path(path, path_from, path_to):
    dst = os.path.join(path_to, os.path.relpath(path, path_from))
    print(dst)
    if not os.path.exists(dst):
        os.makedirs(dst)
    for src in os.listdir(path):
        if src.startswith('.'):
            print(path, src, '[IGNORE]')
            continue
        src = os.path.join(path, src)
        dst = os.path.join(path_to, os.path.relpath(src, path_from))
        if os.path.isdir(src):
            convert_path(src, path_from, path_to)
        elif os.path.isfile(src):
            root, ext = os.path.splitext(dst)
            if ext == '.js':
                try:
                    js2py.translate_file(src, root + '.py')
                    print(dst, '[OK]')
                except js2py.base.PyJsException:
                    print(dst, '[ERROR]')
                    shutil.copyfile(src, dst)
            else:
                print(dst)
                shutil.copyfile(src, dst)
Exemple #2
0
def update_katex_py(src=None, tar="katex.py"):
    src = "katex.js" if src is None else src
    if PurePath(src).suffix == ".js":
        print("%s -> %s" % (src, tar))
        js2py.translate_file("katex.js", tar)
    else:
        with tempfile.NamedTemporaryFile() as tmp_tar:
            print("katex version: %s" % src)
            url = get_katex_from_url(src, tmp_tar)
            src = tmp_tar.name
            print("%s -> %s" % (url, tar))
            js2py.translate_file(src, tar)
Exemple #3
0
def transform_js_to_py(input_javascript_file, output_python_file):
    """
    Recieve a javascript file as input and transform it into python code
    
    Parameters
    ---------
    input_file : string
        name of javascript file with code to convert
    python_file: string
        name of python output file
        
    Returns
    ------
    file 
        A python file converted from javascript file
    """

    js2py.translate_file(input_javascript_file, output_python_file)

    return output_python_file
import js2py
import convertjs2py
array1 = ['a', 'b', 'c', 'x']
array2 = ['z', 'y', 'a']

# func = js2py.eval_js(
#     'function containsCommonItem2(arr1, arr2) {  let map={}; for (let i=0; i < arr1.length; i++) {if(!map[arr1[i]]) {      const item=arr1[i];      map[item] = true;}  }')

# func(array1, array2)

js2py.translate_file('convertjs2py.js', 'convertjs2pyexample.py')

convertjs2py.containsCommonItem2(array1, array2)
def generate_model_from_js():
    assert URL_JS, "Need to fill constant URL_JS"
    lst_data = []
    lst_translation = []
    # ignore KEEP_CACHE, or delete it if necessary
    temp_dir_path = tempfile.mkdtemp()
    print(f"Debug temp dir {temp_dir_path}")
    path_js = os.path.join(temp_dir_path, "file_to_convert.js")
    path_py = os.path.join(temp_dir_path, "file_to_convert.py")
    filename_js = wget.download(URL_JS, out=path_js)
    # Special treatment, support only specific js
    with open(filename_js, "r") as file:
        file_content = file.read()
        assert (
            KEY_GOOD_JS_FILE not in file_content
        ), f"js {URL_JS} not supported, need key {KEY_GOOD_JS_FILE}"
        if KEY_REMOVE_SECTION_JS_FILE in file_content:
            file_content = file_content[
                : file_content.rfind(KEY_REMOVE_SECTION_JS_FILE)
            ]
        file_content = KEY_TO_ADD_BEGIN_FILE + file_content.replace(
            KEY_JS_VARIABLE, "content"
        )
    with open(filename_js, "w") as file:
        file.write(file_content)
    js2py.translate_file(filename_js, path_py)
    sys.path.append(temp_dir_path)
    try:
        import file_to_convert  # pylint: disable=W0404
    except Exception as e:
        raise e
    lst_extract_info = file_to_convert.file_to_convert.content
    for dct_extract_info in lst_extract_info:
        data = {}
        info = namedtuple("ObjectName", dct_extract_info.keys())(
            *dct_extract_info.values()
        )
        child_disabled_info = dct_extract_info.get(KEY_DISABLED_CHILD)
        if child_disabled_info:
            print(child_disabled_info)
            raise ValueError(f"Do not support {KEY_DISABLED_CHILD}.")
        new_fr_url = os.path.join(URL_HTML, "fr", info.Url[1:])
        data["url_fr"] = new_fr_url
        data["data_fr"] = download_url_and_get_content(
            new_fr_url, temp_dir_path
        )
        new_en_url = os.path.join(URL_HTML, "en", info.Url[1:])
        data["url_en"] = new_en_url
        data["data_en"] = download_url_and_get_content(
            new_en_url, temp_dir_path
        )
        data["title_fr"] = convert_html_to_text(info.FrTitle)
        data["title_en"] = info.EnTitle
        lst_translation.append((data["title_en"], data["title_fr"]))
        child_info = dct_extract_info.get(KEY_CHILD)
        if child_info:
            lst_child = []
            for dct_sub_link in child_info:
                sub_link = namedtuple("ObjectName", dct_sub_link.keys())(
                    *dct_sub_link.values()
                )
                dct_child = {}
                new_fr_url = os.path.join(URL_HTML, "fr", sub_link.Url[1:])
                dct_child["url_fr"] = new_fr_url
                dct_child["data_fr"] = download_url_and_get_content(
                    new_fr_url, temp_dir_path
                )
                new_en_url = os.path.join(URL_HTML, "en", sub_link.Url[1:])
                dct_child["url_en"] = new_en_url
                dct_child["data_en"] = download_url_and_get_content(
                    new_en_url, temp_dir_path
                )
                dct_child["title_fr"] = convert_html_to_text(sub_link.FrTitle)
                dct_child["title_en"] = sub_link.EnTitle
                lst_translation.append(
                    (dct_child["title_en"], dct_child["title_fr"])
                )
                dct_child["fields"] = extract_field_from_html(
                    dct_child["data_en"]
                )
                dct_child["fields_fr"] = extract_field_from_html(
                    dct_child["data_fr"]
                )
                sub_child_info = dct_sub_link.get(KEY_CHILD)
                if sub_child_info:
                    print(sub_child_info)
                    raise ValueError(f"Do not support {KEY_CHILD}.")
                child_obj = namedtuple("ObjectName", dct_child.keys())(
                    *dct_child.values()
                )
                lst_child.append(child_obj)
            data["child"] = lst_child
        data_obj = namedtuple("ObjectName", data.keys())(*data.values())
        lst_data.append(data_obj)

    return lst_data, lst_translation
import js2py
js2py.translate_file('test2.js', 'test2res.py')
from test2res.py import *

test2res.encodage('messagclair',377,1370477)
test2res.encode('messagclair',377,1370477)
"""Main logic file. Manages data pipeline."""
from gAPI import Create_Service
import ast
import json
import os
import sys

sys.path.insert(1, 'logging-test')
import extract_data as RUBRIC
import js2py

js2py.translate_file('course_util.js', 'course_utiljs.py')
import find_except as exc
import to_csv as csv

from concurrent.futures import (as_completed, ThreadPoolExecutor)
from course_utiljs import course_utiljs

RUBRIC_REGEX_KEYS = RUBRIC.regex_gen(0)
SUBMISSION_REGEX_KEYS = RUBRIC.regex_gen(1)

CLIENT_SECRET_FILE = 'client_secret.json'
API_SERVICE_NAME = 'classroom'
API_VERSION = 'v1'
SCOPES = [
    'https://www.googleapis.com/auth/classroom.coursework.students https://www.googleapis.com/auth/classroom.courses https://www.googleapis.com/auth/classroom.rosters https://www.googleapis.com/auth/classroom.profile.emails https://www.googleapis.com/auth/classroom.rosters'
]

COURSE_FIELDS = ''
TEACHER_FIELDS = ['teachers/courseId', 'teachers/userId', 'teachers/profile']
STUDENT_FIELDS = ['students/courseId', 'students/userId', 'students/profile']
Exemple #8
0
import os
import time
import math
import js2py
from datetime import datetime
from PIL import ImageTk
from tkinter import Tk, Frame, Menu, Label, Button, filedialog, RIGHT, LEFT, TOP, NO
from tkinter.constants import BOTH
from tkinter.ttk import Treeview, Scrollbar
from pycube.image_gen import genimage
from pycube.session import Session

if not os.path.isfile("./scrambler.py"):
    js2py.translate_file("../scrambler/wca-scramble.js", "scrambler.py")

from pycube.scrambler import scrambler #@UnresolvedImport

class PyCube:
    
    def __init__(self):
        self.root = Tk()
        self.root.title("PyCube")
        
        self.session = Session()
        
        # init UI
        self.initMenu()
        self.leftframe = Frame(self.root)
        self.leftframe.pack(side=LEFT, fill=BOTH, expand=1)
        
        self.rightframe = Frame(self.root)
Exemple #9
0
import json
import re
import random
import datetime
global pyttsx
import pyttsx
from termcolor import colored
import sympy
import time
import sys
from num2words import num2words
import js2py

js2py.translate_file('convert.js', 'convert.py')

from convert import convert

global jsConvert

jsConvert = convert.text2num

engine = pyttsx.init()

def write_file():
    is_interest = raw_input("Is it a bot interest?\n")

    keyvalue = raw_input("Is it a dynamic or specific answer?\n")

    if is_interest.lower() == "yes":
        topic = raw_input("Please type in the interest:\n")
        topic_desc = raw_input("What is the bot's opinion on this interest?\n")
__author__ = "Psideralis"
__copyright__ = "Copyright 2020, Psideralis"
__credits__ = ["Psideralis"]
__license__ = "GPL 3.0"
__version__ = " 00.00.000.001"
__maintainer__ = "Psideralis"
__email__ = "*****@*****.**"
__status__ = "Development"

from ctypes import cdll
lib = cdll.LoadLibrary('./PsideralisDataStructures.dll')

import js2py
f = js2py.eval_js("function $(name) {return name.length}")
f = js2py.eval_js()
js2py.translate_file('example.js', 'example.py')
#from example import example
js = js2py.eval_js('d = {a:1, b:2}')


# STATIC STRUCTURES
class Set:
    def _init__(self):
        pass

    def randomSubstitution(self):
        pass

    def indexSubstitution(self):
        pass
Exemple #11
0
"""
Sprites used in the game: the rat and the pipe.
"""
import enum
import numpy as np
import math
import js2py

import pygame as pg

from settings import *
from os import path

js2py.translate_file('CGP.js', 'js.py')

from js import js


class MovableSprite(pg.sprite.Sprite):
    def __init__(self, *groups):
        super().__init__(*groups)
        self.rect = None

    def moveto(self, x=0, y=0):
        self.rect.x = x
        self.rect.y = y

    def moveby(self, dx=0, dy=0):
        self.rect.move_ip(dx, dy)

import js2py

# there are 2 easy methods to run js file from Js2Py

# Method 1:
eval_result, example = js2py.run_file('example.js')


# Method 2:
js2py.translate_file('example.js', 'example.py') # this translates and saves equivalent Py file
from example import example  # yes, it is: import lib_name from lib_name


##### Now you can use your JS code as if it was Python!

print(example.someVariable)
print(example.someVariable.a)
print(example.someVariable['a'])

example.sayHello('Piotrek!')
example.sayHello()   # told you, just like JS.

example['$nonPyName']()  # non py names have to be accessed through []   example.$ is a syntax error in Py.


# but there is one problem - it is not possible to write 'new example.Rectangle(4,3)' in Python
# so you have to use .new(4,3) instead, to create the object.
rect = example.Rectangle.new(4,3)
print(rect.getArea())  # should print 12
Exemple #13
0
import js2py
# print(js2py.translate_js("console.log('hello world')"))

# 将js文件翻译为python脚本
js2py.translate_file('demo.js', 'demo.py')
Exemple #14
0
import js2py

js2py.translate_file('js_lib.js', 'js_lib.py')
Exemple #15
0
# https://github.com/PiotrDabkowski/Js2Py
# https://pscript.readthedocs.io/en/latest/gettingstarted.html
# https://github.com/brython-dev/brython/issues/937
import js2py

# context = js2py.EvalJs({'window': None})
# context.execute('console.log(typeof window)')

# 修正这个判定 -- var isBrowser = typeof window !== 'undefined';
# from js2py import pyjs
# pyjs.JS_BUILTINS['ttt'] = None
# js2py.eval_js('console.log(typeof window.document)')

# step1 文件使用前,需要先转换 ---> 遇到正则,容易gg的
js2py.translate_file('run2.js', 'run2src.py')
from run2src import run2src
print run2src.run()

# step2 引入文件,并且执行
# from run2_api import run2_api
# print run2_api

# 可行例子
# js2py.translate_file('example.js', 'example.py') # this translates and saves equivalent Py file
# from example import example  # yes, it is: import lib_name from lib_name
# print(example.someVariable)
# print(example.someVariable.a)
# print(example.someVariable['a'])

# JSDOM = js2py.require('jsdom')
Exemple #16
0
"""
@Author: 邓润庭
@Date:   2019/10/12
"""
import js2py

print(js2py.translate_js("console.log('Hello World!')"))


# 将js翻译成python代码
js2py.translate_file('d02.js', 'd02.py')
"""
The main flappy rat game.
"""
import random
from enum import Enum

import os.path
import os
import js2py

js2py.translate_file('proNav.js', 'proNav.py')

from proNav import proNav

import cgp
from sprites import *


class GameMode(Enum):
    PLAYER = 0
    GP = 1
    VS = 2  # human player vs. GP


class Game:
    def __init__(self):
        os.environ['SDL_VIDEO_WINDOW_POS'] = '200,300'
        pg.mixer.pre_init()
        pg.mixer.init()
        pg.init()
        self._screen = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
import js2py

# there are 2 easy methods to run js file from Js2Py

# Method 1:
eval_result, example = js2py.run_file('example.js')

# Method 2:
js2py.translate_file(
    'example.js', 'example.py')  # this translates and saves equivalent Py file
from example import example  # yes, it is: import lib_name from lib_name

##### Now you can use your JS code as if it was Python!

print((example.someVariable))
print((example.someVariable.a))
print((example.someVariable['a']))

example.sayHello('Piotrek!')
example.sayHello()  # told you, just like JS.

example['$nonPyName'](
)  # non py names have to be accessed through []   example.$ is a syntax error in Py.

# but there is one problem - it is not possible to write 'new example.Rectangle(4,3)' in Python
# so you have to use .new(4,3) instead, to create the object.
rect = example.Rectangle.new(4, 3)
print((rect.getArea()))  # should print 12
Exemple #19
0
import js2py
import shutil

js2py.translate_file('tp_link_encryption.js', 'tp_link_encryption.py')
shutil.move("tp_link_encryption.py", "../tp_connected/tp_link_encryption.py")
Exemple #20
0
import js2py
js2py.translate_file('grid.js', 'Grids.py')
# from example import example
# example.someFunction()
import js2py

js2py.translate_file('run.js', 'runchar.py')
Exemple #22
0
'''

#get cookies
r = requests.get(
    'http://service120.sds.fcu.edu.tw/W320104/W320104_stu_pre.aspx?courseid=1061CE0711127436001&lang=cht'
)
r.cookies

cookie = {'Cookie': 'ASP.NET_SessionId=' + r.cookies['ASP.NET_SessionId']}
cookie

df.to_csv('106course.csv', encoding='utf-8', index=False)

#js轉py
js2py.translate_file('DES.js', 'DES.py')

from DES import *

course_id = []
for cid in df['courseid']:
    en = str(encMe(cid))[1:-1]
    print(en)
    course_id.append(en)
course_id

df['course_id'] = course_id
df

r = requests.get(
    'http://service120.sds.fcu.edu.tw/W320104/W320104_stu_pre.aspx?courseid=1061CE0711127436001&lang=cht'
Exemple #23
0
import os
from setuptools import find_packages, setup
import js2py
from npm.bindings import npm_run

stderr, stdout = npm_run('install')
stderr, stdout = npm_run('run', 'bundle')

if not os.path.exists('prosemirror'):
    os.makedirs('prosemirror')

js2py.translate_file('lib/index.js', 'prosemirror/js_lib.py')

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
    README = readme.read()

os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

setup(
    name='prosemirror-python',
    version='0.0.4',
    packages=find_packages(),
    install_requires=[
        'Js2Py==0.59',
    ],
    include_package_data=True,
    license='AGPL License',
    description=
    'Python translation of prosemirror parts needed to modify a document in Python',
    long_description=README,
    url='https://www.github.com/fiduswriter/prosemirror-python',
import js2py
js2py.translate_file('lib-jitsi-meet.min.js', 'lib_jitsi_meet.py')

from lib_jitsi_meet import JitsiMeetJS



Exemple #25
0
import js2py

js2py.translate_file('tk.js', 'tk.py')
Exemple #26
0
import js2py

js2py.translate_file('js_lib.js', 'js_lib.py')
Exemple #27
0
            if line.find('{') != -1:
                result += ['{']
            elif line.find('}') != -1:
                result += ['}']
        else:
            result += [line]
    return '\n'.join(result)


if __name__ == "__main__":
    progress = 1
    total = len(generators)
    broken = []

    for name in sorted(generators):
        sys.stdout.write('\r {} out of {} ({})                \r'.format(
            progress, total, name))
        code = open('js/' + name).read()
        code = finalize(prepare(code))
        buf = io.StringIO(code)
        try:
            js2py.translate_file(buf,
                                 'generators/{}.py'.format(name.split('.')[0]))
        except Exception as e:
            broken += [name]
        progress += 1
    if broken != 0:
        print('\n Done! List of files that cannot be translated (total: \
    {}): {}'.format(len(broken), broken))
    print('\nDone!')
Exemple #28
0
# Python code to readlines()
# writing to file

import js2py
import re

js2py.translate_file('phkConverter.js', 'phkConverter.py')

# Converted from JavaScript
# import phkConverter

# Using readlines()
outputLines = []
infileName = '/Users/craig/Desktop/Projects/PhakeData/joined.txt'  #  Originally wasq'Phake_Dictionary_Ailot_Final.txt'
count = 0

# These should be converted.:wq
phakeFields = ['lx', 'le', 'pl', 'se', 'xv']
banchobFields = ['ph', 'pd', 'xr']
textFields = ['de', 'ge', 'xe']
eval_res, converterFile = js2py.run_file('phkConverter.js')

encodingIndex = 0

banchobMap = {
    'N': 'ŋ',
    'M': 'ñ',
    'j': 'ɛ',
    'v': 'ü',
    'z': 'ə',
    'q': 'ɔ',
Exemple #29
0
import js2py

js2py.translate_file('expand-full.js', 'expand.py')
Exemple #30
0
import js2py

js2py.translate_file('email_parser.js', 'email_parser.py')