Ejemplo n.º 1
0
def gui():
	'''
	Generates the interface for the file sequencer.
	'''
	if( cmds.window(win, ex=True) ):
		cmds.deleteUI(win)
	if( cmds.windowPref(win, ex=True) ):
		cmds.windowPref(win, r=True)
		
	cmds.window(win, h=500, w=400)
	mainCol = cmds.columnLayout()
	
	cmds.rowColumnLayout(nc=2, cw=[[1,200],[2,200]])
	global targField, destField, tslTarget, tslDestin
	
	targField = cmds.scrollField( w=200, h=50, editable=False, wordWrap=True, text='Non editable with word wrap' )
	destField = cmds.scrollField( w=200, h=50, editable=False, wordWrap=True, text='Non editable with word wrap' )
	cmds.button(label="Load Target", c=Callback(getTarget))
	cmds.button(label="Load Destination", c=Callback(getDestin))
	
	cmds.text(label = "Target Files")
	cmds.text(label = "Destination Files")
	
	tslTarget = TextScrollList(200, 200)

	tslDestin = TextScrollList(200, 200)
	cmds.setParent(mainCol)
	
	# Inputs
	fieldsGUI(mainCol)
	
	cmds.showWindow(win)
	
	print("Interface executed.")
Ejemplo n.º 2
0
def get_callbacks(config, vae_m, data):

    if config['formal_training']:

        callback_1 = Callback(vae_m,
                              data.X_vali,
                              data.Y_vali,
                              config,
                              save_model=True)

        callback_2 = Callback(vae_m,
                              data.X_test,
                              data.Y_test,
                              config,
                              save_model=False)

        return [callback_1, callback_2]

    callback = Callback(vae_m,
                        data.X_test,
                        data.Y_test,
                        config,
                        save_model=True)

    return [callback]
Ejemplo n.º 3
0
def first_of(*a):
    cb = Callback()
    cb.called = False
    for i, c in enumerate(a):
        def cb(result, i=i):
            if isinstance(result, Exception):
                raise result
            if not cb.called:
                cb.called = True
                cb((i, result))
        c.add(cb)
    x, r = yield cb
    yield Return([(True, r) if x == i else None for i in xrange(len(a))])
Ejemplo n.º 4
0
def first_of(*a):
    cb = Callback()
    cb.called = False
    for i, c in enumerate(a):

        def cb(result, i=i):
            if isinstance(result, Exception):
                raise result
            if not cb.called:
                cb.called = True
                cb((i, result))

        c.add(cb)
    x, r = yield cb
    yield Return([(True, r) if x == i else None for i in xrange(len(a))])
Ejemplo n.º 5
0
    def addAttrGUI(self):
        win = "attrInfoWin"

        if (cmds.window(win, ex=True)):
            cmds.deleteUI(win)
        if (cmds.windowPref(win, ex=True)):
            cmds.windowPref(win, r=True)

        cmds.window(win, title="Add Attribute", w=300, h=87)

        # mainCol = cmds.columnLayout(rs=5)
        mainFrm = cmds.formLayout()
        # cmds.rowColumnLayout(nc=2, cw=[[1,175],[2,100]])
        self.rbtn = cmds.radioButtonGrp(nrb=2,
                                        labelArray2=["ChannelBox", "Custom"],
                                        cw=[[1, 100], [2, 75]],
                                        sl=1)
        self.txt = cmds.textFieldGrp(w=100, text="object.attribute")
        btn = cmds.button(label="Apply", w=275, c=Callback(self.guiInfo))
        cmds.formLayout(mainFrm,
                        e=1,
                        af=[[self.rbtn, "left", 5], [self.rbtn, "top", 5]])
        cmds.formLayout(mainFrm,
                        e=1,
                        af=[self.txt, "top", 3],
                        ac=[self.txt, "left", 0, self.rbtn])
        cmds.formLayout(mainFrm,
                        e=1,
                        af=[btn, "left", 5],
                        ac=[btn, "top", 3, self.rbtn])

        cmds.showWindow(win)
Ejemplo n.º 6
0
    def _mixerGUI(self, currParent):

        frame = cmds.frameLayout(parent=currParent,
                                 lv=0,
                                 marginWidth=5,
                                 marginHeight=3)
        frm = cmds.formLayout(parent=frame)
        self.mSlider = cmds.floatSliderGrp(field=1,
                                           label="Attribute Mixer",
                                           cw=[1, 75],
                                           cc=self.changeVal,
                                           dc=self.changeVal,
                                           min=-10,
                                           max=10,
                                           step=.1)
        btn1 = cmds.button(label="Reset", w=50, c=Callback(self.resetSlider))
        # btn2 = cmds.button( label="Offset", w=50)

        cmds.formLayout(frm,
                        e=1,
                        af=[[self.mSlider, "left", 5],
                            [self.mSlider, "top", 0]])
        cmds.formLayout(frm,
                        e=1,
                        ac=[btn1, "left", 5, self.mSlider],
                        af=[btn1, "top", 0])
        # cmds.formLayout( frm, e=1, ac=[btn2, "left", 5, btn1], af=[btn2, "top", 0])

        return frame
Ejemplo n.º 7
0
def fieldsGUI(curParent):
	frm = cmds.formLayout( parent=curParent)
	# Row 1 labels
	txt1 = cmds.text(label="fileName", w=200)
	txt2 = cmds.text(label="##", w=60)
	txt3 = cmds.text(label="Pad", w=40)
	
	# Row 2 Fields
	global mainName, counter, pad, copyChk
	mainName = cmds.textField( w=200 )
	counter = cmds.intField( w=60, v=1 )
	pad = cmds.intField( w=40, v=3 )
	
	# Row 3 Buttons
	btn1 = cmds.button(label="Next", w=200, c=Callback(process))
	# copyChk = cmds.checkBox( label="move", v=1, 
	
	# Positioning GUI elements
	cmds.formLayout(frm, e=1, af=[])
	cmds.formLayout(frm, e=1, ac=[])
	
	# Row1
	cmds.formLayout(frm, e=1, af=[[txt1, "left", 0],[txt1, "top", 0]])
	cmds.formLayout(frm, e=1, af=[txt2, "top", 0], ac=[txt2, "left", 0, txt1])
	cmds.formLayout(frm, e=1, af=[txt3, "top", 0], ac=[txt3, "left", 0, txt2])
	
	# Row 2
	cmds.formLayout(frm, e=1, af=[mainName, "left", 0],ac=[mainName, "top", 0, txt1])
	cmds.formLayout(frm, e=1, ac=[[counter, "left", 0, mainName],[counter, "top", 0, txt1]])
	cmds.formLayout(frm, e=1, ac=[[pad, "left", 0, counter],[pad, "top", 0, txt1]])
		
	# Row 3
	cmds.formLayout(frm, e=1, af=[btn1, "left", 0],ac=[btn1, "top", 0, mainName])
	
	return frm
