예제 #1
0
def main():
    parse_options()
    http_server = tornado.httpserver.HTTPServer(Application(),xheaders=True)
    print "Server started on port "+str(options.port)
    http_server.bind(int(options.port), "0.0.0.0")# listen local only "127.0.0.1"
    http_server.start(1)
    tornado.ioloop.IOLoop.instance().start()
예제 #2
0
    def generate(self,
                 opts,
                 outfile=None,
                 format='svg',
                 preview=None,
                 stylesheet=None):
        """
        Generates a the map and renders it using the specified output format.
        """
        if preview is None:
            preview = outfile is None

        # Create a deep copy of the options dictionary so our changes will not be
        # visible to the calling application.
        opts = deepcopy(opts)

        # Parse the options dictionary. See options.py for more details.
        parse_options(opts)

        # Create the map instance. It will do all the hard work for us, so you
        # definitely should check out [map.py](map.html) for all the fun stuff happending
        # there..
        _map = Map(opts, self.layerCache, format=format)

        # Check if the format is handled by a renderer.
        format = format.lower()
        if format in _known_renderer:
            # Create a stylesheet
            style = MapStyle(stylesheet)
            # Create a renderer instance and render the map.
            renderer = _known_renderer[format](_map)
            renderer.render(style, opts['export']['prettyprint'])

            if preview:
                if 'KARTOGRAPH_PREVIEW' in os.environ:
                    command = os.environ['KARTOGRAPH_PREVIEW']
                else:
                    commands = dict(win32='start',
                                    win64='start',
                                    darwin='open',
                                    linux2='xdg-open')
                    import sys
                    if sys.platform in commands:
                        command = commands[sys.platform]
                    else:
                        sys.stderr.write(
                            'don\'t know how to preview SVGs on your system. Try setting the KARTOGRAPH_PREVIEW environment variable.'
                        )
                        print renderer
                        return
                renderer.preview(command)
            # Write the map to a file or return the renderer instance.
            if outfile is None:
                return renderer
            elif outfile == '-':
                print renderer
            else:
                renderer.write(outfile)
        else:
            raise KartographError('unknown format: %s' % format)
예제 #3
0
	def generate(self, opts, output=None):
		"""
		new generic render api, will replace all render_... methods
		"""
		import options
		options.parse_options(opts)

		self.prepare_layers(opts)
		
		print opts		
예제 #4
0
    def generate(self, opts, outfile=None, format="svg", preview=None, stylesheet=None):
        """
        Generates a the map and renders it using the specified output format.
        """
        if preview is None:
            preview = outfile is None

        # Create a deep copy of the options dictionary so our changes will not be
        # visible to the calling application.
        opts = deepcopy(opts)

        # Parse the options dictionary. See options.py for more details.
        parse_options(opts)

        # Create the map instance. It will do all the hard work for us, so you
        # definitely should check out [map.py](map.html) for all the fun stuff happending
        # there..
        _map = Map(opts, self.layerCache, format=format)

        # Check if the format is handled by a renderer.
        format = format.lower()
        if format in _known_renderer:
            # Create a stylesheet
            style = MapStyle(stylesheet)
            # Create a renderer instance and render the map.
            renderer = _known_renderer[format](_map)
            renderer.render(style, opts["export"]["prettyprint"])

            if preview:
                if "KARTOGRAPH_PREVIEW" in os.environ:
                    command = os.environ["KARTOGRAPH_PREVIEW"]
                else:
                    commands = dict(win32="start", win64="start", darwin="open", linux2="xdg-open")
                    import sys

                    if sys.platform in commands:
                        command = commands[sys.platform]
                    else:
                        sys.stderr.write(
                            "don't know how to preview SVGs on your system. Try setting the KARTOGRAPH_PREVIEW environment variable."
                        )
                        print renderer
                        return
                renderer.preview(command)
            # Write the map to a file or return the renderer instance.
            if outfile is None:
                return renderer
            elif outfile == "-":
                print renderer
            else:
                renderer.write(outfile)
        else:
            raise KartographError("unknown format: %s" % format)
