コード例 #1
0
ファイル: init.py プロジェクト: zheharry/bits
def early_init():
    # Set up redirection first, before importing anything else, so that any
    # errors in subsequent imports will get captured into the log.
    import_start_msg("redirect")
    import redirect
    end_msg()
    init_start_msg("redirect")
    redirect.redirect()
    init_end_msg("redirect")

    # Parse the ACPI SPCR and automatically set up the serial port if present
    serial_cmd = "false"
    try:
        import_start_msg("acpi")
        import acpi
        end_msg()
        init_start_msg("serial port redirection", False)
        spcr = acpi.parse_table("SPCR")
        if spcr is not None:
            addr = spcr.base_address
            speed = acpi.baud.get(spcr.baud_rate)
            if addr.address_space_id == acpi.ASID_SYSTEM_IO and addr.register_bit_width == 8 and addr.address != 0 and speed is not None:
                port = addr.address
                serial_cmd = "serial --port={:#x} --speed={}".format(port, speed)
    except Exception as e:
        print "Error parsing Serial Port Console Redirect (SPCR) table:"
        print e
    init_end_msg("serial port redirection")

    import_start_msg("os")
    import os
    end_msg()
    os.environ["serial_cmd"] = serial_cmd
コード例 #2
0
ファイル: init.py プロジェクト: sykeben/BITS-PyOS
def early_init():
    # Set up redirection first, before importing anything else, so that any
    # errors in subsequent imports will get captured into the log.
    with import_annotation("redirect"):
        import redirect
    with init_annotation("redirect"):
        redirect.redirect()

    # Parse the ACPI SPCR and automatically set up the serial port if present
    with init_annotation("serial port redirection"):
        serial_cmd = "false"
        try:
            with import_annotation("acpi"):
                import acpi
            spcr = acpi.parse_table("SPCR")
            if spcr is not None:
                addr = spcr.base_address
                speed = acpi.baud.get(spcr.baud_rate)
                if addr.address_space_id == acpi.ASID_SYSTEM_IO and addr.register_bit_width == 8 and addr.address != 0 and speed is not None:
                    port = addr.address
                    serial_cmd = "serial --port={:#x} --speed={}".format(
                        port, speed)
        except Exception as e:
            print "Error parsing Serial Port Console Redirect (SPCR) table:"
            print e

    with import_annotation("os"):
        import os
    with init_annotation("os"):
        os.environ["serial_cmd"] = serial_cmd
コード例 #3
0
def early_init():
    with import_annotation("redirect"):
        import redirect
    with init_annotation("redirect"):
        redirect.redirect()

    with import_annotation("os"):
        import os
コード例 #4
0
    def run_bmcs(aig_filename):

        with redirect.save_stdout() as prev_stdout:
            with redirect.redirect(src=sys.stdout):
                with redirect.redirect(src=sys.stderr):
                    bmcs_engine(aig_filename, prev_stdout)

        os._exit(0)
コード例 #5
0
        def simplify():

            with redirect.redirect(src=sys.stdout):
                with redirect.redirect(src=sys.stderr):
                    par.read_file_quiet(aig_filename)
                    par.pre_simp()
                    pyabc.run_command('write_aiger %s' % simplified_aig)

            return simplified_aig
コード例 #6
0
def run(module, command):
    """
    module: e.g. "SavedPositionsPanel_2"
    command: e.g. "ConfigurationsPanel()"
    """
    from redirect import redirect
    redirect(module)
    import autoreload
    import wx
    if not hasattr(wx, "app"): wx.app = wx.App(redirect=False)
    exec("from instrumentation import *")  # -> locals()
    exec("from %s import *" % module)
    exec(command)
    wx.app.MainLoop()
コード例 #7
0
    def __init__(self, parent=None, name=None):
        if name is not None: self.name = name

        from redirect import redirect
        redirect(self.name)

        wx.Frame.__init__(self, parent=parent)

        self.update()
        self.Show()

        # Refresh
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
        self.timer.Start(5000, oneShot=True)