Ejemplo n.º 8
0
def gui():
    '''
	Generate scriptJob Win GUI.
	'''

    if (cmds.window(win, q=True, ex=True)):
        cmds.deleteUI(win)

    cmds.window(win, title="Script Jobs Info", mb=True, w=300, h=200)

    cmds.menu(label="ScriptJob Edit")
    cmds.menuItem(label="Refresh List", c=Callback(sjRefresh))
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Kill Normal", c=Callback(sjKill))
    cmds.menuItem(label="Kill Protected", c=Callback(sjKillProtected))
    sjKillGUI()

    cmds.showWindow(win)
Ejemplo n.º 9
0
    def _addTab(self, name):
        '''
        Adds an additional tab to the system.
        '''

        # Make sure that a tab exists!
        # scroll = cmds.scrollLayout( h=450, parent=self.mainTab )
        col = cmds.columnLayout(parent=self.mainTab)

        frm = cmds.formLayout(w=450)
        path = os.path.split(__file__)[0]
        fullPath = lambda x: os.path.join(path, "icons", x)

        btn1 = cmds.symbolButton(image=fullPath('plus_16b.xpm'),
                                 h=20,
                                 command=Callback(
                                     self.addFramePrompt))  # self._attrGUI )

        btn2 = cmds.symbolButton(
            image=fullPath('delete_16b.xpm'),
            h=20,
            command=Callback(self._removeTab))  #command=self._removeAttrs )

        btn3 = cmds.symbolButton(image=fullPath('save_16.xpm'),
                                 h=20,
                                 command=Callback(
                                     self._saveTab))  # self._attrGUI )

        txt = cmds.text(l="")

        cmds.formLayout(frm,
                        e=1,
                        af=[[btn1, "top", 5], [btn1, "left", 5],
                            [btn2, "top", 5], [btn3, "top", 5],
                            [txt, "top", 5], [txt, "right", 0]],
                        ac=[[btn2, "left", 0, btn1], [btn3, "left", 0, btn2]])
        cmds.setParent(col)
        # frm = cmds.formLayout( parent=self.mainTab, w=300, h=300 )

        cmds.tabLayout(self.mainTab, e=1, tl=[col, name])
        self.tabs[col] = []
        self.tabNames.append(col)
        return col
Ejemplo n.º 10
0
 def configure(self, *callbacks, **kwargs):
     cbs = []
     if len(callbacks) > 0:
         if 'callbacks' in kwargs:
             raise InvalidConfiguration(
                 "You cannot pass a list of callbacks and specify a keyword callback list in the same configuration."
             )
         for fn in callbacks:
             cbs.append(Callback(fn))
         kwargs['callbacks'] = cbs
     for k, v in kwargs.iteritems():
         self.config.set(k, v)
Ejemplo n.º 11
0
    def _create_job(self, *args, **kwargs):
        cb = Callback._get_callback(self)
        job = ThreadInProgress(cb, *args, **kwargs)
        job.priority = self.priority

        if not _threads.has_key(self._thread):
            _threads[self._thread] = _JobServer(self._thread)
        server = _threads[self._thread]
        server.add(job)
        # Hook the aborted signal for the ThreadInProgress to stop the thread
        # callback.
        self._setup_abort(server, job)
        return job
Ejemplo n.º 12
0
 def send(self, value):
     if self._recv_cbs:
         # if there are receivers waiting, send to the first one
         rcb = self._recv_cbs.popleft()
         queue_task(0, rcb, value)
     elif len(self._msgs) < self.bufsize:
         # if there's available buffer, use that
         self._msgs.append(value)
     else:
         # otherwise, wait for a receiver
         cb = Callback()
         self._send_cbs.append(cb)
         rcb = yield cb
         queue_task(0, rcb, value)
Ejemplo n.º 13
0
def gui():
	win = "mecAttrGWin"
	if( cmds.window( win, ex=True)):
		cmds.deleteUI(win)
	if( cmds.windowPref(win, ex=True)):
		cmds.windowPref(win, remove=True)
		
	cmds.window( win, title="Attribute Grabber", width=450, h=400, menuBar=True )

	
	tab = TabGroup(win)	

	cmds.menu(label="Attributes")
	cmds.menuItem(label="Add Tab",
				  command=Callback(tab.addTabPrompt))
	cmds.menuItem(label="Add Tab (file)",
		command=Callback(tab._loadTab))
	cmds.menuItem(label="Save Tab",
		command=Callback(tab._saveTab))
	cmds.menuItem(label="Remove Tab",
		command=Callback(tab._removeTab))
	cmds.menuItem(divider=True)
	
	cmds.menuItem(label="Add Frame",
	   command=Callback(tab.addFramePrompt))
	cmds.menuItem(label="Add Frame (file)")
	cmds.menuItem(label="Save Frame")
	cmds.menuItem(label="Remove Frame")
		
	
	cmds.menuItem(divider=True)
	
	
	cmds.menu(label="About")
		
	
	cmds.showWindow()
Ejemplo n.º 14
0
    def recv(self):
        # if there's buffer, read it
        if self._msgs:
            value = self._msgs.popleft()
            yield Return(value)

        # otherwise we need a sender
        rcb = Callback()
        if self._send_cbs:
            # if there are senders waiting, wake up the first one
            cb = self._send_cbs.popleft()
            cb(rcb)
        else:
            # otherwise, wait for a sender
            self._recv_cbs.append(rcb)
        value = yield rcb
        yield Return(value)