예제 #5
0
    def generate_kml(self, opts, outfile=None):
        """
        generates KML file
        """
        parse_options(opts)
        self.prepare_layers(opts)

        # proj = self.get_projection(opts)
        # bounds_poly = self.get_bounds(opts,proj)
        # bbox = bounds_poly.bbox()

        proj = projections["ll"]()
        view = View()

        # view = self.get_view(opts, bbox)
        # w = view.width
        # h = view.height
        # view_poly = MultiPolygon([[(0,0),(0,h),(w,h),(w,0)]])
        # view_poly = bounds_poly.project_view(view)
        view_poly = None

        kml = self.init_kml_canvas()

        layers = []
        layerOpts = {}
        layerFeatures = {}

        # get features
        for layer in opts["layers"]:
            id = layer["id"]
            layerOpts[id] = layer
            layers.append(id)
            features = self.get_features(layer, proj, view, opts, view_poly)
            layerFeatures[id] = features

        self.simplify_layers(layers, layerFeatures, layerOpts)
        # self.crop_layers_to_view(layers, layerFeatures, view_poly)
        self.crop_layers(layers, layerOpts, layerFeatures)
        self.join_layers(layers, layerOpts, layerFeatures)
        self.substract_layers(layers, layerOpts, layerFeatures)
        self.store_layers_kml(layers, layerOpts, layerFeatures, kml, opts)

        if outfile is None:
            outfile = open("tmp.kml", "w")

        from lxml import etree

        outfile.write(etree.tostring(kml, pretty_print=True))
예제 #6
0
def run():
    # Print a banner message
    # print "Parboil parallel benchmark suite, version 0.2"
    # print
    
    # Global variable setup
    if not globals.root:
      globals.root = os.getcwd()

    python_path = (os.path.join(globals.root,'common','python') +
                   ":" +
                   os.environ.get('PYTHONPATH',""))

    bmks = parboilfile.Directory(os.path.join(globals.root,'benchmarks'), 
                     [], benchmark.benchmark_scanner())


    globals.benchdir = bmks

    globals.datadir =  parboilfile.Directory(
                         os.path.join(globals.root, 'datasets'), [], 
                         benchmark.dataset_repo_scanner())

    globals.benchmarks = benchmark.find_benchmarks()

    globals.program_env = {'PARBOIL_ROOT':globals.root,
                           'PYTHONPATH':python_path,
                           }

    # Parse options
    act = options.parse_options(sys.argv)

    # Perform the specified action
    if act:
        return act()
예제 #7
0
    def append(self, token):
        """ Appends a token to the line while keeping the integrity of
            the line, and checking if the logical line is complete.
        """
        # The token content does not include whitespace, so we need to pad it
        # adequately
        token_started_new_line = False
        if token.start_row > self.end_row:
            self.end_col = 0
            token_started_new_line = True
        self.string += (token.start_col - self.end_col) * " " + token.content
        self.end_row = token.end_row
        self.end_col = token.end_col
        self.last_token_type = token.type

        # Keep count of the open and closed brakets.
        if token.type == 'OP':
            if token.content in self.open_symbols:
                self.open_symbols[token.content] += 1
            elif token.content in self.closing_symbols:
                self.open_symbols[self.closing_symbols[token.content]] += -1
            self.brakets_balanced = ( self.open_symbols.values() == [0, 0, 0] ) 
        
        self.complete = ( self.brakets_balanced 
                          and ( token.type in ('NEWLINE', 'ENDMARKER')
                                or ( token_started_new_line
                                      and token.type == 'COMMENT' )
                              )
                        )
        if ( token.type == 'COMMENT' 
                    and token_started_new_line 
                    and token.content[:10] == "#pyreport " ):
            self.options.update(parse_options(self.string[10:].split(" "))[0])
예제 #8
0
파일: pyreport.py 프로젝트: svenk/pyreport
def commandline_call():
    """ Entry point of the program when called from the command line
    """
    options, args = parse_options(sys.argv[1:])
    
    if not len(args)==1:
        if len(args)==0:
            option_parser.print_help()
        else:
            print  >> sys.stderr, "1 argument: input file"
        sys.exit(1)

    import time
    t1 = time.time()
    if args[0] == "-":
        pyfile = sys.stdin
    else:
        pyfile = open(args[0],"r")

        # fix include path
        from os.path import dirname, abspath
        path_of_pyfile = dirname(abspath(args[0]))
        sys.path.insert(0, path_of_pyfile)
        print sys.path

    # Store the name of the input file for later use
    options.update({'infilename':args[0]})

    main(pyfile, overrides=options)
    # FIXME: wath about the options defined in the script: options.quiet
    if not 'quiet' in options:
        print >>sys.stderr, "Ran script in %.2fs" % (time.time() - t1)
