Пример #1
0
def compile_sketch(sketch_name,
                   generate_index=False,
                   index_template=None,
                   force_local=False):
    """
    Transcrypt the sketch python code to javascript.

    :param sketch_name: name for new sketch
    :param generate_index: boolean to flag if the index.html file should be updated
    :param force_local: boolean to flag to force local run (used by web editor only)
    :type sketch_name: string
    :return: file names
    :rtype: list of strings
    """

    sketch = Sketch(sketch_name)
    sketch.validate_name()

    if not sketch.sketch_exists:
        raise PythonSketchDoesNotExist(sketch)

    compile_sketch_js(sketch, force_local=force_local)
    if generate_index:
        # to be able to overwrite default index template file
        # useful for generating the docs or debugging
        sketch.config.index_template = index_template
        index_contet = get_sketch_index_content(sketch)
        with open(sketch.index_html, "w", encoding="utf-8") as fd:
            fd.write(index_contet)
        cprint.info(f"{sketch.index_html.resolve()} updated")

    return sketch
Пример #2
0
def monitor_sketch(sketch_name, sketch_dir):
    """
    Monitor for any change in any .py code under
    the sketch dir and, for every new change,
    runs the transcrypt to update the js files.

    :param sketch_name: name for new sketch
    :type sketch_name: string
    :param sketch_dir: directory name
    :type sketch_dir: string
    :return: file names
    :rtype: list of strings
    """

    sketch_files = Pyp5jsSketchFiles(sketch_dir, sketch_name)
    if not sketch_files.check_sketch_exists():
        cprint.err(f"Couldn't find {sketch_name}", interrupt=True)

    cprint(
        f"Monitoring for changes in {sketch_files.sketch_dir.absolute()}...")

    try:
        monitor_sketch_service(sketch_files)
    except KeyboardInterrupt:
        cprint.info("Exiting monitor...")
Пример #3
0
def export_to_video(sketch_name, frame_rate, output, clean_after):
    """
    Export frames from sketch to a MP4 video
    """
    sketch_dir = SKETCH_DIR.child(sketch_name)

    if not sketch_dir.exists():
        cprint.err(f"There's no directory for the sketch {sketch_name}", interrupt=True)

    output = output or sketch_dir.child('output.mp4')
    cprint.info(f"Generating {output} from sketch sketch_name")
    query = sketch_dir + "/*.png"
    command = ' '.join([str(c) for c in [
        'ffmpeg', '-framerate', frame_rate, '-pattern_type', 'glob', '-i', query, '-c:v', 'libx264', '-r', frame_rate, '-pix_fmt', 'yuv420p', output
    ]])

    cprint.info(f"Command:\n\t$ {command}")

    convert = subprocess.Popen(
        shlex.split(command),
    )
    convert.wait()

    if clean_after:
        pngs = sketch_dir.listdir("*.png")
        cover = random.choice(pngs)
        cover.rename("cover.png")
        for png in pngs:
            png.remove()
Пример #4
0
def transcrypt_sketch(sketch_name, sketch_dir, pyp5js):
    """
    Command to generate the P5.js code for a python sketch

    Params:
    - sketch_name: name of the sketch (will create a {sketch_name}.py)

    Opitionals
    - sketch_dir: sketch's directory (defaults to ./{sketch_name})
    - pyp5hs: path to the pyp5js main file (defaults to local install)
    """
    SKETCH_DIR = Path(sketch_dir or f'./{sketch_name}')
    if not SKETCH_DIR.exists():
        cprint.warn(f"Couldn't find the sketch.")
        cprint.err(f"The directory {SKETCH_DIR} doesn't exist.",
                   interrupt=True)

    sketch = SKETCH_DIR.child(f"{sketch_name}.py")
    pyp5js = Path(pyp5js or PYP5_DIR)

    command = ' '.join([
        str(c)
        for c in ['transcrypt', '-xp', pyp5js, '-b', '-m', '-n', sketch]
    ])
    cprint.info(f"Command:\n\t {command}")

    transcrypt = subprocess.Popen(shlex.split(command))
    transcrypt.wait()