Ejemplo n.º 15
0
    def _create_thread(self, *args, **kwargs):
        """
        Create and start the thread.
        """
        cb = Callback._get_callback(self)
        async = ThreadInProgress(cb, *args, **kwargs)
        # create thread and setDaemon
        t = threading.Thread(target=async)
        t.setDaemon(not self._wait_on_exit)
        # connect thread.join to the InProgress
        join = lambda *args, **kwargs: t.join()

        # Hook the aborted signal for the ThreadInProgress to stop the thread
        # callback.
        self._setup_abort(t, async)
        # XXX: this was in the original abort code but I don't think it's necessary.
        # If I'm wrong, uncomment and explain why it's needed.
        #async.signals['abort'].connect(lambda: async.exception.disconnect(join))

        async.connect_both(join, join)
        # start the thread
        t.start()
        return async
Ejemplo n.º 16
0
def main():
    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir", action="store", type="string", help="Use an alternate statedir", default=".")
    command_line_parser.add_option("--ip", action="store", type="string", default="0.0.0.0", help="Dispersy uses this ip")
    command_line_parser.add_option("--port", action="store", type="int", help="Dispersy uses this UDL port", default=6421)

    # parse command-line arguments
    opt, _ = command_line_parser.parse_args()
    print "Press Ctrl-C to stop Dispersy"

    # start Dispersy
    dispersy = TrackerDispersy.get_instance(Callback(), unicode(opt.statedir), opt.port)
    dispersy.endpoint = StandaloneEndpoint(dispersy, opt.port, opt.ip)
    dispersy.endpoint.start()
    dispersy.define_auto_load(TrackerCommunity)

    def signal_handler(sig, frame):
        print "Received", sig, "signal in", frame
        dispersy.callback.stop(wait=False)
    signal.signal(signal.SIGINT, signal_handler)

    # wait forever
    dispersy.callback.loop()
    dispersy.endpoint.stop()
Ejemplo n.º 17
0
def readXML():
    '''
	Reads the provided xml to load the menu items.
	'''
    filePath = os.path.join(__path__[0], "menu.xml")
    xmlFile = open(filePath, "r")

    # Parse xml file
    xmlInfo = ET.parse(xmlFile)
    # Get root
    root = xmlInfo.getroot()
    # close file
    xmlFile.close()

    scriptName = "mecScripts"
    # print("ScriptName: " + scriptName)
    # Create top menus
    for mainMenu in root:
        cmds.menuItem(label=mainMenu.text.rstrip().lstrip(),
                      subMenu=True,
                      to=int(mainMenu.attrib['tearoff']))
        # print( int(mainMenu.attrib['tearoff']) )
        for subMenu in mainMenu:
            if (subMenu.tag == "script"):
                line1 = subMenu[0].text
                # print(line1)
                line2 = subMenu[1].text
                if (int(subMenu.attrib['type'])):
                    cmds.menuItem(label=subMenu.text.rstrip().lstrip(),
                                  ann=subMenu[2].text,
                                  c="%s;%s" % (line1, line2))
                else:
                    cmds.menuItem(label=subMenu.text.rstrip().lstrip(),
                                  ann=subMenu[2].text,
                                  c=Callback(melRun, line1, line2))
                    #"mecScripts.melRun('%s','%s')" %(line1,line2))
            else:
                cmds.menuItem(label=subMenu.text.rstrip().lstrip(),
                              subMenu=True,
                              to=int(subMenu.attrib['tearoff']))

                for scriptName in subMenu:
                    line1 = scriptName[0].text
                    # print(line1)
                    line2 = scriptName[1].text
                    if (int(scriptName.attrib['type'])):
                        cmds.menuItem(label=scriptName.text.rstrip().lstrip(),
                                      ann=scriptName[2].text,
                                      c=Callback(melRun, line1, line2))
                        # c="%s;%s" %(line1, line2))
                    else:
                        cmds.menuItem(label=scriptName.text.rstrip().lstrip(),
                                      ann=scriptName[2].text,
                                      c=Callback(melRun, line1, line2))
                        # c="mecScripts.melRun('%s','%s')" %(line1,line2))
                '''
				cmds.menuItem( label=scriptName.text.rstrip().lstrip(),
					ann=scriptName[2].text,
					c=(lambda *args: eval( 'melRun( "%s", "%s")' %(line1, line2))))
				'''
                cmds.setParent("..", menu=True)
        cmds.setParent("..", menu=True)
Ejemplo n.º 18
0
import flask
import os
from index import Index
from sign import Sign
from callback import Callback
from logout import Logout

app = flask.Flask(__name__)       # our Flask app

app.secret_key = os.urandom(24)

app.add_url_rule('/',
                 view_func=Index.as_view('index'),
                 methods=["GET"])

app.add_url_rule('/callback',
                 view_func=Callback.as_view('callback'),
                 methods=["GET"])

app.add_url_rule('/sign',
                 view_func=Sign.as_view('sign'),
                 methods=['GET', 'POST'])

app.add_url_rule('/logout',
                 view_func=Logout.as_view('logout'),
                 methods=["GET"])

if __name__ == '__main__':
    os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = "1"
    app.run(host='0.0.0.0', port=8000, debug=True)
Ejemplo n.º 19
0
            from_gen = Return()
        except Exception, e:
            callback(_add_monocle_tb(e))
            return callback

        if isinstance(from_gen, Return):
            try:
                g.close()
            except Exception, e:
                callback(_add_monocle_tb(e))
            else:
                callback(from_gen.value)
            return callback
        elif not isinstance(from_gen, Callback):
            if isinstance(from_gen, TwistedDeferred):
                cb = Callback()
                from_gen.addCallbacks(cb, lambda f: cb(_add_twisted_tb(f)))
                from_gen = cb
            else:
                e = InvalidYieldException(
                    "Unexpected value '%s' of type '%s' yielded from o-routine '%s'.  O-routines can only yield Callback and Return types."
                    % (from_gen, type(from_gen), g))
                return _monocle_chain(e, g, callback)

        if not hasattr(from_gen, 'result'):

            def gotResult(r):
                _monocle_chain(r, g, callback)

            from_gen.add(gotResult)
            return callback