예제 #9
0
    def append(self, token):
        """ Appends a token to the line while keeping the integrity of
            the line, and checking if the logical line is complete.
        """
        # The token content does not include whitespace, so we need to pad it
        # adequately
        token_started_new_line = False
        if token.start_row > self.end_row:
            self.end_col = 0
            token_started_new_line = True
        self.string += (token.start_col - self.end_col) * " " + token.content
        self.end_row = token.end_row
        self.end_col = token.end_col
        self.last_token_type = token.type

        # Keep count of the open and closed brakets.
        if token.type == 'OP':
            if token.content in self.open_symbols:
                self.open_symbols[token.content] += 1
            elif token.content in self.closing_symbols:
                self.open_symbols[self.closing_symbols[token.content]] += -1
            self.brakets_balanced = (self.open_symbols.values() == [0, 0, 0])

        self.complete = (
            self.brakets_balanced
            and (token.type in ('NEWLINE', 'ENDMARKER') or
                 (token_started_new_line and token.type == 'COMMENT')))
        if (token.type == 'COMMENT' and token_started_new_line
                and token.content[:10] == "#pyreport "):
            self.options.update(parse_options(self.string[10:].split(" "))[0])
예제 #10
0
def receive_message():
    print('Method: ' + str(request.method))
    if request.method == 'GET':
        """Before allowing people to message your bot, Facebook has implemented a verify token
        that confirms all requests that your bot receives came from Facebook."""
        token_sent = request.args.get("hub.verify_token")
        return verify_fb_token(token_sent)
    #if the request was not get, it must be POST and we can just proceed with sending a message back to user
    else:
        # get whatever message a user sent the bot
        output = request.get_json()
        for event in output['entry']:
            messaging = event['messaging']
            for message in messaging:
                msg = message.get('message')
                if msg:
                    #Facebook Messenger ID for user so we know where to send response back to
                    sender_id = message['sender']['id']
                    print('The sender id is: ')
                    print(sender_id)
                    print('The message received is: ')
                    print(msg)
                    msg_text = msg.get('text')
                    if msg_text:
                        if msg_text.startswith('#start-translate'):
                            # set a flag in the database
                            # response_sent_text = get_message()
                            options.update_options(sender_id,
                                                   options.default_opts)
                            response_sent_text = 'Starting translation. All audio attachments\
                                                    will now be converted from speech to text'

                            send_message(sender_id, response_sent_text)
                        elif msg_text.startswith('#options'):
                            opts = options.parse_options(msg_text)
                            options.update_options(sender_id, opts)
                            send_message(
                                sender_id, 'Translating FROM: %s, TO: %s' %
                                (opts['src'], opts['dest']))

                    #if user sends us a GIF, photo,video, or any other non-text item
                    attachments = msg.get('attachments')
                    if attachments:
                        attch = attachments[0]
                        attch_type = attch.get('type')
                        if attch_type == 'audio':
                            try:
                                opts = options.get_options(sender_id)
                            except Exception as e:
                                print(e)
                                opts = options.default_opts
                            url = attch['payload']['url']
                            src = opts['src']
                            dest = opts['dest']
                            response = a2t.convert_audio_from_url(url, src)
                            translator = Translator()
                            converted_response = \
                                translator.translate(response, dest=dest, src=src)
                            send_message(sender_id, converted_response.text)
    return "Message Processed"
예제 #11
0
def run():
    # Print a banner message
    print "Parboil parallel benchmark suite, version 0.2"
    print

    # Global variable setup
    if not globals.root:
        globals.root = os.getcwd()

    python_path = (os.path.join(globals.root, 'common', 'python') + ":" +
                   os.environ.get('PYTHONPATH', ""))

    bmks = parboilfile.Directory(os.path.join(globals.root, 'benchmarks'), [],
                                 benchmark.benchmark_scanner())

    globals.benchdir = bmks

    globals.datadir = parboilfile.Directory(
        os.path.join(globals.root, 'datasets'), [],
        benchmark.dataset_repo_scanner())

    globals.benchmarks = benchmark.find_benchmarks()

    globals.program_env = {
        'PARBOIL_ROOT': globals.root,
        'PYTHONPATH': python_path,
    }

    # Parse options
    act = options.parse_options(sys.argv)

    # Perform the specified action
    if act:
        return act()