Пример #5
0
def h():
    cprint.info(
        _('''
Current list of commands: multiplication, division, addition, square, subtraction, modulo, area, volume, cube, exponents, root, logarithm, memory, interest calculator, fibonacci sequence, percentage calculator, convert temperature, and convert bases (aka number systems). Type quit to quit.
Bugs? Head on over to https://github.com/thetechrobo/support/
To contribute: go to https://github.com/thetechrobo/python-text-calculator/
'''))
Пример #6
0
def calculateInterest():
    while True:
        origin = int(input(_("What is the original number? ")))
        rate = float(
            input(
                _("What is the rate of interest in percentage (without the percent sign)? "
                  )))
        print()
        howMany = int(
            input(
                _('''How many units of time would you like to calculate? 
Essentially, one unit of time could be one month, or one decade. It all depends on what you typed in the rate of interest question: it could be per year, per decade...we didn't ask.
It was up to you to type the correct amount in the rate question.
We have no idea what the rate represented: it could have been that rate per century for all we know.
This calculator wasn't programmed with the ability to track time.
So, with that out of the way, type the amount we should multiply the interest by (aka the amount of units of time).\nType it: '''
                  )))
        inRealNumbers = percentage(whole=origin, percent=rate)
        number = origin + (inRealNumbers * howMany)
        logging.info(
            "INTERESTCALC: origin: %s rate: %s howMany: %s answer: %s" %
            (origin, rate, howMany, number))
        cprint.info(_("The answer is: \n%s" % number))
        doItAgain = input(_("Would you like to do it again (Y/n)? "))
        doItAgain = doItAgain.lower()
        if doItAgain == _("y"):
            pass
        else:
            cprint.ok(_("Going back..."))
            break
Пример #7
0
 def translate(self, text):
     cprint.info(
         f"Step {self.iteration}/{self.size}\n>> {self.from_lang} - {self.to_lang}"
     )
     text = from_google(text, source=self.from_code, target=self.to_code)
     cprint.info(f'\t{text}\n')
     return text
Пример #8
0
    def load(self):
        self.load_synsets()

        cprint.info("Loading objects...")
        self.objects
        cprint.info("Loading relationships...")
        self.relationships
Пример #9
0
def mod():  #modulo
    try:
        bigger = int(input(_("\nType the first number (greater): ")))
        smaller = int(input(_("Type the second number (smaller): ")))
    except (TypeError, ValueError):
        cprint.err(_("\nError!"))
        cprint.err(_("Invalid input (code 1)\n"))
        logging.error(
            "ERROR: attempted to modulo numbers %s and %s, but errored code 1."
            % (number1, number2))
    if (abs(bigger) < abs(smaller)):
        cprint.err(_("\nError!"))
        cprint.err(
            _("The second number entered is greater than the first number (code 2)\n"
              ))
        logging.error(
            "ERROR: attempted to modulo numbers %s and %s, but errored code 2."
            % (number1, number2))
    else:
        cprint.info(
            _("\nThat equals...\n%s" %
              (bigger - smaller * int(bigger / smaller))))
        logging.info(
            "User attempted to modulo numbers %s and %s, and got result %s" %
            (bigger, smaller, (bigger - smaller * int(bigger / smaller))))
        print()
Пример #10
0
    def on_modified(self, event):
        event_id = id(event)
        if event_id == self._last_event:
            return

        cprint.info(f"New change in {event.src_path}")
        compile_sketch_js(self.sketch, TARGET_DIRNAME)
Пример #11
0
def trapezium():
    from area import trapezium as trapezi
    a = int(input(_("What is the length of the 1st set of parallel sides? ")))
    b = int(input(_("What is the length of the 2nd set of parallel sides? ")))
    h = int(input(_("What is the height of the trapezium? ")))
    cprint.info(_("The area is: "))
    cprint.info(trapezi(a, b, h))
Пример #12
0
def writeNodes(model_path, graph_def):
    ''' Dump the node names in a graph into a text file. '''
    text_filename = os.path.join(model_path, 'nodes.txt')
    nodes = [n.name for n in graph_def.node]
    cprint.info(f'Dumping {len(nodes)} nodes into {text_filename}...')
    with open(text_filename, 'w') as f:
        [f.write(node + '\n') for node in nodes]
    cprint.info('Done!')
Пример #13
0
    def run_compiler(self):
        """
        Execute transcrypt command to generate the JS files
        """
        command = self.command_line
        cprint.info(
            f"Converting Python to P5.js...\nRunning command:\n\t {command}")

        subprocess.call(command, shell=True)