Ejemplo n.º 20
0
Archivo: main.py Proyecto: duy/dispersy
def main():
    def start():
        # start Dispersy
        dispersy = Dispersy.get_instance(callback, unicode(opt.statedir))

        if opt.swiftproc:
            # start swift
            from Tribler.Core.Swift.SwiftProcessMgr import SwiftProcessMgr
            sesslock = threading.Lock()
            spm = SwiftProcessMgr(opt.swiftpath, opt.swiftcmdlistenport, opt.swiftdlsperproc, sesslock)
            swift_process = spm.get_or_create_sp(opt.statedir)
            dispersy.endpoint = TunnelEndpoint(swift_process, dispersy)
            swift_process.add_download(dispersy.endpoint)

        else:
            def exception(exception, fatal):
                if fatal:
                    dispersy.endpoint.stop()
            dispersy.endpoint = StandaloneEndpoint(dispersy, opt.port, opt.ip)
            dispersy.endpoint.start()
            dispersy.callback.attach_exception_handler(exception)

        # load the script parser
        if opt.script:
            from script import Script
            script = Script.get_instance(callback)

            script_kargs = {}
            if opt.script_args:
                for arg in opt.script_args.split(','):
                    key, value = arg.split('=')
                    script_kargs[key] = value

            if opt.enable_dispersy_script:
                from script import DispersyClassificationScript, DispersyTimelineScript, DispersyDestroyCommunityScript, DispersyBatchScript, DispersySyncScript, DispersyIdenticalPayloadScript, DispersySubjectiveSetScript, DispersySignatureScript, DispersyMemberTagScript, DispersyMissingMessageScript, DispersyUndoScript, DispersyCryptoScript, DispersyDynamicSettings, DispersyBootstrapServers, DispersyBootstrapServersStresstest
                script.add("dispersy-batch", DispersyBatchScript)
                script.add("dispersy-classification", DispersyClassificationScript)
                script.add("dispersy-crypto", DispersyCryptoScript)
                script.add("dispersy-destroy-community", DispersyDestroyCommunityScript)
                script.add("dispersy-dynamic-settings", DispersyDynamicSettings)
                script.add("dispersy-identical-payload", DispersyIdenticalPayloadScript)
                script.add("dispersy-member-tag", DispersyMemberTagScript)
                script.add("dispersy-missing-message", DispersyMissingMessageScript)
                script.add("dispersy-signature", DispersySignatureScript)
                script.add("dispersy-subjective-set", DispersySubjectiveSetScript)
                script.add("dispersy-sync", DispersySyncScript)
                script.add("dispersy-timeline", DispersyTimelineScript)
                script.add("dispersy-undo", DispersyUndoScript)
                script.add("dispersy-bootstrap-servers", DispersyBootstrapServers)
                script.add("dispersy-bootstrap-servers-stresstest", DispersyBootstrapServersStresstest)

                from callbackscript import DispersyCallbackScript
                script.add("dispersy-callback", DispersyCallbackScript)

            if opt.enable_allchannel_script:
                # from Tribler.Community.allchannel.script import AllChannelScript
                # script.add("allchannel", AllChannelScript, include_with_all=False)

                from Tribler.community.allchannel.script import AllChannelScenarioScript
                script.add("allchannel-scenario", AllChannelScenarioScript, script_kargs, include_with_all=False)

            if opt.enable_walktest_script:
                from Tribler.community.walktest.script import ScenarioScript
                script.add("walktest-scenario", ScenarioScript, script_kargs, include_with_all=False)

            if opt.enable_ycsb_script:
                from Tribler.community.ycsb.script import YCSBScript
                script.add("ycsb-scenario", YCSBScript, script_kargs, include_with_all=False)

            if opt.enable_demers_script:
                from Tribler.community.demerstest.script import DemersScript
                script.add("demers-scenario", DemersScript, script_kargs, include_with_all=False)

            if opt.enable_udp_script:
                from script import DispersyUDPScript
                script.add("udp-scenario", DispersyUDPScript, script_kargs, include_with_all=False)

            if opt.enable_effort_script:
                from Tribler.community.effort.script import ScenarioScript
                script.add("effort-scenario", ScenarioScript, script_kargs, include_with_all=False)

            # if opt.enable_barter_script:
            #     from Tribler.Community.barter.script import BarterScript, BarterScenarioScript
            #     script.add("barter", BarterScript)
            #     script.add("barter-scenario", BarterScenarioScript, script_kargs, include_with_all=False)

            # # bump the rawserver, or it will delay everything... since it sucks.
            # def bump():
            #     pass
            # rawserver.add_task(bump)

            script.load(opt.script)

    command_line_parser = optparse.OptionParser()
    command_line_parser.add_option("--statedir", action="store", type="string", help="Use an alternate statedir", default=u".")
    command_line_parser.add_option("--ip", action="store", type="string", default="0.0.0.0", help="Dispersy uses this ip")
    command_line_parser.add_option("--port", action="store", type="int", help="Dispersy uses this UDL port", default=12345)
    command_line_parser.add_option("--timeout-check-interval", action="store", type="float", default=1.0)
    command_line_parser.add_option("--timeout", action="store", type="float", default=300.0)
    command_line_parser.add_option("--enable-allchannel-script", action="store_true", help="Include allchannel scripts", default=False)
    command_line_parser.add_option("--enable-barter-script", action="store_true", help="Include barter scripts", default=False)
    command_line_parser.add_option("--enable-dispersy-script", action="store_true", help="Include dispersy scripts", default=False)
    command_line_parser.add_option("--enable-walktest-script", action="store_true", help="Include walktest scripts", default=False)
    command_line_parser.add_option("--enable-ycsb-script", action="store_true", help="Include ycsb scripts", default=False)
    command_line_parser.add_option("--enable-demers-script", action="store_true", help="Include demers scripts", default=False)
    command_line_parser.add_option("--enable-udp-script", action="store_true", help="Include udp-testing scripts", default=False)
    command_line_parser.add_option("--enable-effort-script", action="store_true", help="Include effort scripts", default=False)
    command_line_parser.add_option("--script", action="store", type="string", help="Runs the Script python file with <SCRIPT> as an argument")
    command_line_parser.add_option("--script-args", action="store", type="string", help="Executes --script with these arguments.  Example 'startingtimestamp=1292333014,endingtimestamp=12923340000'")
    # swift
    command_line_parser.add_option("--swiftproc", action="store_true", help="Use swift to tunnel all traffic", default=False)
    command_line_parser.add_option("--swiftpath", action="store", type="string", default="./swift")
    command_line_parser.add_option("--swiftcmdlistenport", action="store", type="int", default=7760+481)
    command_line_parser.add_option("--swiftdlsperproc", action="store", type="int", default=1000)

    # parse command-line arguments
    opt, args = command_line_parser.parse_args()
    print "Press Ctrl-C to stop Dispersy"

    # start threads
    callback = Callback()
    callback.register(start)
    callback.loop()

    if callback.exception:
        global exit_exception
        exit_exception = callback.exception