예제 #12
0
def main():
    (options, args) = parse_options()

    bus = smbus.SMBus(1)
    display = VFDController(MCP23017(bus, 0x20))

    display.setDisplay(True, False, False)
    display.cls()
    display.set_color(COLOR_NONE)

    player = VFDMidiPlayer(root=options.dir, display=display)

    print "Loaded ", player.count, "files into database"

    if (options.writecatalog):
        player.write_catalog()
        print "catalog saved"
        return

    try:
        while True:
            player.poll()
            time.sleep(0.1)

    finally:
        player.shutdown()
        termios.tcsetattr(stdin_fd, termios.TCSAFLUSH, old_term)
예제 #13
0
def commandline_call():
    """ Entry point of the program when called from the command line
    """
    options, args = parse_options(sys.argv[1:])

    if not len(args) == 1:
        if len(args) == 0:
            option_parser.print_help()
        else:
            print >> sys.stderr, "1 argument: input file"
        sys.exit(1)

    import time
    t1 = time.time()
    if args[0] == "-":
        pyfile = sys.stdin
    else:
        pyfile = open(args[0], "r")

    # Store the name of the input file for later use
    options.update({'infilename': args[0]})

    main(pyfile, overrides=options)
    # FIXME: wath about the options defined in the script: options.quiet
    if not 'quiet' in options:
        print >> sys.stderr, "Ran script in %.2fs" % (time.time() - t1)
예제 #14
0
    def generate_kml(self, opts, outfile=None):
        """
        generates KML file
        """
        parse_options(opts)
        self.prepare_layers(opts)

        #proj = self.get_projection(opts)
        #bounds_poly = self.get_bounds(opts,proj)
        #bbox = bounds_poly.bbox()

        proj = projections['ll']()
        view = View()

        #view = self.get_view(opts, bbox)
        #w = view.width
        #h = view.height
        #view_poly = MultiPolygon([[(0,0),(0,h),(w,h),(w,0)]])
        # view_poly = bounds_poly.project_view(view)
        view_poly = None

        kml = self.init_kml_canvas()

        layers = []
        layerOpts = {}
        layerFeatures = {}

        # get features
        for layer in opts['layers']:
            id = layer['id']
            layerOpts[id] = layer
            layers.append(id)
            features = self.get_features(layer, proj, view, opts, view_poly)
            layerFeatures[id] = features

        self.simplify_layers(layers, layerFeatures, layerOpts)
        # self.crop_layers_to_view(layers, layerFeatures, view_poly)
        self.crop_layers(layers, layerOpts, layerFeatures)
        self.join_layers(layers, layerOpts, layerFeatures)
        self.substract_layers(layers, layerOpts, layerFeatures)
        self.store_layers_kml(layers, layerOpts, layerFeatures, kml, opts)

        if outfile is None:
            outfile = open('tmp.kml', 'w')

        from lxml import etree
        outfile.write(etree.tostring(kml, pretty_print=True))
예제 #15
0
    def generate(self, opts, outfile=None, preview=True):
        """
        generates svg map
        """
        parse_options(opts)
        self.prepare_layers(opts)

        proj = self.get_projection(opts)
        print proj
        bounds_poly = self.get_bounds(opts, proj)
        bbox = bounds_poly.bbox()

        view = self.get_view(opts, bbox)
        w = view.width
        h = view.height
        view_poly = MultiPolygon([[(0, 0), (0, h), (w, h), (w, 0)]])
        # view_poly = bounds_poly.project_view(view)

        svg = self.init_svg_canvas(opts, proj, view, bbox)

        layers = []
        layerOpts = {}
        layerFeatures = {}

        # get features
        for layer in opts['layers']:
            id = layer['id']
            layerOpts[id] = layer
            layers.append(id)
            features = self.get_features(layer, proj, view, opts, view_poly)
            layerFeatures[id] = features

        self.join_layers(layers, layerOpts, layerFeatures)
        self.simplify_layers(layers, layerFeatures, layerOpts)
        self.crop_layers_to_view(layers, layerFeatures, view_poly)
        self.crop_layers(layers, layerOpts, layerFeatures)
        self.substract_layers(layers, layerOpts, layerFeatures)
        self.store_layers_svg(layers, layerOpts, layerFeatures, svg, opts)

        if outfile is None:
            if preview:
                svg.preview()
            else:
                return svg.tostring()
        else:
            svg.save(outfile)