コード例 #8
0
def run_bip(args, aiger):

    log('running: bip', " ".join(args), aiger)

    import redirect
    with redirect.redirect():

        with temp_file_names(1) as tmpnames:

            args = [
                'bip',
                '-abc',
                '-input=%s'%aiger,
                '-output=%s'%tmpnames[0],
            ] + args;
            
            rc = subprocess.call(args)
            
            if rc!=0:
                return None

            res = parse_bip_status(tmpnames[0])

    log('bip finished:', rc, res)
    return res
コード例 #9
0
def addsnippet(headers, body, data):
    #login = str(data['login']) if 'login' in data else ''
    # password = str(data['password']) if 'password' in data else ''
    cookie = str(headers['http-cookie']).replace('sessionid=', '')
    if not cookie_check(cookie):
        return redirect(headers=headers,
                        body=body,
                        data=data,
                        message="Nieautoryzowana proba dodania snippet'a!")

    snippet_content = str(data['snippet']) if 'snippet' in data else ''
    title = str(data['title']) if 'title' in data else ''

    if (title == '' or snippet_content == ''):
        return render_template('html/addsnippet.html',
                               body=body,
                               data=data,
                               headers=headers,
                               cookie=cookie), 200, {}
    elif len(title) > 60:
        return render_template(
            'html/addsnippet.html',
            body=body,
            data=data,
            headers=headers,
            cookie=cookie,
            message="Maksymalna dlugosc nazwy snippet'a to 24 znaki!"
        ), 200, {}
    elif len(snippet_content) > 9999:
        return render_template(
            'html/addsnippet.html',
            body=body,
            data=data,
            headers=headers,
            cookie=cookie,
            message="Dodany przez Ciebie plik jest zbyt dlugi!"), 200, {}

    add_snippet(title, snippet_content, cookie)
    return redirect(headers=headers,
                    body=body,
                    data=data,
                    message='Snippet zostal dodany!')
コード例 #10
0
ファイル: niklas.py プロジェクト: rubund/berkeley-abc
def run_bip(args, aiger):

    import redirect

    with redirect.redirect():

        with temp_file_names(1) as tmpnames:

            args = ["bip", "-abc", "-input=%s" % aiger, "-output=%s" % tmpnames[0]] + args

            rc = subprocess.call(args, preexec_fn=pyabc._set_death_signal)

            if rc != 0:
                return None

            return parse_bip_status(tmpnames[0])
コード例 #11
0
def run_bip(args, aiger):

    import redirect
    with redirect.redirect():

        with temp_file_names(1) as tmpnames:

            args = [
                'bip',
                '-abc',
                '-input=%s' % aiger,
                '-output=%s' % tmpnames[0],
            ] + args

            rc = subprocess.call(args, preexec_fn=pyabc._set_death_signal)

            if rc != 0:
                return None

            return parse_bip_status(tmpnames[0])
コード例 #12
0
def view(headers, body, data, snippet_title):
    snippet_title = str(snippet_title)
    dbfile = '/home/wolonkia/vial/genbase.db'
    conn = sqlite3.connect(dbfile)
    cursor = conn.cursor()
    cursor.execute('SELECT login FROM snippets WHERE title = ?;',
                   (snippet_title, ))
    login = cursor.fetchone()

    if login is None:
        return redirect(headers,
                        body=body,
                        data=data,
                        message='Podany plik nie istnieje!'), 200, {}
    #snippet_path = 'od.iem.pw.edu.pl:2552/static/snippets/' + str(snippet_title) + '.snippet'
    snippet_title = str(snippet_title) + '.snippet'
    return render_template('html/view.html',
                           body=body,
                           data=data,
                           headers=headers,
                           snippet_title=snippet_title), 200, {}