Пример #14
0
def getPercentageRN():
    origin = int(input(_("What is the number that would be 100%? ")))
    part = int(
        input(
            _("What is the number that you want to convert to percentage (e.g. this number out of the number that would be 100%)? "
              )))
    logging.info("Got percentage RN origin %s and %s" % (origin, part))
    cprint.info(_("that equals:"))
    cprint.info(getPercentage(part, origin))
Пример #15
0
    def run_compiler(self):
        """
        Execute transcrypt command to generate the JS files
        """
        command = self.command_line
        cprint.info(f"Converting Python to P5.js...\nRunning command:\n\t {command}")

        proc = subprocess.Popen(shlex.split(command))
        proc.wait()
Пример #16
0
    def prepare(self):
        """
        Creates target_sketch.py to import the sketch's functions
        """
        content = get_target_sketch_content(self.sketch)

        with self.sketch.target_sketch.open('w') as fd:
            fd.write(content)

        cprint.info(f"{self.sketch.target_sketch.resolve()} updated with sketch code")
Пример #17
0
def div(): #division
    n1, n2 = getNum()
    try:
        cprint.info(_("\nThat equals...\n%s" % (n1 / n2)))
        logging.info("User divvied %s by %s, getting a result of %s" % (n1, n2, (n1 / n2)))
    except ZeroDivisionError:
        cprint.err(_("Do not divide by zero!"))
        logging.error("User attempted to divide by zero.")
    except Exception as e:
        cprint.err(_("There was an unknown issue dividing your Numbers..."))
        logging.error("User had an issue divvying up %s by %s (%s)" % (n1,n2,e))
Пример #18
0
def getVideoSource(source, params):
    """Return the camera abstract object to iterate the
    video source."""
    # Validate the source

    if source not in VALID_SOURCES:
        msg = f'The chosen source {source} is not supported. Please choose one of: {VALID_SOURCES}'
        cprint.fatal(msg, interrupt=True)

    if source == 'Local':
        from Camera.local_camera import Camera as LocalCamera
        # Local camera device selected.
        cam_idx = params['DeviceNo']
        cprint.info(f'Selected device: local camera #{cam_idx}')

        cam = LocalCamera(cam_idx)
    elif source == 'Video':
        from Camera.local_video import Camera as LocalVideo
        # Video file selected.
        video_path = os.path.expanduser(params['Path'])
        if not os.path.isfile(video_path):
            msg = f'The chosen video file {video_path} does not exist. Please check the file name.'
            cprint.fatal(msg, interrupt=True)

        cprint.info(f'Selected video: {video_path}')
        cam = LocalVideo(video_path)
    else:
        from Camera.roscam import ROSCam
    # source = cfg['ObjectDetector']['Source']
    # if source.lower() == 'local':
    #     from Camera.local_camera import Camera
    #     cam_idx = cfg['ObjectDetector']['Local']['DeviceNo']
    #     print('  Chosen source: local camera (index %d)' % (cam_idx))
    #     cam = Camera(cam_idx)
    # elif source.lower() == 'video':
    #     from Camera.local_video import Camera
    #     video_path = cfg['ObjectDetector']['Video']['Path']
    #     print('  Chosen source: local video (%s)' % (video_path))
    #     cam = Camera(video_path)
    # elif source.lower() == 'stream':
    #     # comm already prints the source technology (ICE/ROS)
    #     import comm
    #     import config
    #     cfg = config.load(sys.argv[1])
    #     jdrc = comm.init(cfg, 'ObjectDetector')
    #     proxy = jdrc.getCameraClient('ObjectDetector.Stream')
    #     from Camera.stream_camera import Camera
    #     cam = Camera(proxy)
    # else:
    #     raise SystemExit(('%s not supported! Supported source: Local, Video, Stream') % (source))

    return cam
Пример #19
0
def remember():
    cprint.info(
        _("This is the memory function.\nIt will save a number into a file that can be used later with Palc... Or you can just read it with a text editor."
          ))
    toRemember = float(input(_("\nPlease enter the number to be saved: ")))
    slot = str(
        int(
            input(
                _("What slot would you like to use? (Hint: you can use any integer you want as long as you remember it)\nType: "
                  ))))
    toRemember = str(toRemember)
    memory = open(slot, "w+")
    memory.write(toRemember)
    logging.info("Saved number %s to memory slot %s" % (toRemember, slot))
