Open handle

        set protocol=2 to fix python3

        .. versionadded:: 1.3.1
434504
def open(self, flag="c"):
        
        return shelve.open(os.path.join(gettempdir(), self.index), flag=flag, protocol=2)
598616
def params_to_blr(self, trans_handle, params):
        ""
        ln = len(params) * 2
        blr = bs([5, 2, 4, 0, ln & 255, ln >> 8])
        if self.accept_version < PROTOCOL_VERSION13:
            values = bs([])
        else:
            # start with null indicator bitmap
            null_indicator = 0
            for i, p in enumerate(params):
                if p is None:
                    null_indicator |= (1 << i)
            n = len(params) // 8
            if len(params) % 8 != 0:
                n += 1
            if n % 4:   # padding
                n += 4 - n % 4
            null_indicator_bytes = []
            for i in range(n):
                null_indicator_bytes.append(null_indicator & 255)
                null_indicator >>= 8
            values = bs(null_indicator_bytes)
        for p in params:
            if (
                (PYTHON_MAJOR_VER == 2 and type(p) == unicode) or
                (PYTHON_MAJOR_VER == 3 and type(p) == str)
            ):
                p = self.str_to_bytes(p)
            t = type(p)
            if p is None:
                v = bs([])
                blr += bs([14, 0, 0])
            elif (
                (PYTHON_MAJOR_VER == 2 and t == str) or
                (PYTHON_MAJOR_VER == 3 and t == bytes)
            ):
                if len(p) > MAX_CHAR_LENGTH:
                    v = self._create_blob(trans_handle, p)
                    blr += bs([9, 0])
                else:
                    v = p
                    nbytes = len(v)
                    pad_length = ((4-nbytes) & 3)
                    v += bs([0]) * pad_length
                    blr += bs([14, nbytes & 255, nbytes >> 8])
            elif t == int:
                v = bint_to_bytes(p, 4)
                blr += bs([8, 0])    # blr_long
            elif t == float and p == float("inf"):
                v = b'\x7f\x80\x00\x00'
                blr += bs([10])
            elif t == decimal.Decimal or t == float:
                if t == float:
                    p = decimal.Decimal(str(p))
                (sign, digits, exponent) = p.as_tuple()
                v = 0
                ln = len(digits)
                for i in range(ln):
                    v += digits[i] * (10 ** (ln - i - 1))
                if sign:
                    v *= -1
                v = bint_to_bytes(v, 8)
                if exponent < 0:
                    exponent += 256
                blr += bs([16, exponent])
            elif t == datetime.date:
                v = convert_date(p)
                blr += bs([12])
            elif t == datetime.time:
                if p.tzinfo:
                    v = convert_time_tz(p)
                    blr += bs([28])
                else:
                    v = convert_time(p)
                    blr += bs([13])
            elif t == datetime.datetime:
                if p.tzinfo:
                    v = convert_timestamp_tz(p)
                    blr += bs([29])
                else:
                    v = convert_timestamp(p)
                    blr += bs([35])
            elif t == bool:
                v = bs([1, 0, 0, 0]) if p else bs([0, 0, 0, 0])
                blr += bs([23])
            else:   # fallback, convert to string
                p = p.__repr__()
                if PYTHON_MAJOR_VER == 3 or (PYTHON_MAJOR_VER == 2 and type(p) == unicode):
                    p = self.str_to_bytes(p)
                v = p
                nbytes = len(v)
                pad_length = ((4-nbytes) & 3)
                v += bs([0]) * pad_length
                blr += bs([14, nbytes & 255, nbytes >> 8])
            blr += bs([7, 0])
            values += v
            if self.accept_version < PROTOCOL_VERSION13:
                values += bs([0]) * 4 if not p is None else bs([0xff, 0xff, 0xff, 0xff])
        blr += bs([255, 76])    # [blr_end, blr_eoc]
        return blr, values
651869
def handle_getinfo(self, conn, args):
        """"""
        result = None
        if args[0] == b'version':
            result = self.version
        elif args[0] == b's2k_count':
            # Use highest number of S2K iterations.
            # https://www.gnupg.org/documentation/manuals/gnupg/OpenPGP-Options.html
            # https://tools.ietf.org/html/rfc4880#section-3.7.1.3
            result = '{}'.format(64 << 20).encode('ascii')
        else:
            log.warning('Unknown GETINFO command: %s', args)

        if result:
            keyring.sendline(conn, b'D ' + result)