コード例 #13
0
def pipe(args):
    pr, pw = os.pipe()
    rc = os.fork()

    if rc < 0:
        os.write(2, "fork failed, exiting...".encode())
        sys.exit(1)

    elif rc == 0:  # child - will write to pipe
        os.close(1)  # redirect child's stdout
        os.dup(pw)
        os.set_inheritable(1, True)

        for fd in (pr, pw):
            os.close(fd)

        left_args = args[:args.index('|')]

        if '<' in left_args:
            redirect(left_args, '<')

        try:
            os.execve(left_args[0], left_args, os.environ)
        except FileNotFoundError:
            pass

        for dir in re.split(
                ":", os.environ['PATH']):  # try each directory in the path
            program = "%s/%s" % (dir, left_args[0])

            try:
                os.execve(program, left_args,
                          os.environ)  # try to exec program

            except FileNotFoundError:  # ...expected
                pass  # ...fail quietly

        os.write(2, ("Could not exec: %s\n" % left_args[0]).encode())
        sys.exit(1)

    else:  # parent (forked ok)
        os.close(0)
        os.dup(pr)
        os.set_inheritable(0, True)

        for fd in (pw, pr):
            os.close(fd)

        right_args = args[args.index('|') + 1:]

        if '>' in right_args:
            redirect(right_args, '>')

        for dir in re.split(
                ":", os.environ['PATH']):  # try each directory in the path
            program = "%s/%s" % (dir, right_args[0])

            try:
                os.execve(program, right_args,
                          os.environ)  # try to exec program
            except FileNotFoundError:  # ...expected
                pass  # ...fail quietly

        os.write(2, ("Could not exec: %s\n" % right_args[0]).encode())
        sys.exit(1)
コード例 #14
0
        mySocket.listen(5)

        # Accept connections, read incoming data, and call
        # parse and process methods (in a loop)

        while True:
            print('Waiting for connections')
            (recvSocket, address) = mySocket.accept()
            print('HTTP request received (going to parse and process):')
            request = recvSocket.recv(2048).decode('utf-8')
            print(request)
            (theApp, rest) = self.select(request)
            (method, parsedRequest) = theApp.parse(request)
            (returnCode, htmlAnswer) = theApp.process(parsedRequest, method,
                                                      rest)
            print('Answering back...')
            recvSocket.send(
                bytes(
                    "HTTP/1.1 " + returnCode + " \r\n\r\n" + htmlAnswer +
                    "\r\n", 'utf-8'))
            recvSocket.close()


if __name__ == "__main__":
    form = form.form()
    redirect = redirect.redirect()
    testWebApp = webApp("localhost", 1234, {
        'root': form,
        'redirect': redirect
    })
コード例 #15
0
            if not abs(new_value - self.value) < stepsize:
                self.value = new_value

    def post_update(self):
        """Keep the user value constant while tweeking the dial"""
        from numpy import isnan
        if self.keep_value and not isnan(self.value):
            self.register.value = self.value

    from numpy import nan
    value = nan

    def next_step(self, step):
        """Closest possible value for the offset increment
        step: offset increment in seconds"""
        from timing_system import round_next
        stepsize = self.register.stepsize
        if step > 0.5 * stepsize:
            step = max(round_next(step, stepsize), stepsize)
        return step


if __name__ == '__main__':
    from pdb import pm  # for debugging
    from redirect import redirect
    redirect("Timing_Calibration_Panel")
    import wx
    app = wx.App(redirect=False)
    panel = Timing_Calibration_Panel()
    app.MainLoop()
コード例 #16
0
ファイル: syn.py プロジェクト: berkeley-abc/super_prove
def abc_redirect(cmd, dst=redirect.null_file, src=sys.stdout):
    """This is our main way of calling an ABC function. Redirect, means that we suppress any output from ABC"""
    with redirect.redirect(dst, src):
        return run_command(cmd)
コード例 #17
0
        "SavedPositionsPanel_2",
        "ConfigurationPanel(name=%r,globals=globals(),locals=locals())" % name)


def show_configurations():
    ##ConfigurationsPanel()
    from start import start
    start("SavedPositionsPanel_2", "ConfigurationsPanel()")


if __name__ == '__main__':
    from pdb import pm  # for debugging

    from redirect import redirect
    format = "%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s"
    redirect("SavedPositionsPanel_2", format=format)

    import autoreload
    ##name = ""
    ##name = "beamline_configuration"
    ##name = "sequence_modes"
    ##name = "high_speed_chopper_modes"
    ##name = "Julich_chopper_modes"
    name = "timing_modes"
    ##name = "delay_configuration"
    ##name = "power_configuration"
    ##name = "detector_configuration"
    ##name = "method"
    # Allow commandline argument to specifiy which configuration to use.
    from sys import argv
    if len(argv) >= 2: name = argv[1]
