Python exceptions 模块,ValueError() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用exceptions.ValueError()

项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfkr(self, armjnts, armid ="rgt"):
        """
        move the redundant joints of armlj using forward kinematics

        :param armjnts: [waistrot, shoulderrot, armjnts6] all in angle
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20170112
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            armlj[i]['rotangle'] = armjnts[1][counter]
            counter += 1

        self.movewaist(armjnts[0])
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfk6(self, armjnts, armid="rgt"):
        """
        move the last 6 joints of armlj using forward kinematics

        :param armjnts: a 1-by-6 ndarray where each element indicates the angle of a joint (in degree)
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20161205
        """

        if armid != "rgt" and armid != "lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__sixjoints:
            armlj[i]['rotangle'] = armjnts[counter]
            counter += 1
        self.__updatefk(armlj)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfkr(self, armjnts, armid ="rgt"):
        """
        move the redundant joints of armlj using forward kinematics

        :param armjnts: [waistrot, shoulderrot, armjnts6] all in angle
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20170112
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__sixjoints:
            armlj[i]['rotangle'] = armjnts[2][counter]
            counter += 1

        self.movewaistshoulder(armjnts[0], armjnts[1], armid)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def getarmjnts6(self, armid="rgt"):
        """
        get the last 6 joints of the specified armid

        :param armid:
        :return: armjnts: a 1-by-6 numpy ndarray

        author: weiwei
        date: 20161205, tsukuba
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        armjnts = np.zeros(6)
        counter = 0
        for i in self.__sixjoints:
            armjnts[counter] = armlj[i]['rotangle']
            counter += 1

        return armjnts
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def getjntwaistshoulder(self, armid="rgt"):
        """
        get the rot angle of robot shoulder and waist

        :return: [waistangle, shoulderangle] in degree

         author: weiwei
         date: 20170112
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError("Armid must be 'rgt' or 'lft'")

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        return [self.base['rotangle'], armlj[1]['rotangle']]
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def getarmjnts(self, armid="rgt"):
        """
        get the target joints of the specified armid

        :param armid:
        :return: armjnts: a 1-by-6 numpy ndarray

        author: weiwei
        date: 20161111, tsukuba
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        armjnts = np.zeros(len(self.__targetjoints))
        counter = 0
        for i in self.__targetjoints:
            armjnts[counter] = armlj[i]['rotangle']
            counter += 1

        return armjnts
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def jacobian(nxtrobot, armid="rgt"):
    """
    compute the jacobian matrix of rgt or lft arm

    :param nxtrobot: see the nextage.NxtRobot class
    :param armid: a string indicating "rgt" or "lft"
    :return: armjac a 6-by-6 ndarray

    author: weiwei
    date: 20161111
    """

    if armid!="rgt" and armid!="lft":
        raise ep.ValueError

    armlj = nxtrobot.rgtarm
    if armid == "lft":
        armlj = nxtrobot.lftarm

    armjac = np.zeros((6,6))
    for i in range(6):
        a = np.dot(armlj[i+1]["rotmat"], armlj[i+1]["rotax"])
        armjac[:, i] = np.append(np.cross(a, armlj[6]["linkpos"]-armlj[i+1]["linkpos"]), a)

    return armjac
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfk(self, armjnts, armid="rgt"):
        """
        move the joints of armlj specified by targetjoints using forward kinematics, waist is not included

        :param armjnts: a 1-by-6 ndarray where each element indicates the angle of a joint (in degree)
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20161205
        """

        if armid != "rgt" and armid != "lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            armlj[i]['rotangle'] = armjnts[counter]
            counter += 1
        self.__updatefk(armlj)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfkr(self, armjnts, armid ="rgt"):
        """
        move the redundant joints of armlj using forward kinematics

        :param armjnts: [waistrot, shoulderrot, armjnts6] all in angle
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20170112
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            armlj[i]['rotangle'] = armjnts[1][counter]
            counter += 1

        self.movewaist(armjnts[0])
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def getarmjnts(self, armid="rgt"):
        """
        get the target joints of the specified armid

        :param armid:
        :return: armjnts: a 1-by-x numpy ndarray

        author: weiwei
        date: 20161205, tsukuba
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        armjnts = np.zeros(len(self.__targetjoints))
        counter = 0
        for i in self.__targetjoints:
            armjnts[counter] = armlj[i]['rotangle']
            counter += 1

        return armjnts
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfk(self, armjnts, armid="rgt"):
        """
        move the joints of armlj specified by targetjoints using forward kinematics, waist is not included

        :param armjnts: a 1-by-n ndarray where each element indicates the angle of a joint (in degree)
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20161205
        """

        if armid != "rgt" and armid != "lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            armlj[i]['rotangle'] = armjnts[counter]
            counter += 1
        self.__updatefk(armlj)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def getarmjnts(self, armid="rgt"):
        """
        get the target joints of the specified armid

        :param armid:
        :return: armjnts: a 1-by-x numpy ndarray

        author: weiwei
        date: 20161205, tsukuba
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        armjnts = np.zeros(len(self.__targetjoints))
        counter = 0
        for i in self.__targetjoints:
            armjnts[counter] = armlj[i]['rotangle']
            counter += 1

        return armjnts