Пример #20
0
def monitor_sketch(sketch_name, sketch_dir):
    sketch = _validate_sketch_path(sketch_name, sketch_dir)
    cprint(f"Monitoring for changes in {sketch.parent.absolute()}...")

    event_handler = TranscryptSketchEvent(sketch=sketch)
    observer = Observer()

    observer.schedule(event_handler, sketch.parent)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        cprint.info("Exiting monitor...")
        observer.stop()
    observer.join()
Пример #21
0
def start_socket():
    cprint.err('run socket ')
    get_dat_from_plc_thread = threading.Thread(target=get_data_from_plc)
    get_dat_from_plc_thread.start()
    try:
        conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        host = '0.0.0.0'
        port = SOCKET_PORT
        conn.settimeout(1)
        conn.connect((host, port))
        conn.close()
        cprint.info("Socket isset")
    except:
        print("run socket server")
        my_thread = threading.Thread(target=listen_server_mvlab)
        my_thread.start()
Пример #22
0
    def on_modified(self, event):
        cprint.info(f"New change in {event.src_path}")

        # monkey patch on the observer handlers to avoid recursion
        handlers_config = self.observer._handlers.copy()
        handlers_copy = {}

        compile_sketch_js(self.sketch)

        queue = self.observer.event_queue
        while queue.qsize():
            queue.get()

        index_file = self.sketch.index_html
        cprint.ok(
            f"Your sketch is ready and available at file://{index_file.absolute()}"
        )
Пример #23
0
def readMyMemory():
    cprint.info(
        _("This is the remember function.\nIt will read a number that was previously stored in a file."
          ))
    try:
        slot = str(int(input(_("What slot number did you use? "))))
        with open(slot, "r") as memory:
            theMem = memory.read()
            cprint.info(_("Number: %s" % theMem))
            logging.info("Retrieved number %s from memory slot %s" %
                         (theMem, slot))
    except Exception as e:
        logging.info(
            "There was an error retrieving the file from memory. (Err %s)" % e)
        cprint.err(
            _("There was an error reading the file. Did you save the number by using the save function? Did you accidentally rename the file?"
              ))
Пример #24
0
def loadFrozenGraph(model_path, write_nodes):
    ''' Load a frozen graph from a .pb file. '''
    model_path = os.path.join(MODELS_DIR, model_path)
    pb_path = os.path.join(model_path, FG_NAME)
    # Check the existance
    if not os.path.isfile(pb_path):
        cprint.fatal(f'Error: the file {pb_path} does not exist.', interrupt=True)

    cprint.info('Loading the frozen graph...')
    graph_def = tf.compat.v1.GraphDef()
    with tf.io.gfile.GFile(pb_path, 'rb') as fid:
        serialized_graph = fid.read()
        graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(graph_def, name='')
    cprint.ok('Loaded!')
    if write_nodes:
        writeNodes(model_path, graph_def)
    return graph_def
Пример #25
0
def base():
    base = int(
        input('''What base would you like to convert to?
Available: 2 (binary) 8 (octo) 10 (decimal (normal)) 16 (hex)
Type 2, 8, 10, or 16: '''))
    if base == 2:
        origin = int(input(_("Type the original number: ")))  #bin() the number
        printThis = "=" + str(bin(origin))
        logging.info("User binaried number %s, getting a result of %s" %
                     (origin, printThis))
        cprint.info(printThis)
    elif base == 8:
        result = int(input(_("Type the original number: ")))  #oct() the number
        printThis = "=" + str(oct(result))
        logging.info("User oct'ed number %s, getting a result of %s" %
                     (result, printThis))
        cprint.info(printThis)
    elif base == 10:
        base = int(
            input(
                _('''Converting from a base to decimal (normal).
Example bases:
2 - Binary
8 - Oct
16 - Hexadecimal
Or, type 1 for ord.
Type: ''')))
        if base == 1:
            base2Print = "ord"
        else:
            base2Print = "base " + base
        original = int(
            input(
                _("Please enter the number to be converted from %s: " %
                  base2Print)))
        if base == 1:
            eureka = chr(original)
        else:
            eureka = int(original, base)
        logging.info("User int'ed number %s from %s, getting a result of %s" %
                     (original, base2Print, eureka))
        cprint.info(_("That equals...\n%s" % eureka))
        cprint.ok(
            _("TIP: If you got no answer, it might be that it was a Unicode character that it can't render. E.g. \\x06 would just be a blank space, like so: \x06"
              ))
    elif base == 16:
        result = int(input(
            _("Type the original number: ")))  #ask for original number
        printThis = "=" + hex(result)
        logging.info("User hexed number %s, getting a result of %s" %
                     (result, printThis))
        cprint.info(printThis)