コード例 #18
0
#!/usr/bin/env python
"""
Grapical User Interface for FPGA Timing System.
Author: Friedrich Schotte
Date created: 2019-03-26
Date last modified: 2019-03-26
"""
__version__ = "1.0"

from logging import debug, info, warn, error

from SavedPositionsPanel_2 import SavedPositionsPanel


class Sequence_Modes_Panel(SavedPositionsPanel):
    name = "sequence_modes"


if __name__ == '__main__':
    from pdb import pm  # for debugging
    from redirect import redirect
    redirect("Sequence_Modes_Panel")
    import wx
    app = wx.App(redirect=False)
    panel = Sequence_Modes_Panel()
    app.MainLoop()
コード例 #19
0
ファイル: syn.py プロジェクト: berkeley-abc/super_prove
def abc_redirect_all(cmd):
    """This is our main way of calling an ABC function. Redirect, means that we suppress any output from ABC, including error printouts"""
    with redirect.redirect(redirect.null_file, sys.stdout):
        with redirect.redirect(redirect.null_file, sys.stderr):
            return run_command(cmd)
コード例 #20
0
            "type": "Off/On",
            "refresh_period": 1.0
        }],
    ]

    def __init__(self, parent=None):
        BasePanel.__init__(
            self,
            parent=parent,
            name=self.name,
            title=self.title,
            icon="Rayonix Detector",
            parameters=self.parameters,
            standard_view=self.standard_view,
            label_width=180,
            refresh=False,
            live=False,
        )
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        rayonix_detector.limit_files_enabled = True


if __name__ == '__main__':
    from pdb import pm  # for debugging
    from redirect import redirect
    redirect("Rayonix_Detector_Panel", level="INFO")
    import wx
    app = wx.App(redirect=False)
    panel = Rayonix_Detector_Panel()
    app.MainLoop()
コード例 #21
0
    wait = True
    if '&' in args:
        wait = False
        args.remove('&')

    if rc < 0:
        os.write(2, "fork failed, exiting...".encode())
        sys.exit(0)

    elif rc == 0:  # child
        if '|' in args:
            pipe(args)
            continue

        if '<' in args:
            redirect(args, '<')

        if '>' in args:
            redirect(args, '>')

        try:
            os.execve(args[0], args, os.environ)
        except FileNotFoundError:
            pass

        for dir in re.split(":", os.environ['PATH']):  # try each directory in the path
            program = "%s/%s" % (dir, args[0])

            try:
                os.execve(program, args, os.environ)  # try to exec program
            except FileNotFoundError:  # ...expected
コード例 #22
0
#!/usr/bin/env python
"""
Author: Friedrich Schotte
Date created: 2019-02-02
Date last modified: 2019-02-03
"""
from redirect import redirect
redirect("collect_monitor")
from CA import camonitor
camonitor("NIH:TIMING.registers.ch7_state.count")
camonitor("NIH:TIMING.registers.image_number.count")
camonitor("NIH:TIMING.registers.xdet_count.count")
camonitor("NIH:TIMING.registers.xdet_trig_count.count")
camonitor("NIH:TIMING.registers.xdet_acq_count.count")
camonitor("NIH:TIMING.registers.acquiring.count")
from time import sleep
while True: sleep(0.1)
コード例 #23
0
            [PropertyPanel,[],{"name":"channels[%d].pulse_length_PP"%i,"type":"float","width":70,"refresh_period":inf}],
            [TogglePanel,  [],{"name":"channels[%d].enable.count"%i,"type":"/Cont","width":45,"refresh_period":inf}],
            [PropertyPanel,[],{"name":"channels[%d].timed"%i,"width":72,"refresh_period":inf}],
            [PropertyPanel,[],{"name":"channels[%d].gated"%i,"width":72,"refresh_period":inf}],
            [PropertyPanel,[],{"name":"channels[%d].counter_enabled"%i,"type":"/On","width":50,"refresh_period":inf}],
            [PropertyPanel,[],{"name":"channels[%d].output_status"%i,"width":60,"refresh_period":inf}],
        ] for i in range(0,len(timing_system.channels))]

        BasePanel.__init__(self,
            parent=parent,
            name=self.name,
            title=self.title,
            icon=self.icon,
            object=self.object,
            layout=self.layout,
            standard_view=self.standard_view,
            label_width=25,
            refresh=True,
            live=True,
            update=update,
        )
        