项目:serverthrallapi    作者:NullSoldier    | 项目源码 | 文件源码
def next_id(self):
        now = int(time.time() * 1000)
        duplicateTime = (now == self.lastPushTime)
        self.lastPushTime = now
        timeStampChars = [''] * 8

        for i in range(7, -1, -1):
            timeStampChars[i] = self.PUSH_CHARS[now % 64]
            now = int(now / 64)

        if (now != 0):
            raise ValueError('We should have converted the entire timestamp.')

        uid = ''.join(timeStampChars)

        if not duplicateTime:
            for i in range(12):
                self.lastRandChars[i] = int(random.random() * 64)
        else:
            # If the timestamp hasn't changed since last push, use the
            # same random number, except incremented by 1.
            for i in range(11, -1, -1):
                if self.lastRandChars[i] == 63:
                    self.lastRandChars[i] = 0
                else:
                    break
            self.lastRandChars[i] += 1

        for i in range(12):
            uid += self.PUSH_CHARS[self.lastRandChars[i]]

        if len(uid) != 20:
            raise ValueError('Length should be 20.')
        return uid
项目:srepp_server    作者:SummitRoute    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__,
                    self.__field_offsets__[key], key+':', val_str))

        return dump
项目:srepp_server    作者:SummitRoute    | 项目源码 | 文件源码
def dump_dict(self):
        """Returns a dictionary representation of the structure."""

        dump_dict = dict()

        dump_dict['Structure'] = self.name

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val = '0x%-8X [%s UTC]' % (val, time.asctime(time.gmtime(val)))
                        except exceptions.ValueError, e:
                            val = '0x%-8X [INVALID TIME]' % val
                else:
                    val = ''.join(filter(lambda c:c != '\0', str(val)))

                dump_dict[key] = {'FileOffset': self.__field_offsets__[key] + self.__file_offset__,
                                  'Offset': self.__field_offsets__[key],
                                  'Value': val}

        return dump_dict
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def validate(self):
        """Call validate() on the BaseResourceAttribute for all _storage_dict items, and
           ensure that all non-optional BaseResourceAttributes have a value in _storage_dict"""
        for k, v in self._storage_dict.items():
            if k in self._meta.storage_attributes:
                self._meta.storage_attributes[k].validate(v)

        for k, a in self._meta.storage_attributes.items():
            if not k in self._storage_dict and not a.optional:
                raise ValueError("Missing mandatory attribute %s" % k)
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def __init__(self, sample_period = DEFAULT_SAMPLE_PERIOD, units = None, label = None):
        """'units' can be None for dimensionless scalars, UNITS_BYTES for
        sizes in bytes, or a string for arbitrary units"""
        try:
            int(sample_period)
        except ValueError:
            raise RuntimeError("sample period '%s' is not an integer!" % sample_period)

        self.sample_period = sample_period
        self.units = units
        self.label = label