예제 #16
0
    def generate(self, opts, outfile=None, preview=True):
        """
        generates svg map
        """
        parse_options(opts)
        self._verbose = 'verbose' in opts and opts['verbose']
        self.prepare_layers(opts)

        proj = self.get_projection(opts)
        bounds_poly = self.get_bounds(opts, proj)
        bbox = bounds_poly.bbox()

        view = self.get_view(opts, bbox)
        w = view.width
        h = view.height
        view_poly = MultiPolygon([[(0, 0), (0, h), (w, h), (w, 0)]])
        # view_poly = bounds_poly.project_view(view)

        svg = self.init_svg_canvas(opts, proj, view, bbox)

        layers = []
        layerOpts = {}
        layerFeatures = {}

        # get features
        for layer in opts['layers']:
            id = layer['id']
            layerOpts[id] = layer
            layers.append(id)
            features = self.get_features(layer, proj, view, opts, view_poly)
            layerFeatures[id] = features

        self.join_layers(layers, layerOpts, layerFeatures)
        self.simplify_layers(layers, layerFeatures, layerOpts)
        self.crop_layers_to_view(layers, layerFeatures, view_poly)
        self.crop_layers(layers, layerOpts, layerFeatures)
        self.substract_layers(layers, layerOpts, layerFeatures)
        self.store_layers_svg(layers, layerOpts, layerFeatures, svg, opts)

        if outfile is None:
            if preview:
                svg.preview()
            else:
                return svg.tostring()
        else:
            svg.save(outfile)
def main():
    # Determine training options specified by user.  The full list of available options can be found in "options.py" file.
    FLAGS = parse_options()

    # Instantiate the agent and Mujoco environment.  The designer must assign values to the hyperparameters listed in the "design_agent_and_env2.py" file.
    agent, env = design_agent_and_env(FLAGS)

    # Begin training
    run_HAC(FLAGS, env, agent)
예제 #18
0
파일: app.py 프로젝트: uta1502/LinguBot
def receive_message():
    print('Method: ' + str(request.method))
    if request.method == 'GET':
        """Before allowing people to message your bot, Facebook has implemented a verify token
        that confirms all requests that your bot receives came from Facebook.""" 
        token_sent = request.args.get("hub.verify_token")
        return verify_fb_token(token_sent)
    #if the request was not get, it must be POST and we can just proceed with sending a message back to user
    else:
        # get whatever message a user sent the bot
        output = request.get_json()
        for event in output['entry']:
            messaging = event['messaging']
            for message in messaging:
                msg = message.get('message')
                if msg:
                    #Facebook Messenger ID for user so we know where to send response back to
                    sender_id = message['sender']['id']
                    print('The sender id is: ')
                    print(sender_id)
                    print('The message received is: ')
                    print(msg)
                    msg_text = msg.get('text')
                    if msg_text:
                        if msg_text.startswith('#start-translate'):
                            # set a flag in the database
                            # response_sent_text = get_message()
                            options.update_options(sender_id, options.default_opts)
                            response_sent_text = 'Starting translation. All audio attachments\
                                                    will now be converted from speech to text'
                            send_message(sender_id, response_sent_text)
                        elif msg_text.startswith('#options'):
                            opts = options.parse_options(msg_text)
                            options.update_options(sender_id, opts)
                            send_message(sender_id, 'Translating FROM: %s, TO: %s' % (opts['src'], opts['dest']))

                    #if user sends us a GIF, photo,video, or any other non-text item
                    attachments = msg.get('attachments')
                    if attachments:
                        attch = attachments[0]
                        attch_type = attch.get('type')
                        if attch_type == 'audio':
                            try:
                                opts = options.get_options(sender_id)
                            except Exception as e:
                                print(e)
                                opts = options.default_opts
                            url = attch['payload']['url']
                            src = opts['src']
                            dest = opts['dest']
                            response = a2t.convert_audio_from_url(url, src)
                            translator = Translator()
                            converted_response = \
                                translator.translate(response, dest=dest, src=src)
                            send_message(sender_id, converted_response.text)
    return "Message Processed"
