Search is not available for this dataset
text
stringlengths
75
104k
def pack_into_dict(fmt, names, buf, offset, data, **kwargs): """Same as :func:`~bitstruct.pack_into()`, but data is read from a dictionary. See :func:`~bitstruct.pack_dict()` for details on `names`. """ return CompiledFormatDict(fmt, names).pack_into(buf, ...
def unpack_from_dict(fmt, names, data, offset=0): """Same as :func:`~bitstruct.unpack_from_dict()`, but returns a dictionary. See :func:`~bitstruct.pack_dict()` for details on `names`. """ return CompiledFormatDict(fmt, names).unpack_from(data, offset)
def byteswap(fmt, data, offset=0): """Swap bytes in `data` according to `fmt`, starting at byte `offset` and return the result. `fmt` must be an iterable, iterating over number of bytes to swap. For example, the format string ``'24'`` applied to the bytes ``b'\\x00\\x11\\x22\\x33\\x44\\x55'`` will p...
def pack(self, *args): """See :func:`~bitstruct.pack()`. """ # Sanity check of the number of arguments. if len(args) < self._number_of_arguments: raise Error( "pack expected {} item(s) for packing (got {})".format( self._number_of_argumen...
def pack_into(self, buf, offset, *args, **kwargs): """See :func:`~bitstruct.pack_into()`. """ # Sanity check of the number of arguments. if len(args) < self._number_of_arguments: raise Error( "pack expected {} item(s) for packing (got {})".format( ...
def unpack_from(self, data, offset=0): """See :func:`~bitstruct.unpack_from()`. """ return tuple([v[1] for v in self.unpack_from_any(data, offset)])
def pack(self, data): """See :func:`~bitstruct.pack_dict()`. """ try: return self.pack_any(data) except KeyError as e: raise Error('{} not found in data dictionary'.format(str(e)))
def pack_into(self, buf, offset, data, **kwargs): """See :func:`~bitstruct.pack_into_dict()`. """ try: self.pack_into_any(buf, offset, data, **kwargs) except KeyError as e: raise Error('{} not found in data dictionary'.format(str(e)))
def unpack_from(self, data, offset=0): """See :func:`~bitstruct.unpack_from_dict()`. """ return {info.name: v for info, v in self.unpack_from_any(data, offset)}
def cli(ctx, version): """Bottery""" # If no subcommand was given and the version flag is true, shows # Bottery version if not ctx.invoked_subcommand and version: click.echo(bottery.__version__) ctx.exit() # If no subcommand but neither the version flag, shows help message elif...
def build_message(self, data): ''' Return a Message instance according to the data received from Telegram API. https://core.telegram.org/bots/api#update ''' message_data = data.get('message') or data.get('edited_message') if not message_data: return N...
def get_chat_id(self, message): ''' Telegram chat type can be either "private", "group", "supergroup" or "channel". Return user ID if it is of type "private", chat ID otherwise. ''' if message.chat.type == 'private': return message.user.id return mess...
def build_message(self, data): ''' Return a Message instance according to the data received from Facebook Messenger API. ''' if not data: return None return Message( id=data['message']['mid'], platform=self.platform, text=d...
async def _get_response(self, message): """ Get response running the view with await syntax if it is a coroutine function, otherwise just run it the normal way. """ view = self.discovery_view(message) if not view: return if inspect.iscoroutinefunctio...
def discovery_view(self, message): """ Use the new message to search for a registered view according to its pattern. """ for handler in self.registered_handlers: if handler.check(message): return handler.view return None
async def message_handler(self, data): """ For each new message, build its platform specific message object and get a response. """ message = self.build_message(data) if not message: logger.error( '[%s] Unable to build Message with data, data=...
def diff(iterable): """Diff elements of a sequence: s -> s0 - s1, s1 - s2, s2 - s3, ... """ a, b = tee(iterable) next(b, None) return (i - j for i, j in izip(a, b))
def unpack(endian, fmt, data): """Unpack a byte string to the given format. If the byte string contains more bytes than required for the given format, the function returns a tuple of values. """ if fmt == 's': # read data as an array of chars val = struct.unpack(''.join([endian, str(...
def read_file_header(fd, endian): """Read mat 5 file header of the file fd. Returns a dict with header values. """ fields = [ ('description', 's', 116), ('subsystem_offset', 's', 8), ('version', 'H', 2), ('endian_test', 's', 2) ] hdict = {} for name, fmt, num_...
def read_element_tag(fd, endian): """Read data element tag: type and number of bytes. If tag is of the Small Data Element (SDE) type the element data is also returned. """ data = fd.read(8) mtpn = unpack(endian, 'I', data[:4]) # The most significant two bytes of mtpn will always be 0, # ...
def read_elements(fd, endian, mtps, is_name=False): """Read elements from the file. If list of possible matrix data types mtps is provided, the data type of the elements are verified. """ mtpn, num_bytes, data = read_element_tag(fd, endian) if mtps and mtpn not in [etypes[mtp]['n'] for mtp in m...
def read_header(fd, endian): """Read and return the matrix header.""" flag_class, nzmax = read_elements(fd, endian, ['miUINT32']) header = { 'mclass': flag_class & 0x0FF, 'is_logical': (flag_class >> 9 & 1) == 1, 'is_global': (flag_class >> 10 & 1) == 1, 'is_complex': (flag_c...
def read_var_header(fd, endian): """Read full header tag. Return a dict with the parsed header, the file position of next tag, a file like object for reading the uncompressed element data. """ mtpn, num_bytes = unpack(endian, 'II', fd.read(8)) next_pos = fd.tell() + num_bytes if mtpn == et...
def read_numeric_array(fd, endian, header, data_etypes): """Read a numeric matrix. Returns an array with rows of the numeric matrix. """ if header['is_complex']: raise ParseError('Complex arrays are not supported') # read array data (stored as column-major) data = read_elements(fd, endia...
def read_cell_array(fd, endian, header): """Read a cell array. Returns an array with rows of the cell array. """ array = [list() for i in range(header['dims'][0])] for row in range(header['dims'][0]): for col in range(header['dims'][1]): # read the matrix header and array ...
def read_struct_array(fd, endian, header): """Read a struct array. Returns a dict with fields of the struct array. """ # read field name length (unused, as strings are null terminated) field_name_length = read_elements(fd, endian, ['miINT32']) if field_name_length > 32: raise ParseError(...
def read_var_array(fd, endian, header): """Read variable array (of any supported type).""" mc = inv_mclasses[header['mclass']] if mc in numeric_class_etypes: return read_numeric_array( fd, endian, header, set(compressed_numeric).union([numeric_class_etypes[mc]]) ) ...
def eof(fd): """Determine if end-of-file is reached for file fd.""" b = fd.read(1) end = len(b) == 0 if not end: curpos = fd.tell() fd.seek(curpos - 1) return end
def loadmat(filename, meta=False): """Load data from MAT-file: data = loadmat(filename, meta=False) The filename argument is either a string with the filename, or a file like object. The returned parameter ``data`` is a dict with the variables found in the MAT file. Call ``loadmat`` with...
def write_elements(fd, mtp, data, is_name=False): """Write data element tag and data. The tag contains the array type and the number of bytes the array data will occupy when written to file. If data occupies 4 bytes or less, it is written immediately as a Small Data Element (SDE). """ fmt ...
def write_var_header(fd, header): """Write variable header""" # write tag bytes, # and array flags + class and nzmax (null bytes) fd.write(struct.pack('b3xI', etypes['miUINT32']['n'], 8)) fd.write(struct.pack('b3x4x', mclasses[header['mclass']])) # write dimensions array write_elements(fd,...
def write_var_data(fd, data): """Write variable data to file""" # write array data elements (size info) fd.write(struct.pack('b3xI', etypes['miMATRIX']['n'], len(data))) # write the data fd.write(data)
def write_compressed_var_array(fd, array, name): """Write compressed variable data to file""" bd = BytesIO() write_var_array(bd, array, name) data = zlib.compress(bd.getvalue()) bd.close() # write array data elements (size info) fd.write(struct.pack('b3xI', etypes['miCOMPRESSED']['n'], le...
def write_numeric_array(fd, header, array): """Write the numeric array""" # make a memory file for writing array data bd = BytesIO() # write matrix header to memory file write_var_header(bd, header) if not isinstance(array, basestring) and header['dims'][0] > 1: # list array data in co...
def write_var_array(fd, array, name=''): """Write variable array (of any supported type)""" header, array = guess_header(array, name) mc = header['mclass'] if mc in numeric_class_etypes: return write_numeric_array(fd, header, array) elif mc == 'mxCHAR_CLASS': return write_char_array(...
def isarray(array, test, dim=2): """Returns True if test is True for all array elements. Otherwise, returns False. """ if dim > 1: return all(isarray(array[i], test, dim - 1) for i in range(len(array))) return all(test(i) for i in array)
def guess_header(array, name=''): """Guess the array header information. Returns a header dict, with class, data type, and size information. """ header = {} if isinstance(array, Sequence) and len(array) == 1: # sequence with only one element, squeeze the array array = array[0] ...
def savemat(filename, data): """Save data to MAT-file: savemat(filename, data) The filename argument is either a string with the filename, or a file like object. The parameter ``data`` shall be a dict with the variables. A ``ValueError`` exception is raised if data has invalid format, or if ...
def _execute(self, command, data=None, unpack=True): """ Private method to execute command. Args: command(Command): The defined command. data(dict): The uri variable and body. uppack(bool): If unpack value from result. Returns: The unwrapped valu...
def _unwrap_el(self, value): """Convert {'Element': 1234} to WebElement Object Args: value(str|list|dict): The value field in the json response. Returns: The unwrapped value. """ if isinstance(value, dict) and 'ELEMENT' in value: element_id =...
def _wrap_el(self, value): """Convert WebElement Object to {'Element': 1234} Args: value(str|list|dict): The local value. Returns: The wrapped value. """ if isinstance(value, dict): return {k: self._wrap_el(v) for k, v in value.items()} ...
def init(self): """Create Session by desiredCapabilities Support: Android iOS Web(WebView) Returns: WebDriver Object. """ resp = self._execute(Command.NEW_SESSION, { 'desiredCapabilities': self.desired_capabilities }, False) r...
def switch_to_window(self, window_name): """Switch to the given window. Support: Web(WebView) Args: window_name(str): The window to change focus to. Returns: WebDriver Object. """ data = { 'name': window_name } ...
def set_window_size(self, width, height, window_handle='current'): """Sets the width and height of the current window. Support: Web(WebView) Args: width(int): the width in pixels. height(int): the height in pixels. window_handle(str): Identifier ...
def set_window_position(self, x, y, window_handle='current'): """Sets the x,y position of the current window. Support: Web(WebView) Args: x(int): the x-coordinate in pixels. y(int): the y-coordinate in pixels. window_handle(str): Identifier of wi...
def move_to(self, element, x=0, y=0): """Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead. Move the mouse by an offset of the specificed element. Support: Android Args: element(WebElement): WebElement Object. x(float): X of...
def flick(self, element, x, y, speed): """Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead. Flick on the touch screen using finger motion events. This flickcommand starts at a particulat screen location. Support: iOS Args: ...
def switch_to_frame(self, frame_reference=None): """Switches focus to the specified frame, by index, name, or webelement. Support: Web(WebView) Args: frame_reference(None|int|WebElement): The identifier of the frame to switch to. None mea...
def execute_script(self, script, *args): """Execute JavaScript Synchronously in current context. Support: Web(WebView) Args: script: The JavaScript to execute. *args: Arguments for your JavaScript. Returns: Returns the return value of th...
def execute_async_script(self, script, *args): """Execute JavaScript Asynchronously in current context. Support: Web(WebView) Args: script: The JavaScript to execute. *args: Arguments for your JavaScript. Returns: Returns the return valu...
def add_cookie(self, cookie_dict): """Set a cookie. Support: Web(WebView) Args: cookie_dict: A dictionary contain keys: "name", "value", ["path"], ["domain"], ["secure"], ["httpOnly"], ["expiry"]. Returns: WebElement Object. ...
def save_screenshot(self, filename, quietly = False): """Save the screenshot to local. Support: Android iOS Web(WebView) Args: filename(str): The path to save the image. quietly(bool): If True, omit the IOError when failed to save the image. ...
def element(self, using, value): """Find an element in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: WebElement Object. ...
def element_if_exists(self, using, value): """Check if an element in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return ...
def element_or_none(self, using, value): """Check if an element in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return El...
def elements(self, using, value): """Find elements in the current context. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return a List<Element ...
def wait_for( self, timeout=10000, interval=1000, asserter=lambda x: x): """Wait for driver till satisfy the given condition Support: Android iOS Web(WebView) Args: timeout(int): How long we should be retrying stuff. interval(int): How long b...
def wait_for_element( self, using, value, timeout=10000, interval=1000, asserter=is_displayed): """Wait for element till satisfy the given condition Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str)...
def wait_for_elements( self, using, value, timeout=10000, interval=1000, asserter=is_displayed): """Wait for elements till satisfy the given condition Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(st...
def from_object(cls, obj): """The factory method to create WebDriverResult from JSON Object. Args: obj(dict): The JSON Object returned by server. """ return cls( obj.get('sessionId', None), obj.get('status', 0), obj.get('value', None) ...
def raise_for_status(self): """Raise WebDriverException if returned status is not zero.""" if not self.status: return error = find_exception_by_code(self.status) message = None screen = None stacktrace = None if isinstance(self.value, str): ...
def add_element_extension_method(Klass): """Add element_by alias and extension' methods(if_exists/or_none).""" def add_element_method(Klass, using): locator = using.name.lower() find_element_name = "element_by_" + locator find_element_if_exists_name = "element_by_" + locator + "_if_exist...
def fluent(func): """Fluent interface decorator to return self if method return None.""" @wraps(func) def fluent_interface(instance, *args, **kwargs): ret = func(instance, *args, **kwargs) if ret is not None: return ret return instance return fluent_interface
def value_to_key_strokes(value): """Convert value to a list of key strokes >>> value_to_key_strokes(123) ['123'] >>> value_to_key_strokes('123') ['123'] >>> value_to_key_strokes([1, 2, 3]) ['123'] >>> value_to_key_strokes(['1', '2', '3']) ['123'] Args: value(int|str|list...
def value_to_single_key_strokes(value): """Convert value to a list of key strokes >>> value_to_single_key_strokes(123) ['1', '2', '3'] >>> value_to_single_key_strokes('123') ['1', '2', '3'] >>> value_to_single_key_strokes([1, 2, 3]) ['1', '2', '3'] >>> value_to_single_key_strokes(['1', '...
def check_unused_args(self, used_args, args, kwargs): """Implement the check_unused_args in superclass.""" for k, v in kwargs.items(): if k in used_args: self._used_kwargs.update({k: v}) else: self._unused_kwargs.update({k: v})
def vformat(self, format_string, args, kwargs): """Clear used and unused dicts before each formatting.""" self._used_kwargs = {} self._unused_kwargs = {} return super(MemorizeFormatter, self).vformat(format_string, args, kwargs)
def format_map(self, format_string, mapping): """format a string by a map Args: format_string(str): A format string mapping(dict): A map to format the string Returns: A formatted string. Raises: KeyError: if key is not provided by the gi...
def find_exception_by_code(code): """Find name of exception by WebDriver defined error code. Args: code(str): Error code defined in protocol. Returns: The error name defined in protocol. """ errorName = None for error in WebDriverError: if error.value.code == code: ...
def execute(self, command, data={}): """Format the endpoint url by data and then request the remote server. Args: command(Command): WebDriver command to be executed. data(dict): Data fulfill the uri template and json body. Returns: A dict represent the json ...
def _request(self, method, url, body): """Internal method to send request to the remote server. Args: method(str): HTTP Method(GET/POST/PUT/DELET/HEAD). url(str): The request url. body(dict): The JSON object to be sent. Returns: A dict represent ...
def _execute(self, command, data=None, unpack=True): """Private method to execute command with data. Args: command(Command): The defined command. data(dict): The uri variable and body. Returns: The unwrapped value field in the json response. """ ...
def element(self, using, value): """find an element in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: WebElement Object. ...
def element_or_none(self, using, value): """Check if an element in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return El...
def elements(self, using, value): """find elements in the current element. Support: Android iOS Web(WebView) Args: using(str): The element location strategy. value(str): The value of the location strategy. Returns: Return a List<Element ...
def move_to(self, x=0, y=0): """Deprecated use element.touch('drag', { toX, toY, duration(s) }) instead. Move the mouse by an offset of the specificed element. Support: Android Args: x(float): X offset to move to, relative to the top-le...
def flick(self, x, y, speed): """Deprecated use touch('drag', { fromX, fromY, toX, toY, duration(s) }) instead. Flick on the touch screen using finger motion events. This flickcommand starts at a particulat screen location. Support: iOS Args: x(f...
def touch(self, name, args=None): """Apply touch actions on devices. Such as, tap/doubleTap/press/pinch/rotate/drag. See more on https://github.com/alibaba/macaca/issues/366. Support: Android iOS Args: name(str): Name of the action args(dict): Ar...
def is_displayed(target): """Assert whether the target is displayed Args: target(WebElement): WebElement Object. Returns: Return True if the element is displayed or return False otherwise. """ is_displayed = getattr(target, 'is_displayed', None) if not is_displayed or not calla...
def PlugIn(self): """Take next available controller id and plug in to Virtual USB Bus""" ids = self.available_ids() if len(ids) == 0: raise MaxInputsReachedError('Max Inputs Reached') self.id = ids[0] _xinput.PlugIn(self.id) while self.id in self.available_i...
def UnPlug(self, force=False): """Unplug controller from Virtual USB Bus and free up ID""" if force: _xinput.UnPlugForce(c_uint(self.id)) else: _xinput.UnPlug(c_uint(self.id)) while self.id not in self.available_ids(): if self.id == 0: ...
def set_value(self, control, value=None): """Set a value on the controller If percent is True all controls will accept a value between -1.0 and 1.0 If not then: Triggers are 0 to 255 Axis are -32768 to 32767 Control List: AxisLx , Left Stick X-Axis AxisLy ...
def main(): """Test the functionality of the rController object""" import time print('Testing controller in position 1:') print('Running 3 x 3 seconds tests') # Initialise Controller con = rController(1) # Loop printing controller state and buttons held for i in range(3): prin...
def gamepad(self): """Returns the current gamepad state. Buttons pressed is shown as a raw integer value. Use rController.buttons for a list of buttons pressed. """ state = _xinput_state() _xinput.XInputGetState(self.ControllerID - 1, pointer(state)) self.dwPacketNumber =...
def buttons(self): """Returns a list of buttons currently pressed""" return [name for name, value in rController._buttons.items() if self.gamepad.wButtons & value == value]
def maybe_decode_header(header): """ Decodes an encoded 7-bit ASCII header value into it's actual value. """ value, encoding = decode_header(header)[0] if encoding: return value.decode(encoding) else: return value
def autodiscover(): """ Imports all available previews classes. """ from django.conf import settings for application in settings.INSTALLED_APPS: module = import_module(application) if module_has_submodule(module, 'emails'): emails = import_module('%s.emails' % applicatio...
def register(self, cls): """ Adds a preview to the index. """ preview = cls(site=self) logger.debug('Registering %r with %r', preview, self) index = self.__previews.setdefault(preview.module, {}) index[cls.__name__] = preview
def detail_view(self, request, module, preview): """ Looks up a preview in the index, returning a detail view response. """ try: preview = self.__previews[module][preview] except KeyError: raise Http404 # The provided module/preview does not exist in the ...
def url(self): """ The URL to access this preview. """ return reverse('%s:detail' % URL_NAMESPACE, kwargs={ 'module': self.module, 'preview': type(self).__name__, })
def detail_view(self, request): """ Renders the message view to a response. """ context = { 'preview': self, } kwargs = {} if self.form_class: if request.GET: form = self.form_class(data=request.GET) else: ...
def split_docstring(value): """ Splits the docstring of the given value into it's summary and body. :returns: a 2-tuple of the format ``(summary, body)`` """ docstring = textwrap.dedent(getattr(value, '__doc__', '')) if not docstring: return None pieces = docstring.strip().split('\...
def render_to_message(self, extra_context=None, **kwargs): """ Renders and returns an unsent message with the provided context. Any extra keyword arguments passed will be passed through as keyword arguments to the message constructor. :param extra_context: Any additional contex...
def send(self, extra_context=None, **kwargs): """ Renders and sends an email message. All keyword arguments other than ``extra_context`` are passed through as keyword arguments when constructing a new :attr:`message_class` instance for this message. This method exists p...
def render_subject(self, context): """ Renders the message subject for the given context. The context data is automatically unescaped to avoid rendering HTML entities in ``text/plain`` content. :param context: The context to use when rendering the subject template. :typ...
def render_to_message(self, extra_context=None, *args, **kwargs): """ Renders and returns an unsent message with the given context. Any extra keyword arguments passed will be passed through as keyword arguments to the message constructor. :param extra_context: Any additional co...
def timestamp(_, dt): 'get microseconds since 2000-01-01 00:00' # see http://stackoverflow.com/questions/2956886/ dt = util.to_utc(dt) unix_timestamp = calendar.timegm(dt.timetuple()) # timetuple doesn't maintain microseconds # see http://stackoverflow.com/a/14369386/519015 val = ((unix_time...
def numeric(_, n): """ NBASE = 1000 ndigits = total number of base-NBASE digits weight = base-NBASE weight of first digit sign = 0x0000 if positive, 0x4000 if negative, 0xC000 if nan dscale = decimal digits after decimal place """ try: nt = n.as_tuple() except AttributeError:...
def set_default_subparser(self, name, args=None): """default subparser selection. Call after setup, just before parse_args() name: is the name of the subparser to call by default args: if set is the argument list handed to parse_args() , tested with 2.7, 3.2, 3.3, 3.4 it works with 2.6 assuming arg...
def execute_from_command_line(argv=None): """ A simple method that runs a ManagementUtility. """ parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--monitors-dir', default=MONITORS_DIR) parser.add_argument('--alerts-dir', default=ALERTS_DIR) parser.add_argument('--co...