385360
def help(handler):
    
    data = {'operation': 'describe'}
    response = handler.invoke(data, raw=True)
    description = response.data
    lines = []
    lines.append('# {}'.format(handler.lambda_fn))
    lines.append('## Handler Info')
    lines.append('**Cruddy version**: {}'.format(
        description['cruddy_version']))
    lines.append('')
    lines.append('**Table name**: {}'.format(description['table_name']))
    lines.append('')
    lines.append('**Supported operations**:')
    lines.append('')
    for op in description['supported_operations']:
        lines.append('* {}'.format(op))
    lines.append('')
    lines.append('**Prototype**:')
    lines.append('')
    lines.append('```')
    lines.append(str(description['prototype']))
    lines.append('```')
    lines.append('')
    lines.append('## Operations')
    for op_name in description['operations']:
        op = description['operations'][op_name]
        lines.append('### {}'.format(op_name))
        lines.append('')
        lines.append(_build_signature_line(
            op_name, description['operations'][op_name]['argspec']))
        lines.append('')
        if op['docs'] is None:
            lines.append('')
        else:
            lines.append(op['docs'])
        lines.append('')
    click.echo('\n'.join(lines))
116198
function(err, res) {
				if(err) {
					return onError('Weird Error open', err);
				}
				//Check for no errors
				if(res === 0) {
					//Save the handle & other information to the 
					//	device class
					self.handle = refDeviceHandle.readInt32LE(0);
					self.deviceType = deviceType;
					self.connectionType = connectionType;
					self.identifier = identifier;
					self.isHandleValid = true;
					return onSuccess();
				} else {
					//Make sure that the handle, deviceType 
					//		& connectionType are still null
					self.handle = null;
					self.deviceType = null;
					self.connectionType = null;
					self.identifier = null;
					return onError(res);
				}
			}
124351
def SetProtocol(self, protocol):
    
    if protocol not in self.SUPPORTED_PROTOCOLS:
      raise ValueError('Unsupported protocol: {0!s}'.format(protocol))

    self._protocol = protocol
648268
async def on_isupport_chanmodes(self, value):
        
        list, param, param_set, noparams = [ set(modes) for modes in value.split(',')[:4] ]
        self._channel_modes.update(set(value.replace(',', '')))

        # The reason we have to do it like this is because other ISUPPORTs (e.g. PREFIX) may update these values as well.
        if not rfc1459.protocol.BEHAVIOUR_LIST in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST].update(list)

        if not rfc1459.protocol.BEHAVIOUR_PARAMETER in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER].update(param)

        if not rfc1459.protocol.BEHAVIOUR_PARAMETER_ON_SET in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER_ON_SET] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_PARAMETER_ON_SET].update(param_set)

        if not rfc1459.protocol.BEHAVIOUR_NO_PARAMETER in self._channel_modes_behaviour:
            self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_NO_PARAMETER] = set()
        self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_NO_PARAMETER].update(noparams)
520448
def openAPIDoc(**kwargs):
    
    s = yaml.dump(kwargs, default_flow_style=False)
    def deco(routeHandler):
        # Wrap routeHandler, retaining name and __doc__, then edit __doc__.

        # The only reason we need to do this is so we can be certain
        # that __doc__ will be modifiable. partial() objects have
        # a modifiable __doc__, but native function objects do not.
        ret = functools.wraps(routeHandler)(routeHandler)
        if not ret.__doc__:
            ret.__doc__ = ''
        ret.__doc__ = cleandoc(ret.__doc__) + '\n---\n' + s
        return ret
    return deco