项目:PyMal    作者:cysinfo    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__, 
                    self.__field_offsets__[key], key+':', val_str))

        return dump
项目:tools    作者:sourceincite    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s]' % time.ctime(val)
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('%-30s %s' % (key+':', val_str))

        return dump
项目:pefile-go    作者:omarghader    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__,
                    self.__field_offsets__[key], key+':', val_str))

        return dump
项目:pefile-go    作者:omarghader    | 项目源码 | 文件源码
def dump_dict(self):
        """Returns a dictionary representation of the structure."""

        dump_dict = dict()

        dump_dict['Structure'] = self.name

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val = '0x%-8X [%s UTC]' % (val, time.asctime(time.gmtime(val)))
                        except exceptions.ValueError, e:
                            val = '0x%-8X [INVALID TIME]' % val
                else:
                    val = ''.join(filter(lambda c:c != '\0', str(val)))

                dump_dict[key] = {'FileOffset': self.__field_offsets__[key] + self.__file_offset__,
                                  'Offset': self.__field_offsets__[key],
                                  'Value': val}

        return dump_dict
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def myint(string):
    f, s = False, []
    for char in string:
        if char in '0123456789':
            s.append(char)
            f = True
        elif f:
            break
    try:
        return int(''.join(s))
    except exceptions.ValueError:
        return 0
项目:apiscout    作者:danielplohmann    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__, 
                    self.__field_offsets__[key], key+':', val_str))

        return dump
项目:requests-arcgis-auth    作者:DOI-BLM    | 项目源码 | 文件源码
def _handle_response(self, resp, **kwargs):
        # type(r) = Response
        # Check the response for an expired token... re-acquire if necessary
        #       ex:     {u'error': {u'code': 498, u'details': [], u'message': u'Invalid token.'}}

        ### Handling Expired Tokens!!!

        # Check for actual HTTP Status code 498 (when f=json is not supplied)
        if resp.status_code == 498:
            return self._handle_expired_token(resp,**kwargs)

        # Check for JSON error (vendor spec)
        try:
            if resp.json().get("error") is not None:
                err = resp.json().get("error")
                if err.get("code") == 498 and err.get("message") == "Invalid token.":
                    return self._handle_expired_token(resp, **kwargs)
                else:
                    # Why do we get here?!?!?!?
                    #    {u'error': {u'code': 403,
                    #        u'details': [],
                    #        u'message': u'You do not have permissions to access this resource or perform this operation.',
                    #        u'messageCode': u'GWM_0003'}}
                    # OTHERS?!?!?!?
                    # raise TokenAuthenticationError("Failed to handle expired token...")
                    pass
        # Unable to parse JSON data... requestor could ask for non-JSON formatted data...  Just throw away exception for now...
        except ValueError:
            pass
        return resp
项目:derbycon-binary_ninja    作者:VDA-Labs    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__,
                    self.__field_offsets__[key], key+':', val_str))

        return dump
项目:derbycon-binary_ninja    作者:VDA-Labs    | 项目源码 | 文件源码
def dump_dict(self):
        """Returns a dictionary representation of the structure."""

        dump_dict = dict()

        dump_dict['Structure'] = self.name

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val = '0x%-8X [%s UTC]' % (val, time.asctime(time.gmtime(val)))
                        except exceptions.ValueError, e:
                            val = '0x%-8X [INVALID TIME]' % val
                else:
                    val = ''.join(filter(lambda c:c != '\0', str(val)))

                dump_dict[key] = {'FileOffset': self.__field_offsets__[key] + self.__file_offset__,
                                  'Offset': self.__field_offsets__[key],
                                  'Value': val}

        return dump_dict
项目:derbycon-binary_ninja    作者:VDA-Labs    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__,
                    self.__field_offsets__[key], key+':', val_str))

        return dump