Ejemplo n.º 21
0
app.add_url_rule('/streets/<query>',
                view_func=Streets.as_view('street'),
                methods=["GET"])
app.add_url_rule('/<page>/',
                 view_func=main_view_func,
                 methods=["GET"])
app.add_url_rule('/login/',
                 view_func=Login.as_view('login'),
                 methods=["GET", "POST"])
app.add_url_rule('/remote/',
                 view_func=Remote.as_view('remote'),
                 methods=['GET', 'POST'])
app.add_url_rule('/music/',
                 view_func=Music.as_view('music'),
                 methods=['GET'])
app.add_url_rule('/callback/',
                view_func=Callback.as_view('callback'),
                methods=['GET'])

@app.errorhandler(404)
def page_not_found(error):
	return flask.render_template('404.html'), 404

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))

    if port == 5000:
        app.debug = True

    app.run(host='0.0.0.0', port=port)
Ejemplo n.º 22
0
def wait(name):
    waits.setdefault(name, Callback())
    r = yield waits[name]
    yield Return(r)
Ejemplo n.º 23
0
def gui():
    '''
	GUI for creating scriptJobs
	'''
    # Get XML Data
    parseXML()
    global mainCol, tsl, sfDisc, tslText, radioCol

    if (cmds.window(win, q=True, ex=True)):
        cmds.deleteUI(win)
    if (cmds.windowPref(win, ex=True)):
        cmds.windowPref(win, r=True)

    cmds.window(win,
                title="Script Job Creator",
                mb=True,
                w=winWidth2,
                h=winHeight)
    cmds.menu(label="System")
    cmds.menuItem(label="Script Job Monitor", c=Callback(mecScriptJob.gui))
    mainCol = cmds.columnLayout(rs=4, co=["both", 5])
    cmds.rowColumnLayout(nc=2, cw=[[1, winWidth * .4], [2, winWidth * .6]])
    tslText = cmds.text(label="Event Types", w=200, al="center")
    cmds.text(label="Type Desciption", w=300, al="center")
    tsl = cmds.textScrollList(w=200,
                              h=150,
                              append="Select Mode",
                              en=False,
                              sc=Callback(loadDisc))
    sfDisc = cmds.scrollField(w=300,
                              h=150,
                              editable=False,
                              wordWrap=True,
                              text='Select event for discription.')
    cmds.setParent(mainCol)

    # Create a radioButton collection
    cmds.frameLayout(label="Script Job Type",
                     labelAlign="center",
                     w=winWidth,
                     labelIndent=winWidth / 2 - 50)
    frmType = cmds.formLayout(w=winWidth, h=25)

    # cmds.text( l="Choose Script Job Type", w=winWidth, al="center")
    rlType = cmds.rowColumnLayout(nc=4,
                                  w=500,
                                  cw=[[1, winWidth * .25 - 15],
                                      [2, winWidth * .25],
                                      [3, winWidth * .25 - 10],
                                      [4, winWidth * .25]],
                                  co=[1, "left", 5])
    radioCol = cmds.radioCollection()
    cmds.radioButton("mecSJEvent",
                     label='event',
                     cl=radioCol,
                     sl=True,
                     onCommand=Callback(loadTSL))
    cmds.radioButton("mecSJAttr",
                     label='attributes',
                     cl=radioCol,
                     onCommand=Callback(loadTSL))
    cmds.radioMenuItemCollection("mecSJAttrCol")
    cmds.popupMenu()
    cmds.menuItem("mecAttrCh",
                  label="attributeChange",
                  cl="mecSJAttrCol",
                  rb=True)
    cmds.menuItem("mecAttrDel",
                  label="attributeDeleted",
                  rb=False,
                  cl="mecSJAttrCol")
    cmds.menuItem("mecAttrAdd",
                  label="attributeAdded",
                  rb=False,
                  cl="mecSJAttrCol")
    cmds.setParent("..", m=True)

    cmds.radioButton("mecSJCond",
                     label='condition',
                     cl=radioCol,
                     onCommand=Callback(loadTSL))
    cmds.radioMenuItemCollection("mecSJConCol")
    cmds.popupMenu()
    cmds.menuItem("mecCondTrue",
                  label="conditionTrue",
                  rb=True,
                  cl="mecSJConCol")
    cmds.menuItem("mecCondFalse",
                  label="conditionFalse",
                  rb=False,
                  cl="mecSJConCol")
    cmds.menuItem("mecCondChange",
                  label="conditionChange",
                  rb=False,
                  cl="mecSJConCol")
    cmds.setParent("..", m=True)

    cmds.radioButton("mecSJNode",
                     label='nodeNameChanged',
                     cl=radioCol,
                     onCommand=Callback(loadTSL))

    cmds.setParent(frmType)
    rlType2 = cmds.rowColumnLayout(nc=3,
                                   w=500,
                                   cw=[[1,
                                        winWidth / 3], [2, winWidth / 3 - 20],
                                       [3, winWidth / 3]],
                                   co=[1, "right", 10])

    cmds.radioButton("mecSJConn",
                     label='connectionChange',
                     cl=radioCol,
                     onCommand=Callback(loadTSL))
    cmds.radioButton("mecSJUI",
                     label='uiDeleted',
                     cl=radioCol,
                     onCommand=Callback(loadTSL))
    cmds.radioButton("mecSJTime",
                     label='timeChange',
                     cl=radioCol,
                     onCommand=Callback(loadTSL))

    cmds.setParent(frmType)

    row1 = cmds.rowColumnLayout(nc=2,
                                cw=[[1, winWidth / 2 + 10],
                                    [2, winWidth / 2 - 20]])
    # This text and ann will change depending when type of script job is chosen.
    # In the case time this text and field will not be used.
    # Certain scriptJob types will automaticly change the content of this field
    cmds.textFieldGrp("mecSJConLabel",
                      label='Attribute',
                      text='',
                      w=winWidth / 2,
                      cw=[[1, 90], [2, 200]],
                      ann="")

    # This field will recieve which procedure will be exectued when the scriptJob is triggered.
    cmds.textFieldGrp("mecSJProcLabel",
                      label='Procedure: ',
                      text='',
                      w=winWidth / 2,
                      cw=[1, 75],
                      ann="What function will the scriptJob call?")
    cmds.formLayout(frmType,
                    edit=True,
                    attachForm=[[rlType, "left", 0], [rlType2, "left", 40],
                                [row1, "left", 0], [rlType, "top", 5]],
                    attachControl=[[rlType2, "top", 5, rlType],
                                   [row1, "top", 5, rlType2]])
    cmds.formLayout(frmType, e=1, af=[row1, "bottom", 5])
    cmds.setParent(mainCol)

    frmMid = cmds.formLayout()
    jsLayout = jobSecurity(frmMid)
    jLayout = jobLifeSpan(frmMid)

    cmds.formLayout(frmMid,
                    e=1,
                    af=[[jsLayout, "top", 5], [jLayout, "top", 5]],
                    ac=[jLayout, "left", 10, jsLayout])

    cmds.setParent(mainCol)

    # Script Job UI Connection
    cmds.frameLayout(label="Script Job UI Connection",
                     labelAlign="center",
                     w=winWidth,
                     labelIndent=winWidth / 2 - 60)
    frm3 = cmds.formLayout(w=winWidth, h=25)
    row3 = cmds.rowColumnLayout(nc=3, cw=[[1, 60], [2, 150], [3, 100]])
    cmds.checkBox(
        "mecSJParent",
        label="parent",
        w=100,
        v=0,
        ann=
        "Attaches this job to a piece of maya UI. When the UI is destroyed, the job will be killed along with it."
    )
    cmds.textField("mecSJParentText", text="UINameHere", w=100)
    cmds.checkBox(
        "mecSJReplace",
        label="replacePrevious",
        v=0,
        ann=
        "This flag can only be used with the -parent flag. Before the new scriptJob is created, any existing scriptJobs that have the same parent are first deleted."
    )
    cmds.setParent("..")
    cmds.formLayout(frm3,
                    edit=True,
                    attachForm=[[row3, "left", winWidth / 2 - 140],
                                [row3, "top", 5]])
    cmds.setParent(mainCol)

    # Create the Script Job
    cmds.button(label="Generate Script Job",
                w=winWidth,
                c=Callback(sjCreateSJ))
    cmds.textField("mecSJPreview",
                   w=winWidth,
                   text="Preview Area",
                   editable=False)
    cmds.button(
        label="Execute Script Job! Warning this will activate the scriptJob!",
        w=winWidth,
        c=Callback(exeScriptJ))
    # Preview Area (Extra)
    # This area will show what the script job is looking like.

    # Get radioButton event setup first
    # Attr
    # Condition

    # Add elements into textScrollList
    #appendElements( tsl )
    loadTSL()
    cmds.showWindow(win)