727427
async def cli_handler(loop):
    """"""
    parser = argparse.ArgumentParser()

    parser.add_argument('command', nargs='+',
                        help='commands, help, ...')
    parser.add_argument('--name', help='apple tv name',
                        dest='name', default='Apple TV')
    parser.add_argument('--address', help='device ip address or hostname',
                        dest='address', default=None)
    parser.add_argument('--protocol', action=TransformProtocol,
                        help='protocol to use (values: dmap, mrp)',
                        dest='protocol', default=None)
    parser.add_argument('--port', help='port when connecting',
                        dest='port', type=_in_range(0, 65535),
                        default=0)
    parser.add_argument('-t', '--scan-timeout', help='timeout when scanning',
                        dest='scan_timeout', type=_in_range(1, 100),
                        metavar='TIMEOUT', default=3)
    parser.add_argument('--version', action='version',
                        help='version of atvremote and pyatv',
                        version='%(prog)s {0}'.format(const.__version__))

    pairing = parser.add_argument_group('pairing')
    pairing.add_argument('--remote-name', help='remote pairing name',
                         dest='remote_name', default='pyatv')
    pairing.add_argument('-p', '--pin', help='pairing pin code',
                         dest='pin_code', metavar='PIN', default=1234,
                         type=_in_range(0, 9999, allow_none=True))
    pairing.add_argument('--pairing-guid',
                         help='pairing guid (16 chars hex)',
                         dest='pairing_guid', default=None)

    parser.add_argument('-a', '--autodiscover', action='store_true',
                        help='automatically find a device',
                        dest='autodiscover', default=False)
    parser.add_argument('--device_credentials', help='credentials to device',
                        dest='device_credentials', default=None)

    airplay = parser.add_argument_group('airplay')
    airplay.add_argument('--airplay_credentials',
                         help='credentials for airplay',
                         dest='airplay_credentials', default=None)

    debug = parser.add_argument_group('debugging')
    debug.add_argument('-v', '--verbose', help='increase output verbosity',
                       action='store_true', dest='verbose')
    debug.add_argument('--debug', help='print debug information',
                       action='store_true', dest='debug')

    args = parser.parse_args()
    loglevel = logging.WARNING
    if args.verbose:
        loglevel = logging.INFO
    if args.debug:
        loglevel = logging.DEBUG

    logging.basicConfig(level=loglevel,
                        format='%(levelname)s: %(message)s')
    logging.getLogger('requests').setLevel(logging.WARNING)

    cmds = retrieve_commands(GlobalCommands)

    if args.command[0] in cmds:
        glob_cmds = GlobalCommands(args, loop)
        return (await _exec_command(
            glob_cmds, args.command[0], print_result=False))
    if args.autodiscover:
        if not await _autodiscover_device(args, loop):
            return 1

        return await _handle_commands(args, loop)
    if args.address:
        return await _handle_commands(args, loop)

    logging.error('To autodiscover an Apple TV, add -a')

    return 1
695378
def args_fixup(args):
    
    # cache key_handle_to_int of all key handles, turning args.key_handles into
    # a list of tuples with both original value and integer
    res = []
    for kh in args.key_handles:
        kh_int = pyhsm.util.key_handle_to_int(kh)
        res.append((kh, kh_int,))
    args.key_handles = res

    # Check if the DB url should be read from an environment variable
    if args.db_url and args.db_url.startswith('env:'):
        env_var = args.db_url[4:]
        if env_var in os.environ:
            args.db_url = os.environ[env_var]
1275483
def begin(self):
        
        log.debug("handshake (version %s)" % PROTOCOL_VERSION)
        version = Version()
        version.services = 0    # can't send blocks
        log.debug("send Version")
        self.send_message(version)
749565
def action_handler_adapter(handler_cls: type, action_name: str) -> Callable:
    

    if not hasattr(handler_cls(), action_name):
        message = "{0} does'nt have attr:{1}".format(handler_cls, action_name)
        raise ValueError(message)

    def wsgiapp(environ, start_response):
        """ inner app """
        handler = handler_cls()
        return getattr(handler, action_name)(environ, start_response)
    return wsgiapp
1083659
def accept(self):
        
        while 1:
            try:
                sock, addr = self._sock.accept()
                return (type(self)(sock,
                    keyfile=self.keyfile,
                    certfile=self.certfile,
                    server_side=True,
                    cert_reqs=self.cert_reqs,
                    ssl_version=self.ssl_version,
                    ca_certs=self.ca_certs,
                    do_handshake_on_connect=self.do_handshake_on_connect,
                    suppress_ragged_eofs=self.suppress_ragged_eofs,
                    ciphers=self.ciphers), addr)
            except socket.error, exc:
                if exc.args[0] not in (errno.EAGAIN, errno.EWOULDBLOCK):
                    raise
                sys.exc_clear()
                self._wait_event(self.gettimeout())
377624
def install_handle_input(self):
        """"""
        self.pointer = self.get_fptr()

        self.hooked = ctypes.windll.user32.SetWindowsHookExA(
            13,
            self.pointer,
            ctypes.windll.kernel32.GetModuleHandleW(None),
            0
        )
        if not self.hooked:
            return False
        return True
1267095
def get_handle():
    '''
    
    '''
    global __handle__
    if not __handle__:
        __handle__ = FT_Library()
        error = FT_Init_FreeType(byref(__handle__))
        if error:
            raise RuntimeError(hex(error))
    return __handle__
828840
def try_open (*args, **kwargs):
    
    try:
        return io.open (*args, **kwargs)
    except IOError as e:
        if e.errno == 2:
            return None
        raise
965670
def defaultDecoder(self, message, server):
        
        mode = message.getArg(OPENID_NS, 'mode')
        fmt = "Unrecognized OpenID mode %r"
        raise ProtocolError(message, text=fmt % (mode,))