项目:derbycon-binary_ninja    作者:VDA-Labs    | 项目源码 | 文件源码
def dump_dict(self):
        """Returns a dictionary representation of the structure."""

        dump_dict = dict()

        dump_dict['Structure'] = self.name

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val = '0x%-8X [%s UTC]' % (val, time.asctime(time.gmtime(val)))
                        except exceptions.ValueError, e:
                            val = '0x%-8X [INVALID TIME]' % val
                else:
                    val = ''.join(filter(lambda c:c != '\0', str(val)))

                dump_dict[key] = {'FileOffset': self.__field_offsets__[key] + self.__file_offset__,
                                  'Offset': self.__field_offsets__[key],
                                  'Value': val}

        return dump_dict
项目:rucio    作者:rucio01    | 项目源码 | 文件源码
def get_config(self, section=None, option=None):
        """
        Sends the request to get the matching configuration.

        :param section: the optional name of the section.
        :param option: the optional option within the section.
        :return: dictionary containing the configuration.
        """

        if section is None and option is not None:
            raise ValueError('--section not specified')

        path = self.CONFIG_BASEURL
        if section is not None and option is None:
            path += '/' + section
        elif section is not None and option is not None:
            path += '/'.join(['', section, option])

        url = build_url(choice(self.list_hosts), path=path)

        r = self._send_request(url, type='GET')
        if r.status_code == codes.ok:
            return r.json()
        else:
            exc_cls, exc_msg = self._get_exception(headers=r.headers, status_code=r.status_code, data=r.content)
            raise exc_cls(exc_msg)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def jacobian(hrp2krobot, armid="rgt"):
    """
    compute the jacobian matrix of the last 6 dof for rgt or lft arm

    :param hrp2krobot: see the hrp2k.Hrp2KRobot class
    :param armid: a string indicating "rgt" or "lft"
    :return: armjac a 6-by-6 ndarray

    author: weiwei
    date: 20170626
    """

    if armid!="rgt" and armid!="lft":
        raise ep.ValueError

    armlj = hrp2krobot.rgtarm
    if armid == "lft":
        armlj = hrp2krobot.lftarm

    armjac = np.zeros((6,len(hrp2krobot.targetjoints)))

    counter = 0
    for i in hrp2krobot.targetjoints:
        a = np.dot(armlj[i]["rotmat"], armlj[i]["rotax"])
        armjac[:, counter] = np.append(np.cross(a, armlj[hrp2krobot.targetjoints[-1]]["linkpos"]-armlj[i]["linkpos"]), a)
        counter += 1

    return armjac
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfk(self, armjnts, armid="rgt"):
        """
        move the joints of armlj specified by targetjoints using forward kinematics, waist is not included

        :param armjnts: a 1-by-n ndarray where each element indicates the angle of a joint (in degree)
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20161205
        """

        if armid != "rgt" and armid != "lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            armlj[i]['rotangle'] = armjnts[counter]
            counter += 1
        self.__updatefk(armlj)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def chkrng(self, armjnts, armid="rgt"):
        """
        check if the given armjnts is inside the oeprating range of the speificed armid
        this function doesn't check the waist

        :param armjnts: a 1-by-6 numpy ndarray indicating the targejoints of a manipulator
        :param armid: a string "rgt" or "lft"
        :return: True or False indicating inside the range or not

        author: weiwei
        date: 20161205
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            if armjnts[counter] < armlj[i]["rngmin"] or armjnts[counter] > armlj[i]["rngmax"]:
                # print "Joint "+ str(i) + " of the " + armid + " arm is out of range"
                # print "Angle is " + str(armjnts[counter])
                # print "Range is (" + str(armlj[i]["rngmin"]) + ", " + str(armlj[i]["rngmax"]) + ")"
                return False
            counter += 1

        return True
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def eubik(pos, armid="rgt"):
    """
    compute the euristic waist angles for the first three joints?
    ew = euristic waist
    eubik doesnt use waist
    eubik use waist

    :param pos: object position
    :return: [waistangle, shoulderangle] in degree

    author: weiwei
    date: 20161202
    """

    newpos = copy.deepcopy(pos)
    anglecomponent1 = 0
    try:
        if armid == "rgt":
            newpos[1] = newpos[1]-80
        else:
            if armid == "lft":
                newpos[1] = newpos[1]+80
            else:
                raise ValueError("Armid must be 'rgt' or 'lft'")
        anglecomponent1 = math.asin(130 / np.linalg.norm(newpos[0:2]))
    except:
        pass
    shoulderangle = (math.atan2(newpos[1], newpos[0]) + anglecomponent1) * 180 / math.pi
    if armid == "rgt":
        if shoulderangle > 55:
            shoulderangle = 55
        if shoulderangle < -15:
            shoulderangle = -15
    if armid == "lft":
        shoulderangle = -shoulderangle
        if shoulderangle > 15:
            shoulderangle = 15
        if shoulderangle < -55:
            shoulderangle = -55
    return [0, shoulderangle]
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def jacobian(hrp5robot, armid="rgt"):
    """
    compute the jacobian matrix of the last 6 dof for rgt or lft arm

    :param hrp5robot: see the hrp5.Hrp5Robot class
    :param armid: a string indicating "rgt" or "lft"
    :return: armjac a 6-by-6 ndarray

    author: weiwei
    date: 20161202
    """

    if armid!="rgt" and armid!="lft":
        raise ep.ValueError

    armlj = hrp5robot.rgtarm
    if armid == "lft":
        armlj = hrp5robot.lftarm

    armjac = np.zeros((6,6))

    counter = 0
    for i in hrp5robot.sixjoints:
        a = np.dot(armlj[i]["rotmat"], armlj[i]["rotax"])
        armjac[:, counter] = np.append(np.cross(a, armlj[hrp5robot.sixjoints[-1]]["linkpos"]-armlj[i]["linkpos"]), a)
        counter += 1

    return armjac
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movewaistshoulder(self, waistrot, shoulderrot, armid="rgt"):
        """
        rotate the shoulderwaist of the robot

        :param waistrot: in degree
        :param shoulderrot: in degree
        :return: null

        author: weiwei
        date: 20170112
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError("Armid must be 'rgt' or 'lft'")

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        # right arm
        self.rgtarm[0]['rotangle'] = waistrot
        self.rgtarm[0]['rotmat'] = rm.rodrigues(self.rgtarm[0]['rotax'], self.rgtarm[0]['rotangle'])
        self.rgtarm[0]['linkend'] = np.squeeze(np.dot(self.rgtarm[0]['rotmat'], self.rgtarm[0]['linkvec'].reshape((-1,))))+self.rgtarm[0]['linkpos']

        # left arm
        self.lftarm[0]['rotangle'] = waistrot
        self.lftarm[0]['rotmat'] = rm.rodrigues(self.lftarm[0]['rotax'], self.lftarm[0]['rotangle'])
        self.lftarm[0]['linkend'] = np.squeeze(np.dot(self.lftarm[0]['rotmat'], self.lftarm[0]['linkvec'].reshape((-1,))))+self.lftarm[0]['linkpos']

        # shoulder
        armlj[1]['rotangle'] = shoulderrot

        self.__updatefk(self.rgtarm)
        self.__updatefk(self.lftarm)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def movearmfk(self, armjnts, armid="rgt"):
        """
        move the 6 joints of armlj using forward kinematics
        this function will replace movearmfk6

        :param armjnts: a 1-by-6 ndarray where each element indicates the angle of a joint (in degree)
        :param armid: a string indicating the rgtlj or lftlj robot structure, could "lft" or "rgt"
        :return: null

        author: weiwei
        date: 20161205
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            armlj[i]['rotangle'] = armjnts[counter]
            counter += 1

        self.__updatefk(armlj)
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def goinitpose(self):
        """
        move the nextage robot to initial pose

        :return: null

        author: weiwei
        date: 20161108
        """

        self.movealljnts(self.initjnts)

    # def getarmjnts6(self, armid="rgt"):
    #     """
    #     get the 6 joints of the specified armid
    #
    #     :param armid:
    #     :return: armjnts: a 1-by-6 numpy ndarray
    #
    #     author: weiwei
    #     date: 20161111, tsukuba
    #     """
    #
    #     if armid!="rgt" and armid!="lft":
    #         raise ep.ValueError
    #
    #     armlj = self.rgtarm
    #     if armid == "lft":
    #         armlj = self.lftarm
    #
    #     armjnts = np.zeros(6)
    #     for i in range(6):
    #         armjnts[i] = armlj[i+1]['rotangle']
    #
    #     return armjnts
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def jacobian(ur5dualrobot, armid="rgt"):
    """
    compute the jacobian matrix of the targetjoints of rgt or lft arm

    :param ur5dualrobot: see the ur5.ur5dual class
    :param armid: a string indicating "rgt" or "lft"
    :return: armjac a 6-by-x matrix

    author: weiwei
    date: 20161202
    """

    if armid!="rgt" and armid!="lft":
        raise ep.ValueError

    armlj = ur5dualrobot.rgtarm
    if armid == "lft":
        armlj = ur5dualrobot.lftarm

    armjac = np.zeros((6,len(ur5dualrobot.targetjoints)))

    counter = 0
    for i in ur5dualrobot.targetjoints:
        a = np.dot(armlj[i]["rotmat"], armlj[i]["rotax"])
        armjac[:, counter] = np.append(np.cross(a, armlj[ur5dualrobot.targetjoints[-1]]["linkpos"]-armlj[i]["linkpos"]), a)
        counter += 1

    return armjac
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def chkrng(self, armjnts, armid="rgt"):
        """
        check if the given armjnts is inside the oeprating range of the speificed armid
        this function doesn't check the waist

        :param armjnts: a 1-by-x numpy ndarray indicating the targejoints of a manipulator
        :param armid: a string "rgt" or "lft"
        :return: True or False indicating inside the range or not

        author: weiwei
        date: 20161205
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            if armjnts[counter] < armlj[i]["rngmin"] or armjnts[counter] > armlj[i]["rngmax"]:
                print "Joint "+ str(i) + " of the " + armid + " arm is out of range"
                print "Angle is " + str(armjnts[counter])
                print "Range is (" + str(armlj[i]["rngmin"]) + ", " + str(armlj[i]["rngmax"]) + ")"
                return False
            counter += 1

        return True
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def chkrng(self, armjnts, armid="rgt"):
        """
        check if the given armjnts is inside the oeprating range of the speificed armid
        this function doesn't check the waist

        :param armjnts: a 1-by-6 numpy ndarray indicating the targejoints of a manipulator
        :param armid: a string "rgt" or "lft"
        :return: True or False indicating inside the range or not

        author: weiwei
        date: 20161205
        """

        if armid!="rgt" and armid!="lft":
            raise ep.ValueError

        armlj = self.rgtarm
        if armid == "lft":
            armlj = self.lftarm

        counter = 0
        for i in self.__targetjoints:
            if armjnts[counter] < armlj[i]["rngmin"] or armjnts[counter] > armlj[i]["rngmax"]:
                # print "Joint "+ str(i) + " of the " + armid + " arm is out of range"
                # print "Angle is " + str(armjnts[counter])
                # print "Range is (" + str(armlj[i]["rngmin"]) + ", " + str(armlj[i]["rngmax"]) + ")"
                return False
            counter += 1

        return True
项目:pyhiro    作者:wanweiwei07    | 项目源码 | 文件源码
def jacobian(hrp5nrobot, armid="rgt"):
    """
    compute the jacobian matrix of the last 6 dof for rgt or lft arm

    :param hrp5robot: see the hrp5.Hrp5Robot class
    :param armid: a string indicating "rgt" or "lft"
    :return: armjac a 6-by-6 ndarray

    author: weiwei
    date: 20161202
    """

    if armid!="rgt" and armid!="lft":
        raise ep.ValueError

    armlj = hrp5nrobot.rgtarm
    if armid == "lft":
        armlj = hrp5nrobot.lftarm

    armjac = np.zeros((6,len(hrp5nrobot.targetjoints)))

    counter = 0
    for i in hrp5nrobot.targetjoints:
        a = np.dot(armlj[i]["rotmat"], armlj[i]["rotax"])
        armjac[:, counter] = np.append(np.cross(a, armlj[hrp5nrobot.targetjoints[-1]]["linkpos"]-armlj[i]["linkpos"]), a)
        counter += 1

    return armjac
项目:OpenC2SDN    作者:SDNC2    | 项目源码 | 文件源码
def process_oc2_command(self, request):
        try:
            request.setHeader('Content-Type', 'application/json')
            body = json.loads(request.content.read())

            # PROCESS OPENC2 message here.
            result = self.handler(body)
            if isinstance(result, basestring):
                return result
            else:
                return json.dumps(result)

        except exceptions.ValueError:
                return json.dumps({'success': False, 'message': 'Failed to parse JSON-encoded action.'})
项目:pyry3d_chimera_extension    作者:mdobrychlop    | 项目源码 | 文件源码
def isReal(self, txt):
        try:
            float(txt)
            return True
        except ValueError:
            return False
项目:HydroSphere    作者:lake-lerna    | 项目源码 | 文件源码
def validate_deployment_id(deployment_id):
    # Since hydra depends on dashes and gce api doesn't allow other non-aphanumeric characters
    # in instance names, don't allow them in deployment_ids
    if re.match(r"^[A-Za-z0-9]+$", deployment_id):
        return deployment_id
    else:
        exception_msg = "--deployment_id | -i <%s> cannot contain non-alphanumeric characters" % (deployment_id)
        raise ValueError(exception_msg)
项目:python-ormsqlite    作者:vallemrv    | 项目源码 | 文件源码
def get_dato(self):
        if self.null == False and self.dato == None:
            raise ValueError("Error el valor no puede ser nulo")
        return self.dato
项目:python-ormsqlite    作者:vallemrv    | 项目源码 | 文件源码
def set_dato(self, value):
        if not ("@" in value and "." in value):
            raise ValueError('Formato email no valido')
        self.dato = value
项目:python-ormsqlite    作者:vallemrv    | 项目源码 | 文件源码
def get_pack_dato(self):
        if self.auto_now:
            self.dato = date.today()
        elif self.auto_now_add and self.dato == None:
            self.dato = date.today()
        elif self.null == False and self.dato == None:
            raise ValueError("El dato no puede ser null")

        return u'"{0}"'.format(unicode(self.dato))
项目:python-ormsqlite    作者:vallemrv    | 项目源码 | 文件源码
def get_pack_dato(self):
        if self.auto_now:
            self.dato = datetime.now()
        elif self.auto_now_add and self.dato == None:
            self.dato = datetime.now()
        elif self.null == False and self.dato == None:
            raise ValueError("El dato no puede ser null")
        return u'"{0}"'.format(unicode(self.dato))
项目:Snakepit    作者:K4lium    | 项目源码 | 文件源码
def dump(self, indentation=0):
        """Returns a string representation of the structure."""

        dump = []

        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__,
                    self.__field_offsets__[key], key+':', val_str))

        return dump
项目:Snakepit    作者:K4lium    | 项目源码 | 文件源码
def dump_dict(self):
        """Returns a dictionary representation of the structure."""

        dump_dict = dict()

        dump_dict['Structure'] = self.name

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val = '0x%-8X [%s UTC]' % (val, time.asctime(time.gmtime(val)))
                        except exceptions.ValueError, e:
                            val = '0x%-8X [INVALID TIME]' % val
                else:
                    val = ''.join(filter(lambda c:c != '\0', str(val)))

                dump_dict[key] = {'FileOffset': self.__field_offsets__[key] + self.__file_offset__,
                                  'Offset': self.__field_offsets__[key],
                                  'Value': val}

        return dump_dict