if __name__ == '__main__':
    from pdb import pm # for debugging
    from redirect import redirect
    redirect("Timing_Channel_Configuration_Panel")
    import wx
    app = wx.App(redirect=False) # to initialize WX...
    panel = Timing_Channel_Configuration_Panel()
    app.MainLoop()
コード例 #24
0
        BasePanel.__init__(
            self,
            parent=parent,
            name=self.name,
            title=self.title,
            icon="Rayonix Detector",
            parameters=self.parameters,
            standard_view=self.standard_view,
            label_width=180,
            refresh=False,
            live=False,
        )
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        rayonix_detector.limit_files_enabled = True

    def OnClose(self, event=None):
        # Shut down background tasks.
        rayonix_detector.limit_files_enabled = False
        rayonix_detector.ADXV_live_image = False
        self.Destroy()


if __name__ == '__main__':
    from pdb import pm  # for debugging
    from redirect import redirect
    redirect("Rayonix_Detector_Panel_old")
    import wx
    app = wx.App(redirect=False)
    panel = Rayonix_Detector_Panel_old()
    app.MainLoop()
コード例 #25
0
#C:\...\PP4E\System\Streams> python
from teststreams import interact
##### interact()    # for testing need activate this line and deactivate other
# Hello stream world
#Enter a number>2
# 2 squared is 4
# Enter a number>3
# 3 squared is 9
# Enter a number^Z
# Bye

from redirect import redirect
(result, output) = redirect(interact, (), {}, '4\n5\n6\n')
print(result)
# None
# ######################################################################################################################

print(output)
# 'Hello stream world\nEnter a number>4 squared is 16\nEnter a number>5 squared
# is 25\nEnter a number>6 squared is 36\nEnter a number>Bye\n'

# for line in output.splitlines(): print(line)

# Hello stream world
# Enter a number>4 squared is 16
# Enter a number>5 squared is 25
# Enter a number>6 squared is 36
# Enter a number>Bye

# from PP4E.System.more import more
# more(output)
コード例 #26
0
    ]
    
    def __init__(self,parent=None):
        BasePanel.__init__(self,
            parent=parent,
            name=self.name,
            title=self.title,
            icon="ADXV",
            parameters=self.parameters,
            standard_view=self.standard_view,
            label_width=140,
            width=260,
            refresh=False,
            live=False,
        )
        self.Bind(wx.EVT_CLOSE,self.OnClose)

    def OnClose(self,event=None):
        # Shut down background tasks.
        ADXV_live_image.live_image = False
        self.Destroy()
        
if __name__ == '__main__':
    from pdb import pm # for debugging
    from redirect import redirect
    redirect("ADXV_Live_Image_Panel")
    import wx
    app = wx.App(redirect=False) 
    panel = ADXV_Live_Image_Panel()
    app.MainLoop()
コード例 #27
0
            label_width=180,
            refresh=True,
            live=True,
            subpanels=[
                ["Setup...",                Timing_Setup_Panel],
                ["Channel Configuration...",Timing_Channel_Configuration_Panel],
                ["Calibration...",          Timing_Calibration_Panel],
                ["Clock Configuration...",  Timing_Clock_Configuration_Panel],
                ["PP Modes...",             PP_Modes_Panel],
                ["Sequence Modes...",       Sequence_Modes_Panel],
                ["Configuration...",        Timing_Configuration_Panel],
            ],
            buttons=[
                ["Cal..",Timing_Calibration_Panel],
                ["Conf..",Timing_Channel_Configuration_Panel],
                ["Setup..",Timing_Setup_Panel],
                ["Modes..",PP_Modes_Panel],
            ],
        )