Пример #26
0
def compile_sketch_js(sketch, target_name):
    sketch_dir = sketch.parent

    command = ' '.join([str(c) for c in [
        'transcrypt', '-xp', PYP5_DIR, '-b', '-m', '-n', sketch
    ]])

    cprint.info(f"Converting Python to P5.js...\nRunning command:\n\t {command}")

    proc = subprocess.Popen(shlex.split(command))
    proc.wait()

    __target = sketch_dir.child('__target__')
    if not __target.exists():
        cprint.err(f"Error with transcrypt: the {__target} directory wasn't created.", interrupt=True)

    target_dir = sketch_dir.child(target_name)
    if target_dir.exists():
        shutil.rmtree(target_dir)
    shutil.move(__target, target_dir)
Пример #27
0
def monitor_sketch(sketch_name):
    """
    Monitor for any change in any .py inside the sketch dir.
    For every new change, runs the transcrypt to update the js files.

    :param sketch_name: name for new sketch
    :type sketch_name: string
    :return: file names
    :rtype: list of strings
    """

    sketch_files = SketchFiles(sketch_name)
    if not sketch_files.sketch_exists:
        raise PythonSketchDoesNotExist(sketch_files.sketch_py.resolve())

    cprint(f"Monitoring for changes in {sketch_files.sketch_dir.resolve()}...")

    try:
        monitor_sketch_service(sketch_files)
    except KeyboardInterrupt:
        cprint.info("Exiting monitor...")
Пример #28
0
 def load_synsets(self):
     cprint.info("Loading relationship synsets...")
     self.rel_synsets
     cprint.info("Loading object synsets...")
     self.obj_synsets
     cprint.info("Loading attribute synsets...")
     self.attr_synsets
Пример #29
0
async def interact(conn, svr, connector, method, args, verbose=False):
    try:
        await connector
    except Exception as e:
        print("Unable to connect to server: %s" % e)
        return -1

    cprint.info("\nConnected to: %s\n" % svr)

    if verbose:
        donate = await conn.RPC('server.donation_address')
        if donate:
            cprint.info("Donations: " + donate)

        motd = await conn.RPC('server.banner')
        cprint.info("\n---\n%s\n---" % motd)

    # XXX TODO do a simple REPL here

    if method:
        cprint.warn("\nMethod: %s" % method)

    # risky type cocerce here
    args = [(int(i) if i.isdigit() else i) for i in args]

    try:
        rv = await conn.RPC(method, *args)
        cprint.ok(json.dumps(rv, indent=1))
    except ElectrumErrorResponse as e:
        cprint.err(e)

    conn.close()
Пример #30
0
    def report(self, filepath):
        if not self.can_report():
            cprint.info(f'not more then {self.interval} minutes')
            return

        logging.info("try to report from " + filepath)
        with open(filepath, 'rb') as fp:
            binary_data = fp.read()
            if not binary_data:
                cprint.err("read image err: " + filepath)
                return

            # not json, but form-data
            # data = {
            #   'images': [base64.encodebytes(binary_data).decode('utf-8')],
            #   "category": "测试",
            #   'street': self.street,
            #   'title': '告警'
            # }
            # encoded_data = json.dumps(data).encode('utf-8')
            # r = self.http.request(
            #   'POST',
            #   self.url,
            #   body=encoded_data,
            #   headers={'Content-Type': 'application/json'}
            # )

            r = self.http.request('POST',
                                  self.url,
                                  fields={
                                      'event[images][]':
                                      ('image.jpg', binary_data),
                                      'event[title]': self.title,
                                      'event[street]': self.street,
                                      'event[category]': self.category
                                  })
            result = r.data
            logging.info("result: " + result.decode("utf-8"))
            self.last_report_time = datetime.datetime.now().time()