Ejemplo n.º 24
0
import tensorflow as tf
from draw import draw_results
from callback import Callback

callbacks = Callback()

fashion_mnist = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images,
                               test_labels) = fashion_mnist.load_data()

clothes = ["T-shirt/top",
           "Trouser",
           "Pullover",
           "Dress",
           "Coat",
           "Sandal",
           "Shirt",
           "Sneaker",
           "Bag",
           "Ankel boot"]

normalize_number = 255.0
train_images, test_images = train_images / \
    normalize_number, test_images / normalize_number

model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])
Ejemplo n.º 25
0
 def callback(self):
     self.sensor_state_manager.handle_callback(Callback(self.sensor_key, self.measured_value))
Ejemplo n.º 26
0
    def gui(self):
        '''
		Generates the interface for the AttrGUISingle object.
		'''

        btnWidth = 30
        btnSep = 2
        # textWidth = 70
        # fieldWidth
        # if( cmds.about( os=True ) == "mac" ):

        self.mainLayout = cmds.rowColumnLayout(parent=self.parent,
                                               nc=7,
                                               h=20,
                                               rat=[[1, "both", btnSep],
                                                    [2, "both", btnSep],
                                                    [3, "both", btnSep],
                                                    [4, "both", btnSep],
                                                    [5, "both", btnSep],
                                                    [6, "both", btnSep],
                                                    [7, "both", btnSep]],
                                               cw=[[1, 100], [2, 70], [3, 125],
                                                   [4,
                                                    btnWidth], [5, btnWidth],
                                                   [6, btnWidth],
                                                   [7, btnWidth]])
        cmds.text(label=self.text, w=70, al="center")
        self.fieldGui = cmds.floatField(w=100, pre=2)
        pop = cmds.popupMenu(parent=self.fieldGui)
        cmds.menuItem(parent=pop,
                      label="0 - 1",
                      c=Callback(self.setMinMax, 0, 1))
        cmds.menuItem(parent=pop,
                      label="0 - 10",
                      c=Callback(self.setMinMax, 0, 10))
        cmds.menuItem(parent=pop,
                      label="-10 - 10",
                      c=Callback(self.setMinMax, -10, 10))
        cmds.menuItem(parent=pop, label="Set Min/Max")
        cmds.menuItem(divider=1)
        cmds.menuItem(label="Step 1", c=Callback(self.setStep, 1))
        cmds.menuItem(label="Step .1", c=Callback(self.setStep, .1))
        cmds.menuItem(label="Step .01", c=Callback(self.setStep, .01))

        self.sliderGui = cmds.floatSlider(w=100, h=20)

        cmds.popupMenu(parent=self.sliderGui)
        cmds.menuItem(label="0 - 1", c=Callback(self.setMinMax, 0, 1))
        cmds.menuItem(label="0 - 10", c=Callback(self.setMinMax, 0, 10))
        cmds.menuItem(label="-10 - 10", c=Callback(self.setMinMax, -10, 10))
        cmds.menuItem(label="Set Min/Max")
        cmds.menuItem(divider=1)
        cmds.menuItem(label="Step 1", c=Callback(self.setStep, 1))
        cmds.menuItem(label="Step .1", c=Callback(self.setStep, .1))
        cmds.menuItem(label="Step .01", c=Callback(self.setStep, .01))

        if (self.attrs.min != None):
            cmds.floatField(self.fieldGui, e=1, min=self.attrs.min)
            cmds.floatSlider(self.sliderGui, e=1, min=self.attrs.min)
        if (self.attrs.max != None):
            cmds.floatField(self.fieldGui, e=1, max=self.attrs.max)
            cmds.floatSlider(self.sliderGui, e=1, max=self.attrs.max)

        cmds.connectControl(self.fieldGui, self.attrNames)
        cmds.connectControl(self.sliderGui, self.attrNames)

        cmds.symbolButton(image='MENUICONKEYS.XPM',
                          h=20,
                          ann="Keyframe",
                          command=Callback(self.key))
        cmds.symbolButton(image='REDRAWPAINTEFFECTS.XPM',
                          h=20,
                          ann="Reset to Default",
                          command=Callback(self.reset))
        self.symGUI = cmds.symbolCheckBox(image='ONRADIOBTNICON.XPM',
                                          h=20,
                                          oni='ONRADIOBTNICON.XPM',
                                          ofi='OFFRADIOBTNICON.XPM',
                                          ann="Set Offset",
                                          onc=Callback(self.setOffset))
        self.resOffName = cmds.symbolButton(image='AUTOLOAD.XPM',
                                            h=20,
                                            ann="Reset Offset",
                                            command=Callback(self.resetOffset))

        cmds.setParent(self.parent)