if __name__ == '__main__':
    from pdb import pm # for debugging
    from redirect import redirect
    redirect("Timing_Panel")
    import autoreload
    import wx
    wx.app = wx.App(redirect=False)
    panel = Timing_Panel()
    wx.app.MainLoop()
コード例 #28
0
            name=self.name + ".report",
            size=(420, 160),
        )
        layout.Add(control, flag=wx.ALIGN_CENTRE | wx.ALL)

        panel.Fit()
        return panel


def update_globals():
    global dataset
    try:
        import dataset_check
        reload(dataset_check)
        from dataset_check import dataset
        globals()["dataset"] = dataset
    except Exception, msg:
        error("%s\n%s" % (msg, format_exc()))


if __name__ == '__main__':
    from pdb import pm
    from redirect import redirect
    redirect("Check_Dataset_Panel")

    import autoreload
    # Needed to initialize WX library
    wx.app = wx.App(redirect=False)
    panel = Dataset_Check_Panel()
    wx.app.MainLoop()
コード例 #29
0
#!/usr/bin/env python
"""Alio diffractometer
Control panel to save and motor positions.
Author: Friedrich Schotte
Date created: 2009-10-18
Date last modified: 2019-01-27
"""
__version__ = "1.3.1" # logging

from pdb import pm # for debugging

from redirect import redirect
redirect("AlioDiffractometerSavedPositionsPanel")

import wx
app = wx.App(redirect=False) 
from instrumentation import * # -> globals()
from SavedPositionsPanel_2 import SavedPositionsPanel
panel = SavedPositionsPanel(name="alio_diffractometer_saved",globals=globals())
app.MainLoop()
コード例 #30
0
        "Clock manager",
        "Clock multiplier",
        "Clock divider",
        "Clock DFS frequency mode",
        "Clock DLL frequency mode",
        "Clock multiplier status",
        "Internal clock frequency",
    ]
    def __init__(self,parent=None,update=lambda: None):
        from Panel import PropertyPanel
        BasePanel.__init__(self,parent=parent,
            name=self.name,
            title=self.title,
            icon=self.icon,
            component=PropertyPanel,
            parameters=self.parameters,
            standard_view=self.standard_view,
            label_width=250,
            refresh=True,
            live=True,
        )
       
if __name__ == '__main__':
    from pdb import pm # for debugging
    from redirect import redirect
    redirect("Timing_Clock_Configuration_Panel")
    import wx
    app = wx.App(redirect=False) 
    panel = Timing_Clock_Configuration_Panel()
    app.MainLoop()
コード例 #31
0
#!/usr/bin/env python
"""
Grapical User Interface for FPGA Timing System.
Author: Friedrich Schotte
Date created: 2019-03-26
Date last modified: 2019-03-26
"""
__version__ = "1.0"

from logging import debug, info, warn, error

from SavedPositionsPanel_2 import SavedPositionsPanel


class PP_Modes_Panel(SavedPositionsPanel):
    name = "timing_modes"


if __name__ == '__main__':
    from pdb import pm  # for debugging
    from redirect import redirect
    redirect("PP_Modes_Panel")
    import wx
    app = wx.App(redirect=False)
    panel = PP_Modes_Panel()
    app.MainLoop()
コード例 #32
0
            globals=globals(),
            locals=locals(),
            name="Collect_Panel.Finish_Series_Variable",
            size=(width, height),
        )
        group.Add(control, flag=flag, border=border, proportion=1)

        panel.Fit()
        return panel

    @staticmethod
    def show_methods():
        from SavedPositionsPanel_2 import show_panel
        show_panel("method")

    @staticmethod
    def play_sound():
        from sound import play_sound
        play_sound("ding")


if __name__ == '__main__':
    from pdb import pm
    from redirect import redirect
    redirect("Collect_Panel")
    ##import autoreload
    # Needed to initialize WX library
    if not hasattr(wx, "app"): wx.app = wx.App(redirect=False)
    panel = Collect_Panel()
    wx.app.MainLoop()