예제 #19
0
def main():
    (options, args) = parse_options()

    player = ConsoleMidiPlayer(root = options.dir)

    print "Loaded ", player.count, "files into database"

    if (options.writecatalog):
        player.write_catalog()
        print "catalog saved"
        return

    print "n - next file"
    print "p - previous file"
    print "> - next sub-folder"
    print "< - previous sub-folder"
    print "] - next major-folder"
    print "[ - previous major-folder"
    print "q - quit"

    print ""

    stdin_fd = sys.stdin.fileno()
    new_term = termios.tcgetattr(stdin_fd)
    old_term = termios.tcgetattr(stdin_fd)
    new_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)
    termios.tcsetattr(stdin_fd, termios.TCSAFLUSH, new_term)

    try:
        while True:
            if player.idle:
                player.next_file()

            dr,dw,de = select.select([sys.stdin], [], [], 0.1)
            if dr != []:
                ch = sys.stdin.read(1)

                #ch = getchar()
                if (ch == "n"):
                    player.next_file()
                elif (ch == "p"):
                    player.prev_file()
                elif (ch == ">"):
                    player.next_folder()
                elif (ch == "<"):
                    player.prev_folder()
                elif (ch == "]"):
                    player.next_major()
                elif (ch == "["):
                    player.prev_major()
                elif (ch == "q"):
                    break
    finally:
        player.shutdown()
        termios.tcsetattr(stdin_fd, termios.TCSAFLUSH, old_term)
예제 #20
0
def main(argv=None):
    global parser, settings
    parser, settings = parse_options(argv)

    cpu_util = CpuUtil(load_limit=int(settings.cpu_load_limit))
    cpu_util.load_limit = int(settings.cpu_load_limit)
    cpu_util.daemon = True
    cpu_util.start()

    Sender.host = settings.rabbit_host
    Sender.port = int(settings.rabbit_port)
    Sender.credentials = [settings.rabbit_login, settings.rabbit_psw]

    app.run(host='0.0.0.0', threaded=True)
예제 #21
0
def run():
    # Print a banner message
    print "Parboil parallel benchmark suite, version 0.1"
    print
    
    # Global variable setup
    root_path = os.getcwd()
    python_path = (os.path.join(root_path,'common','python') +
                   ":" +
                   os.environ.get('PYTHONPATH',""))
    
    globals.root = root_path
    globals.benchmarks = benchmark.find_benchmarks()
    globals.program_env = {'PARBOIL_ROOT':root_path,
                           'PYTHONPATH':python_path,
                           }

    # Parse options
    act = options.parse_options(sys.argv)

    # Perform the specified action
    if act: act()
예제 #22
0
def run():
    # Print a banner message
    print "Parboil parallel benchmark suite, version 0.1"
    print

    # Global variable setup
    root_path = os.getcwd()
    python_path = (os.path.join(root_path, 'common', 'python') + ":" +
                   os.environ.get('PYTHONPATH', ""))

    globals.root = root_path
    globals.benchmarks = benchmark.find_benchmarks()
    globals.program_env = {
        'PARBOIL_ROOT': root_path,
        'PYTHONPATH': python_path,
    }

    # Parse options
    act = options.parse_options(sys.argv)

    # Perform the specified action
    if act: act()
예제 #23
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#

from gi.repository import GObject as gobject
import datetime, random
import options, sys

options = options.parse_options (graphic_mode=False, period=2, msgsize=1, timeout=0)

if options['graphic_mode']:
    import gtk
    from abstract_engine import AbstractEngine
    superKlass = AbstractEngine
    mainloop = gtk.main
else:
    from abstract_text_engine import AbstractTextEngine
    superKlass = AbstractTextEngine
    mainloop = gobject.MainLoop().run


class WebBrowserEngine (superKlass):

    def __init__ (self, name, period, msgsize, timeout):
예제 #24
0
"""
This is the starting file for the Hierarchical Actor-Critc (HAC) algorithm.  The below script processes the command-line options specified
by the user and instantiates the environment and agent. 
"""
import comet_ml
from design_agent_and_env import design_agent_and_env
from options import parse_options
from agent import Agent
from run_HAC import run_HAC