Ejemplo n.º 27
0
 def callback(self):
     return Callback(self)
Ejemplo n.º 28
0
 def callback(self):
     for observer in self.observers:
         observer.handle_callback(
             Callback(self.sensor_key, self.measured_value)
         )  # callback sends measured value to observers, and makes observers handle the sent callback
Ejemplo n.º 29
0
class Controller(bt.DefaultDelegate):
    """

    """
    def __init__(self, log):

        self.device = None
        self.stream = None
        self.log = log
        self.timer = 0
        self.stop_flag = threading.Event()
        """ Callbacks """
        # Called when bluetooth is connected
        self.connected = Callback()

        # Called when bluetooth is disconnected
        self.disconnected = Callback()

        # Called if the connection to bluetooth fails
        self.connection_failed = Callback()

        # Called if the target device can't be found
        self.device_not_found = Callback()

        # Called if there's already a connection with the target
        self.already_connected = Callback()

        # Called when a packet is received from the device
        self.packet_received = Callback()

        # Called to send a packet
        self.send_packet = Callback()

        # Called when timeout
        self.timeout = Callback()

        self.add_default_callbacks()

    def add_default_callbacks(self):
        self.connected.add_callback(
            lambda MAC: self.log.info('Connected to Bluetooth MAC %s' % MAC))
        self.connection_failed.add_callback(
            lambda: self.log.info('Connection failed'))
        self.device_not_found.add_callback(
            lambda: self.log.info('Device not found'))
        self.already_connected.add_callback(
            lambda: self.log.info('Already connected to %s' % self.device))

    """ Scans nearby devices and connects to the target if not 
        already connected. Also sets the usart handler to
        send and receive messages (like a socket stream)         """

    def connect(self):

        if self.device is None:

            # Scans for nearby devices
            scan = bt.Scanner()
            scan.scan(SCAN_TIMEOUT)

            for dev in scan.getDevices():

                # Check is target MAC is found
                if dev.addr == TARGET_MAC:

                    if dev.connectable:

                        # Make a connection to the target and set callbacks to bluepy API
                        # (This is done by inheriting DefaultDelegate class)
                        self.device = bt.Peripheral(dev)
                        self.device.withDelegate(self)

                        # Sets the correct handler for the usart (allows stream-like API)
                        for char in self.device.getCharacteristics():
                            if char.getHandle() == USART_HANDLER:
                                self.stream = char

                        # Let the rest of the program know that we're connected!
                        self.connected.call(TARGET_MAC)

                        # Start infinite-communication-loop
                        self.stop_flag.clear()
                        self.run()

                        # Should not be reached
                        return

                    else:
                        self.connection_failed.call()
                        return

            self.device_not_found.call()

        else:
            self.already_connected.call()

    def send(self, packet):
        if self.stream:
            self.stream.write(packet)

    def disconnect(self):
        if self.device:
            self.device.disconnect()
            self.device = None
            self.usart = None
            self.disconnected.call()

    def __enter__(self):
        threading.Thread(target=self.connect).start()
        return self

    def __exit__(self, *args):
        self.stop_flag.set()
        self.disconnect()
        self.send('Exiting!')

    def run(self):

        try:
            # Make sure that we're still connected
            if self.device:

                # Enter infinite-loop, running as long as programs wants us to
                while not self.stop_flag.is_set():

                    try:
                        self.device.waitForNotifications(1)
                        if time.time() - self.timer >= PACKET_TIMEOUT:
                            self.timeout.call()
                            self.timer = time.time()

                    except Exception as e:
                        self.disconnected.call()

            else:
                self.disconnected.call()

        finally:
            # We're done, let's disconnect
            self.disconnect()

    # Callback from connected Peripheral
    # c_handle is only needed if multiple devices are used
    def handleNotification(self, c_handle, data):
        try:
            if data:
                data = struct.unpack_from(RCV_PKT_FORMAT, data)
                self.packet_received.call(data)
                self.send_packet.call()
        except Exception as e:
            self.log.info('Exception as BT: %s' % e)

        finally:
            self.timer = time.time()
Ejemplo n.º 30
0
    def __init__(self, log):

        self.device = None
        self.stream = None
        self.log = log
        self.timer = 0
        self.stop_flag = threading.Event()
        """ Callbacks """
        # Called when bluetooth is connected
        self.connected = Callback()

        # Called when bluetooth is disconnected
        self.disconnected = Callback()

        # Called if the connection to bluetooth fails
        self.connection_failed = Callback()

        # Called if the target device can't be found
        self.device_not_found = Callback()

        # Called if there's already a connection with the target
        self.already_connected = Callback()

        # Called when a packet is received from the device
        self.packet_received = Callback()

        # Called to send a packet
        self.send_packet = Callback()

        # Called when timeout
        self.timeout = Callback()

        self.add_default_callbacks()
Ejemplo n.º 31
0
    def _manipWidgit(self, curParent):
        '''
		This gui widgit contains the buttons to add & remove attributes
		Overall adjusts for all the attribute contained inside.
		'''
        frame = cmds.frameLayout(parent=curParent,
                                 labelVisible=False,
                                 marginWidth=5,
                                 marginHeight=3)
        frm = cmds.formLayout(parent=frame, w=415)

        path = os.path.split(__file__)[0]
        fullPath = lambda x: os.path.join(path, "icons", x)

        btn1 = cmds.symbolButton(image=fullPath('plus_16b.xpm'),
                                 h=20,
                                 command=Callback(
                                     self.addAttrGUI))  # self._attrGUI )

        btn2 = cmds.symbolButton(
            image=fullPath('delete_16b.xpm'),
            h=20,
            command=Callback(self.removeAll))  #command=self._removeAttrs )

        btn2a = cmds.symbolButton(image=fullPath('save_16.xpm'),
                                  h=20,
                                  command=Callback(
                                      self.addAttrGUI))  # self._attrGUI )
        btn2b = cmds.symbolButton(image=fullPath('folder_16b.xpm'),
                                  h=20,
                                  command=Callback(
                                      self.addAttrGUI))  # self._attrGUI )

        cmds.formLayout(frm, e=1, af=[[btn1, "left", 5], [btn1, "top", 0]])
        cmds.formLayout(frm,
                        e=1,
                        ac=[btn2, "left", 5, btn1],
                        af=[btn2, "top", 0])
        cmds.formLayout(frm,
                        e=1,
                        ac=[btn2a, "left", 5, btn2],
                        af=[btn2a, "top", 0])
        cmds.formLayout(frm,
                        e=1,
                        ac=[btn2b, "left", 5, btn2a],
                        af=[btn2b, "top", 0])
        '''		                    
		btn1 = cmds.button( label="Add Attr", w=100,
		                    command=Callback(self.addAttrGUI)) # self._attrGUI )
		
		btn2 = cmds.button( label="Remove Attrs", w=100,
		                    command=Callback(self.removeAll ))#command=self._removeAttrs )
		'''

        btn3 = cmds.symbolButton(image='MENUICONKEYS.XPM',
                                 h=20,
                                 ann="Keyframe",
                                 command=Callback(self.keyAll))
        '''		
		btn3 = cmds.button( label="Keyframe",
						    command=Callback(self.keyAll))
		'''
        btn4 = cmds.symbolButton(image='REDRAWPAINTEFFECTS.XPM',
                                 h=20,
                                 ann="Reset to Default",
                                 command=Callback(self.resetAll))

        btn5 = cmds.symbolCheckBox(image='ONRADIOBTNICON.XPM',
                                   h=20,
                                   oni='ONRADIOBTNICON.XPM',
                                   ofi='OFFRADIOBTNICON.XPM',
                                   ann="Set Offset",
                                   onc=Callback(self.setOffset))

        btn6 = cmds.symbolButton(image='AUTOLOAD.XPM',
                                 h=20,
                                 ann="Reset Offset",
                                 command=Callback(self.resetOffset))
        '''
		cmds.formLayout( frm, e=1, ac=[btn3, "left", 5, btn2], af=[btn3, "top", 0])
		cmds.formLayout( frm, e=1, ac=[btn4, "left", 5, btn3], af=[btn4, "top", 0])
		cmds.formLayout( frm, e=1, ac=[btn5, "left", 5, btn4], af=[btn5, "top", 0])
		cmds.formLayout( frm, e=1, ac=[btn6, "left", 5, btn5], af=[btn6, "top", 0])
		'''
        cmds.formLayout(frm, e=1, af=[[btn6, "top", 0], [btn6, "right", 5]])
        cmds.formLayout(frm,
                        e=1,
                        ac=[btn5, "right", 5, btn6],
                        af=[btn5, "top", 0])
        cmds.formLayout(frm,
                        e=1,
                        ac=[btn4, "right", 5, btn5],
                        af=[btn4, "top", 0])
        cmds.formLayout(frm,
                        e=1,
                        ac=[btn3, "right", 5, btn4],
                        af=[btn3, "top", 0])

        return frame
Ejemplo n.º 32
0
Archivo: main.py Proyecto: L3nn0x/mud
from mysql import Mysql
from callback import Callback
import time

def loadBroadcasts(mysql, callbacks, worker):
    for i in mysql.getEntry("select time_interval, message from broadcast"):
        if not i:
            return
        callbacks.register(i["time_interval"], worker.broadcast, i["message"])

server = TelnetServer("0.0.0.0", 23)
mud = Mud("data.xml")
bus = BusEvent()
mysql = Mysql('localhost', 'mud', 'root', 'vive-moi')
if not mysql.ok:
    print("Error while connecting to mysql")
    exit()
if not mud.begin:
    print("Error while loading data for mud")
    exit()
worker = Worker(mud, server, bus, mysql)
callbacks = Callback()
loadBroadcasts(mysql, callbacks, worker)

while server.update():
    worker.connections()
    worker.disconnections()
    worker.messages()
    callbacks.run()
    time.sleep(0.2)
Ejemplo n.º 33
0
 def _use_memory(self):
     ''' _use_memory()
         pass interpreter as an argument to every callback in grammar
     '''
     for key, callback in self.grammar.iteritems():
         self.grammar[key] = Callback(callback, self)