# Determine training options specified by user.  The full list of available options can be found in "options.py" file.
FLAGS = parse_options()

# Instantiate the agent and Mujoco environment.  The designer must assign values to the hyperparameters listed in the "design_agent_and_env.py" file.
agent, env = design_agent_and_env(FLAGS)

# Begin training
run_HAC(FLAGS, env, agent)
예제 #25
0
import argparse
import sys
import torch
import torch.optim as optim
from torch.autograd import Variable
from options import parse_options
# from util import SharedLogDirichletInitializer
import random
from terpret_problem import TerpretProblem, TerpretProblem_ConcreteDistribution, TerpretProblem_STE, TerpretProblem_Bop, TerpretProblem_NR, TerpretProblem_NR_New
from terpret_problem import Bop, CustomizedAdam, NewAdam

from terpret_problem import TerpretProblem_binary
from terpret_problem import NewOp

if __name__ == "__main__":
    opts = parse_options()

    manualSeed = 0
    manualSeed = random.randint(1, 10000)  # use if you want new results
    print("Random Seed: ", manualSeed)
    random.seed(manualSeed)
    torch.manual_seed(manualSeed)

    if opts.type == 0:
        ''' type 0: continuous surrogate '''
        tp = TerpretProblem(opts)
        # optimizer = optim.Adam(tp.parameters(), lr=0.001)
        optimizer = optim.Adam(tp.parameters(), lr=0.001)

    elif opts.type == 1:
        ''' type 1: using a local reparameterization of gumble-softmax trick '''
예제 #26
0
import torch
import torch.nn.functional as F
import pickle
import os

import options
import logger
from rl.qlearning_trainer_gc import (
    QLearningGraphCenteredTrainer,
    QLearningPrioritizedBufferGraphCenteredTrainer,
)
from model.graph_centered import GraphCenteredNet, GraphCenteredNetV2
from data.embedding import DirectionalPositionalEmbedding, DirectionalEmbedding

opt = options.parse_options()
opt.embedding = DirectionalPositionalEmbedding()

# Setup logger
logger.setup_logger(opt.logs, training_id=opt.training_id)
history_train = dict()
history_eval = dict()
if opt.use_prioritised_replay:
    trainer = QLearningPrioritizedBufferGraphCenteredTrainer(opt)
else:
    trainer = QLearningGraphCenteredTrainer(opt)

# Load pretrained models if any
if opt.pretrained:
    trainer.policy_net.load_state_dict(torch.load(opt.weights_path))
    trainer.target_net.load_state_dict(torch.load(opt.weights_path))
예제 #27
0
from torch.utils.data import DataLoader
from torch.autograd import Variable
from PIL import Image
import torch

from models import Generator
from models import Discriminator
from utils import ReplayBuffer
from utils import LambdaLR
from utils import Logger
from utils import weights_init_normal
from datasets import ImageDataset
from dataloader import load_dataset_da
from options import parse_options
from tqdm import tqdm
opt = parse_options()

if torch.cuda.is_available() and not opt['cuda']:
    print("WARNING: You have a CUDA device, so you should probably run with --cuda")

###### Definition of variables ######
# Networks
netG_A2B = Generator(opt['input_nc'], opt['output_nc'])
netG_B2A = Generator(opt['output_nc'], opt['input_nc'])
netD_A = Discriminator(opt['input_nc'])
netD_B = Discriminator(opt['output_nc'])

if opt['cuda']:
    netG_A2B.cuda()
    netG_B2A.cuda()
    netD_A.cuda()
예제 #28
0
    def generate(self, opts, outfile=None, format='svg', preview=None, stylesheet=None, render_format='wikiplace', curr_place=00000, cache_bounds=False, cache_view = False, cache_union = False, verbose=False):
        """
        Generates a the map and renders it using the specified output format.
        """
        if preview is None:
            preview = False#outfile is None

        # Create a deep copy of the options dictionary so our changes will not be
        # visible to the calling application.
        opts = deepcopy(opts)

        # Parse the options dictionary. See options.py for more details.
        parse_options(opts)

        # Create the map instance. It will do all the hard work for us, so you
        # definitely should check out [map.py](map.html) for all the fun stuff happending
        # there..
        alt_outfile=''
        countyalt_file=''
        curr_place_name=''
        curr_state_name=''
        curr_state_fips=''
        _map = Map(opts, self.layerCache, format=format,boundCache=self.boundCache, cache_bounds=cache_bounds, viewCache=self.viewCache, cache_view=cache_view, unionCache = self.unionCache, cache_union = cache_union,  verbose=verbose)
        for layer in _map.layers:
            if layer.id=='countylayer':
                county_and_flag=False
                county_list=[(feat.props['NAME'],self.lsad_map[feat.props['LSAD']]) for feat in layer.features]
                county_list=sorted(county_list)
                for (county, county_type) in county_list:
                    if county_and_flag:
                        countyalt_file+='_and_'
                    countyalt_file=countyalt_file+county+'_'+county_type
                    county_and_flag=True
                #print 'Feature={0}'.format(feature.props)
                curr_state_name=self.state_fips[feature.props['STATEFP']]
                curr_state_fips=feature.props['STATEFP']
            for feature in layer.features:
                if 'PLACEFP' in feature.props and feature.props['PLACEFP']==curr_place: # this is highlighting place
                    curr_place_name=re.sub('\s','_',feature.props['NAME']+' '+self.lsad_map[feature.props['LSAD']])
                    
                #print('feature.props={0}'.format(feature.props))
        alt_outfile=countyalt_file+'_'+curr_state_name+'_Incorporated_and_Unincorporated_areas_'+curr_place_name+'_Highlighted_'+curr_state_fips+curr_place+'.svg'
        #print('alt_outfile={0}'.format(alt_outfile))
        if outfile is None:
           
 
            outfile=re.sub('/','-',alt_outfile) # use the alt outfile if nothing else specified
            outfile=outfile.encode('utf-8','replace')
            print 'outfile was None, now={0}'.format(outfile)
        else:
            print('outfile={0}'.format(outfile))
      
        stylesheet+=_map.add_styling();
        # Check if the format is handled by a renderer.
        format = format.lower()
        if format in _known_renderer:
            # Create a stylesheet
            style = MapStyle(stylesheet)
            # Create a renderer instance and render the map.
            renderer = _known_renderer[format](_map)
            renderer.render(style, opts['export']['prettyprint'], render_format)

            if preview:
                if 'KARTOGRAPH_PREVIEW' in os.environ:
                    command = os.environ['KARTOGRAPH_PREVIEW']
                else:
                    commands = dict(win32='start', win64='start', darwin='open', linux2='xdg-open')
                    import sys
                    if sys.platform in commands:
                        command = commands[sys.platform]
                    else:
                        sys.stderr.write('don\'t know how to preview SVGs on your system. Try setting the KARTOGRAPH_PREVIEW environment variable.')
                        print renderer
                        return
                renderer.preview(command)
            # Write the map to a file or return the renderer instance.
            if outfile is None:
                return renderer
            elif outfile == '-':
                print renderer
            else:
                renderer.write(outfile)
        else:
            raise KartographError('unknown format: %s' % format)
예제 #29
0
		    result = lisp_tree_str(tree[0])
		else:
			result = tree[0]
	print>>destination,result

class ReadlineWrap(object):
    def readline(self):
        return raw_input()

def main(options,args):
	destination = sys.stdout
	if options.expression != None:
		eval_expression(options.expression,options.eval,destination)
		return
	if options.filename:
		input_file = open(options.filename)
	else:
		input_file = ReadlineWrap()
	while True:
		try:		
			input = input_file.readline().strip()
			if input == "":
				break
			eval_expression(input,options.eval,destination,options)
			
		except EOFError:
			break
if __name__=="__main__":
	options,args = options.parse_options(sys.argv)
	main(options,args)
예제 #30
0

class ReadlineWrap(object):
    def readline(self):
        return raw_input()


def main(options, args):
    destination = sys.stdout
    if options.expression != None:
        eval_expression(options.expression, options.eval, destination)
        return
    if options.filename:
        input_file = open(options.filename)
    else:
        input_file = ReadlineWrap()
    while True:
        try:
            input = input_file.readline().strip()
            if input == "":
                break
            eval_expression(input, options.eval, destination, options)

        except EOFError:
            break


if __name__ == "__main__":
    options, args = options.parse_options(sys.argv)
    main(options, args)