INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Populates self._user_dn with the distinguished name of our user. This will either construct the DN from a template in AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it. If we have to search, we'll cache the DN.
def _load_user_dn(self): """ Populates self._user_dn with the distinguished name of our user. This will either construct the DN from a template in AUTH_LDAP_USER_DN_TEMPLATE or connect to the server and search for it. If we have to search, we'll cache the DN. """ ...
Searches the directory for a user matching AUTH_LDAP_USER_SEARCH. Populates self._user_dn and self._user_attrs.
def _search_for_user_dn(self): """ Searches the directory for a user matching AUTH_LDAP_USER_SEARCH. Populates self._user_dn and self._user_attrs. """ search = self.settings.USER_SEARCH if search is None: raise ImproperlyConfigured( "AUTH_LDAP_...
Returns True if the group requirement (AUTH_LDAP_REQUIRE_GROUP) is met. Always returns True if AUTH_LDAP_REQUIRE_GROUP is None.
def _check_required_group(self): """ Returns True if the group requirement (AUTH_LDAP_REQUIRE_GROUP) is met. Always returns True if AUTH_LDAP_REQUIRE_GROUP is None. """ required_group_dn = self.settings.REQUIRE_GROUP if required_group_dn is not None: if not i...
Returns True if the negative group requirement (AUTH_LDAP_DENY_GROUP) is met. Always returns True if AUTH_LDAP_DENY_GROUP is None.
def _check_denied_group(self): """ Returns True if the negative group requirement (AUTH_LDAP_DENY_GROUP) is met. Always returns True if AUTH_LDAP_DENY_GROUP is None. """ denied_group_dn = self.settings.DENY_GROUP if denied_group_dn is not None: is_member = se...
Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER.
def _get_or_create_user(self, force_populate=False): """ Loads the User model object from the database or creates it if it doesn't exist. Also populates the fields, subject to AUTH_LDAP_ALWAYS_UPDATE_USER. """ save_user = False username = self.backend.ldap_to_dja...
Converts one or more group DNs to an LDAPGroupQuery. group_dns may be a string, a non-empty list or tuple of strings, or an LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple will be joined with the | operator.
def _normalize_group_dns(self, group_dns): """ Converts one or more group DNs to an LDAPGroupQuery. group_dns may be a string, a non-empty list or tuple of strings, or an LDAPGroupQuery. The result will be an LDAPGroupQuery. A list or tuple will be joined with the | operator. ...
Validates the group mirroring settings and converts them as necessary.
def _normalize_mirror_settings(self): """ Validates the group mirroring settings and converts them as necessary. """ def malformed_mirror_groups_except(): return ImproperlyConfigured( "{} must be a collection of group names".format( self.s...
Mirrors the user's LDAP groups in the Django database and updates the user's membership.
def _mirror_groups(self): """ Mirrors the user's LDAP groups in the Django database and updates the user's membership. """ target_group_names = frozenset(self._get_groups().get_group_names()) current_group_names = frozenset( self._user.groups.values_list("name...
Returns an _LDAPUserGroups object, which can determine group membership.
def _get_groups(self): """ Returns an _LDAPUserGroups object, which can determine group membership. """ if self._groups is None: self._groups = _LDAPUserGroups(self) return self._groups
Binds to the LDAP server with AUTH_LDAP_BIND_DN and AUTH_LDAP_BIND_PASSWORD.
def _bind(self): """ Binds to the LDAP server with AUTH_LDAP_BIND_DN and AUTH_LDAP_BIND_PASSWORD. """ self._bind_as(self.settings.BIND_DN, self.settings.BIND_PASSWORD, sticky=True)
Binds to the LDAP server with the given credentials. This does not trap exceptions. If sticky is True, then we will consider the connection to be bound for the life of this object. If False, then the caller only wishes to test the credentials, after which the connection will be consider...
def _bind_as(self, bind_dn, bind_password, sticky=False): """ Binds to the LDAP server with the given credentials. This does not trap exceptions. If sticky is True, then we will consider the connection to be bound for the life of this object. If False, then the caller only wishe...
Returns our cached LDAPObject, which may or may not be bound.
def _get_connection(self): """ Returns our cached LDAPObject, which may or may not be bound. """ if self._connection is None: uri = self.settings.SERVER_URI if callable(uri): if func_supports_parameter(uri, "request"): uri = uri...
Loads the settings we need to deal with groups. Raises ImproperlyConfigured if anything's not right.
def _init_group_settings(self): """ Loads the settings we need to deal with groups. Raises ImproperlyConfigured if anything's not right. """ self._group_type = self.settings.GROUP_TYPE if self._group_type is None: raise ImproperlyConfigured( ...
Returns the set of Django group names that this user belongs to by virtue of LDAP group memberships.
def get_group_names(self): """ Returns the set of Django group names that this user belongs to by virtue of LDAP group memberships. """ if self._group_names is None: self._load_cached_attr("_group_names") if self._group_names is None: group_infos ...
Returns true if our user is a member of the given group.
def is_member_of(self, group_dn): """ Returns true if our user is a member of the given group. """ is_member = None # Normalize the DN group_dn = group_dn.lower() # If we have self._group_dns, we'll use it. Otherwise, we'll try to # avoid the cost of loa...
Returns a (cached) list of group_info structures for the groups that our user is a member of.
def _get_group_infos(self): """ Returns a (cached) list of group_info structures for the groups that our user is a member of. """ if self._group_infos is None: self._group_infos = self._group_type.user_groups( self._ldap_user, self._group_search ...
Memcache keys can't have spaces in them, so we'll remove them from the DN for maximum compatibility.
def _cache_key(self, attr_name): """ Memcache keys can't have spaces in them, so we'll remove them from the DN for maximum compatibility. """ dn = self._ldap_user.dn return valid_cache_key( "auth_ldap.{}.{}.{}".format(self.__class__.__name__, attr_name, dn) ...
Returns the configured ldap module.
def get_ldap(cls, global_options=None): """ Returns the configured ldap module. """ # Apply global LDAP options once if not cls._ldap_configured and global_options is not None: for opt, value in global_options.items(): ldap.set_option(opt, value) ...
Initializes and returns our logger instance.
def get_logger(cls): """ Initializes and returns our logger instance. """ if cls.logger is None: cls.logger = logging.getLogger("django_auth_ldap") cls.logger.addHandler(logging.NullHandler()) return cls.logger
Returns a new search object with additional search terms and-ed to the filter string. term_dict maps attribute names to assertion values. If you don't want the values escaped, pass escape=False.
def search_with_additional_terms(self, term_dict, escape=True): """ Returns a new search object with additional search terms and-ed to the filter string. term_dict maps attribute names to assertion values. If you don't want the values escaped, pass escape=False. """ term_...
Returns a new search object with filterstr and-ed to the original filter string. The caller is responsible for passing in a properly escaped string.
def search_with_additional_term_string(self, filterstr): """ Returns a new search object with filterstr and-ed to the original filter string. The caller is responsible for passing in a properly escaped string. """ filterstr = "(&{}{})".format(self.filterstr, filterstr) ...
Given the (DN, attrs) 2-tuple of an LDAP group, this returns the name of the Django group. This may return None to indicate that a particular LDAP group has no corresponding Django group. The base implementation returns the value of the cn attribute, or whichever attribute was given to ...
def group_name_from_info(self, group_info): """ Given the (DN, attrs) 2-tuple of an LDAP group, this returns the name of the Django group. This may return None to indicate that a particular LDAP group has no corresponding Django group. The base implementation returns the value o...
Searches for any group that is either the user's primary or contains the user as a member.
def user_groups(self, ldap_user, group_search): """ Searches for any group that is either the user's primary or contains the user as a member. """ groups = [] try: user_uid = ldap_user.attrs["uid"][0] if "gidNumber" in ldap_user.attrs: ...
Returns True if the group is the user's primary group or if the user is listed in the group's memberUid attribute.
def is_member(self, ldap_user, group_dn): """ Returns True if the group is the user's primary group or if the user is listed in the group's memberUid attribute. """ try: user_uid = ldap_user.attrs["uid"][0] try: is_member = ldap_user.conne...
This searches for all of a user's groups from the bottom up. In other words, it returns the groups that the user belongs to, the groups that those groups belong to, etc. Circular references will be detected and pruned.
def user_groups(self, ldap_user, group_search): """ This searches for all of a user's groups from the bottom up. In other words, it returns the groups that the user belongs to, the groups that those groups belong to, etc. Circular references will be detected and pruned. "...
Returns a function for aggregating a sequence of sub-results.
def aggregator(self): """ Returns a function for aggregating a sequence of sub-results. """ if self.connector == self.AND: aggregator = all elif self.connector == self.OR: aggregator = any else: raise ValueError(self.connector) ...
Generates the query result for each child.
def _resolve_children(self, ldap_user, groups): """ Generates the query result for each child. """ for child in self.children: if isinstance(child, LDAPGroupQuery): yield child.resolve(ldap_user, groups) else: yield groups.is_member...
Makes a list of positions and position commands from the tree
def gather_positions(tree): """Makes a list of positions and position commands from the tree""" pos = {'data-x': 'r0', 'data-y': 'r0', 'data-z': 'r0', 'data-rotate-x': 'r0', 'data-rotate-y': 'r0', 'data-rotate-z': 'r0', 'data-scale': 'r0', ...
Calculates position information
def calculate_positions(positions): """Calculates position information""" current_position = {'data-x': 0, 'data-y': 0, 'data-z': 0, 'data-rotate-x': 0, 'data-rotate-y': 0, 'data-rotate-z': 0,...
Updates the tree with new positions
def update_positions(tree, positions): """Updates the tree with new positions""" for step, pos in zip(tree.findall('step'), positions): for key in sorted(pos): value = pos.get(key) if key.endswith("-rel"): abs_key = key[:key.index("-rel")] if valu...
Position the slides in the tree
def position_slides(tree): """Position the slides in the tree""" positions = gather_positions(tree) positions = calculate_positions(positions) update_positions(tree, positions)
Makes a copy of a node with the same attributes and text, but no children.
def copy_node(node): """Makes a copy of a node with the same attributes and text, but no children.""" element = node.makeelement(node.tag) element.text = node.text element.tail = node.tail for key, value in node.items(): element.set(key, value) return element
Copies a resource file and returns the source path for monitoring
def copy_resource(self, resource, targetdir): """Copies a resource file and returns the source path for monitoring""" final_path = resource.final_path() if final_path[0] == '/' or (':' in final_path) or ('?' in final_path): # Absolute path or URI: Do nothing return ...
Start the server. Do nothing if server is already running. This function will block if no_block is not set to True.
def start(self): """Start the server. Do nothing if server is already running. This function will block if no_block is not set to True. """ if not self.is_run: # set class attribute ThreadingTCPServer.address_family = socket.AF_INET6 if self.ipv6 else soc...
Generates the presentation and returns a list of files used
def generate(args): """Generates the presentation and returns a list of files used""" source_files = {args.presentation} # Parse the template info template_info = Template(args.template) if args.css: presentation_dir = os.path.split(args.presentation)[0] target_path = os.path.relpa...
Stop the server. Do nothing if server is already not running.
def stop(self): """Stop the server. Do nothing if server is already not running. """ if self.is_run: self._service.shutdown() self._service.server_close()
Get or set host (IPv4/IPv6 or hostname like 'plc.domain.net') :param hostname: hostname or IPv4/IPv6 address or None for get value :type hostname: str or None :returns: hostname or None if set fail :rtype: str or None
def host(self, hostname=None): """Get or set host (IPv4/IPv6 or hostname like 'plc.domain.net') :param hostname: hostname or IPv4/IPv6 address or None for get value :type hostname: str or None :returns: hostname or None if set fail :rtype: str or None """ if (hos...
Get or set TCP port :param port: TCP port number or None for get value :type port: int or None :returns: TCP port or None if set fail :rtype: int or None
def port(self, port=None): """Get or set TCP port :param port: TCP port number or None for get value :type port: int or None :returns: TCP port or None if set fail :rtype: int or None """ if (port is None) or (port == self.__port): return self.__port ...
Get or set unit ID field :param unit_id: unit ID (0 to 255) or None for get value :type unit_id: int or None :returns: unit ID or None if set fail :rtype: int or None
def unit_id(self, unit_id=None): """Get or set unit ID field :param unit_id: unit ID (0 to 255) or None for get value :type unit_id: int or None :returns: unit ID or None if set fail :rtype: int or None """ if unit_id is None: return self.__unit_id ...
Get or set timeout field :param timeout: socket timeout in seconds or None for get value :type timeout: float or None :returns: timeout or None if set fail :rtype: float or None
def timeout(self, timeout=None): """Get or set timeout field :param timeout: socket timeout in seconds or None for get value :type timeout: float or None :returns: timeout or None if set fail :rtype: float or None """ if timeout is None: return self._...
Get or set debug mode :param state: debug state or None for get value :type state: bool or None :returns: debug state or None if set fail :rtype: bool or None
def debug(self, state=None): """Get or set debug mode :param state: debug state or None for get value :type state: bool or None :returns: debug state or None if set fail :rtype: bool or None """ if state is None: return self.__debug self.__deb...
Get or set automatic TCP connect mode :param state: auto_open state or None for get value :type state: bool or None :returns: auto_open state or None if set fail :rtype: bool or None
def auto_open(self, state=None): """Get or set automatic TCP connect mode :param state: auto_open state or None for get value :type state: bool or None :returns: auto_open state or None if set fail :rtype: bool or None """ if state is None: return sel...
Get or set automatic TCP close mode (after each request) :param state: auto_close state or None for get value :type state: bool or None :returns: auto_close state or None if set fail :rtype: bool or None
def auto_close(self, state=None): """Get or set automatic TCP close mode (after each request) :param state: auto_close state or None for get value :type state: bool or None :returns: auto_close state or None if set fail :rtype: bool or None """ if state is None: ...
Get or set modbus mode (TCP or RTU) :param mode: mode (MODBUS_TCP/MODBUS_RTU) to set or None for get value :type mode: int :returns: mode or None if set fail :rtype: int or None
def mode(self, mode=None): """Get or set modbus mode (TCP or RTU) :param mode: mode (MODBUS_TCP/MODBUS_RTU) to set or None for get value :type mode: int :returns: mode or None if set fail :rtype: int or None """ if mode is None: return self.__mode ...
Connect to modbus server (open TCP connection) :returns: connect status (True if open) :rtype: bool
def open(self): """Connect to modbus server (open TCP connection) :returns: connect status (True if open) :rtype: bool """ # restart TCP if already open if self.is_open(): self.close() # init socket and connect # list available sockets on the ...
Close TCP connection :returns: close status (True for close/None if already close) :rtype: bool or None
def close(self): """Close TCP connection :returns: close status (True for close/None if already close) :rtype: bool or None """ if self.__sock: self.__sock.close() self.__sock = None return True else: return None
Modbus function READ_COILS (0x01) :param bit_addr: bit address (0 to 65535) :type bit_addr: int :param bit_nb: number of bits to read (1 to 2000) :type bit_nb: int :returns: bits list or None if error :rtype: list of bool or None
def read_coils(self, bit_addr, bit_nb=1): """Modbus function READ_COILS (0x01) :param bit_addr: bit address (0 to 65535) :type bit_addr: int :param bit_nb: number of bits to read (1 to 2000) :type bit_nb: int :returns: bits list or None if error :rtype: list of b...
Modbus function READ_INPUT_REGISTERS (0x04) :param reg_addr: register address (0 to 65535) :type reg_addr: int :param reg_nb: number of registers to read (1 to 125) :type reg_nb: int :returns: registers list or None if fail :rtype: list of int or None
def read_input_registers(self, reg_addr, reg_nb=1): """Modbus function READ_INPUT_REGISTERS (0x04) :param reg_addr: register address (0 to 65535) :type reg_addr: int :param reg_nb: number of registers to read (1 to 125) :type reg_nb: int :returns: registers list or None ...
Modbus function WRITE_SINGLE_COIL (0x05) :param bit_addr: bit address (0 to 65535) :type bit_addr: int :param bit_value: bit value to write :type bit_value: bool :returns: True if write ok or None if fail :rtype: bool or None
def write_single_coil(self, bit_addr, bit_value): """Modbus function WRITE_SINGLE_COIL (0x05) :param bit_addr: bit address (0 to 65535) :type bit_addr: int :param bit_value: bit value to write :type bit_value: bool :returns: True if write ok or None if fail :rtyp...
Modbus function WRITE_SINGLE_REGISTER (0x06) :param reg_addr: register address (0 to 65535) :type reg_addr: int :param reg_value: register value to write :type reg_value: int :returns: True if write ok or None if fail :rtype: bool or None
def write_single_register(self, reg_addr, reg_value): """Modbus function WRITE_SINGLE_REGISTER (0x06) :param reg_addr: register address (0 to 65535) :type reg_addr: int :param reg_value: register value to write :type reg_value: int :returns: True if write ok or None if f...
Modbus function WRITE_MULTIPLE_COILS (0x0F) :param bits_addr: bits address (0 to 65535) :type bits_addr: int :param bits_value: bits values to write :type bits_value: list :returns: True if write ok or None if fail :rtype: bool or None
def write_multiple_coils(self, bits_addr, bits_value): """Modbus function WRITE_MULTIPLE_COILS (0x0F) :param bits_addr: bits address (0 to 65535) :type bits_addr: int :param bits_value: bits values to write :type bits_value: list :returns: True if write ok or None if fai...
Modbus function WRITE_MULTIPLE_REGISTERS (0x10) :param regs_addr: registers address (0 to 65535) :type regs_addr: int :param regs_value: registers values to write :type regs_value: list :returns: True if write ok or None if fail :rtype: bool or None
def write_multiple_registers(self, regs_addr, regs_value): """Modbus function WRITE_MULTIPLE_REGISTERS (0x10) :param regs_addr: registers address (0 to 65535) :type regs_addr: int :param regs_value: registers values to write :type regs_value: list :returns: True if write...
Wait data available for socket read :returns: True if data available or None if timeout or socket error :rtype: bool or None
def _can_read(self): """Wait data available for socket read :returns: True if data available or None if timeout or socket error :rtype: bool or None """ if self.__sock is None: return None if select.select([self.__sock], [], [], self.__timeout)[0]: ...
Send data over current socket :param data: registers value to write :type data: str (Python2) or class bytes (Python3) :returns: True if send ok or None if error :rtype: bool or None
def _send(self, data): """Send data over current socket :param data: registers value to write :type data: str (Python2) or class bytes (Python3) :returns: True if send ok or None if error :rtype: bool or None """ # check link if self.__sock is None: ...
Receive data over current socket :param max_size: number of bytes to receive :type max_size: int :returns: receive data or None if error :rtype: str (Python2) or class bytes (Python3) or None
def _recv(self, max_size): """Receive data over current socket :param max_size: number of bytes to receive :type max_size: int :returns: receive data or None if error :rtype: str (Python2) or class bytes (Python3) or None """ # wait for read if not self._...
Receive data over current socket, loop until all bytes is receive (avoid TCP frag) :param size: number of bytes to receive :type size: int :returns: receive data or None if error :rtype: str (Python2) or class bytes (Python3) or None
def _recv_all(self, size): """Receive data over current socket, loop until all bytes is receive (avoid TCP frag) :param size: number of bytes to receive :type size: int :returns: receive data or None if error :rtype: str (Python2) or class bytes (Python3) or None """ ...
Send modbus frame :param frame: modbus frame to send (with MBAP for TCP/CRC for RTU) :type frame: str (Python2) or class bytes (Python3) :returns: number of bytes send or None if error :rtype: int or None
def _send_mbus(self, frame): """Send modbus frame :param frame: modbus frame to send (with MBAP for TCP/CRC for RTU) :type frame: str (Python2) or class bytes (Python3) :returns: number of bytes send or None if error :rtype: int or None """ # for auto_open mode, ...
Receive a modbus frame :returns: modbus frame body or None if error :rtype: str (Python2) or class bytes (Python3) or None
def _recv_mbus(self): """Receive a modbus frame :returns: modbus frame body or None if error :rtype: str (Python2) or class bytes (Python3) or None """ # receive # modbus TCP receive if self.__mode == const.MODBUS_TCP: # 7 bytes header (mbap) ...
Build modbus frame (add MBAP for Modbus/TCP, slave AD + CRC for RTU) :param fc: modbus function code :type fc: int :param body: modbus frame body :type body: str (Python2) or class bytes (Python3) :returns: modbus frame :rtype: str (Python2) or class bytes (Python3)
def _mbus_frame(self, fc, body): """Build modbus frame (add MBAP for Modbus/TCP, slave AD + CRC for RTU) :param fc: modbus function code :type fc: int :param body: modbus frame body :type body: str (Python2) or class bytes (Python3) :returns: modbus frame :rtype:...
Print modbus/TCP frame ('[header]body') or RTU ('body[CRC]') on stdout :param label: modbus function code :type label: str :param data: modbus frame :type data: str (Python2) or class bytes (Python3)
def _pretty_dump(self, label, data): """Print modbus/TCP frame ('[header]body') or RTU ('body[CRC]') on stdout :param label: modbus function code :type label: str :param data: modbus frame :type data: str (Python2) or class bytes (Python3) """ # split dat...
Add CRC to modbus frame (for RTU mode) :param frame: modbus RTU frame :type frame: str (Python2) or class bytes (Python3) :returns: modbus RTU frame with CRC :rtype: str (Python2) or class bytes (Python3)
def _add_crc(self, frame): """Add CRC to modbus frame (for RTU mode) :param frame: modbus RTU frame :type frame: str (Python2) or class bytes (Python3) :returns: modbus RTU frame with CRC :rtype: str (Python2) or class bytes (Python3) """ crc = struct.pack('<H', ...
Get the list of bits of val_int integer (default size is 16 bits) Return bits list, least significant bit first. Use list.reverse() if need. :param val_int: integer value :type val_int: int :param val_size: bit size of integer (word = 16, long = 32) (optional) :type val...
def get_bits_from_int(val_int, val_size=16): """Get the list of bits of val_int integer (default size is 16 bits) Return bits list, least significant bit first. Use list.reverse() if need. :param val_int: integer value :type val_int: int :param val_size: bit size of integer...
Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list :param big_endian: True for big endian/False for little ...
def word_list_to_long(val_list, big_endian=True): """Word list (16 bits int) to long list (32 bits int) By default word_list_to_long() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 16 bits int value :type val_list: list ...
Long list (32 bits int) to word list (16 bits int) By default long_list_to_word() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 32 bits int value :type val_list: list :param big_endian: True for big endian/False for little ...
def long_list_to_word(val_list, big_endian=True): """Long list (32 bits int) to word list (16 bits int) By default long_list_to_word() use big endian order. For use little endian, set big_endian param to False. :param val_list: list of 32 bits int value :type val_list: list ...
Compute CRC16 :param frame: frame :type frame: str (Python2) or class bytes (Python3) :returns: CRC16 :rtype: int
def crc16(frame): """Compute CRC16 :param frame: frame :type frame: str (Python2) or class bytes (Python3) :returns: CRC16 :rtype: int """ crc = 0xFFFF for index, item in enumerate(bytearray(frame)): next_byte = item crc ^= next_byte for i in range(8): ...
Wrap text to length characters, breaking when target length is reached, taking into account character width. Used to wrap lines which cannot be wrapped on whitespace.
def _wc_hard_wrap(line, length): """ Wrap text to length characters, breaking when target length is reached, taking into account character width. Used to wrap lines which cannot be wrapped on whitespace. """ chars = [] chars_len = 0 for char in line: char_len = wcwidth(char) ...
Wrap text to given length, breaking on whitespace and taking into account character width. Meant for use on a single line or paragraph. Will destroy spacing between words and paragraphs and any indentation.
def wc_wrap(text, length): """ Wrap text to given length, breaking on whitespace and taking into account character width. Meant for use on a single line or paragraph. Will destroy spacing between words and paragraphs and any indentation. """ line_words = [] line_len = 0 words = re....
Truncates text to given length, taking into account wide characters. If truncated, the last char is replaced by an elipsis.
def trunc(text, length): """ Truncates text to given length, taking into account wide characters. If truncated, the last char is replaced by an elipsis. """ if length < 1: raise ValueError("length should be 1 or larger") # Remove whitespace first so no unneccesary truncation is done. ...
Pads text to given length, taking into account wide characters.
def pad(text, length): """Pads text to given length, taking into account wide characters.""" text_length = wcswidth(text) if text_length < length: return text + ' ' * (length - text_length) return text
Makes text fit the given length by padding or truncating it.
def fit_text(text, length): """Makes text fit the given length by padding or truncating it.""" text_length = wcswidth(text) if text_length > length: return trunc(text, length) if text_length < length: return pad(text, length) return text
Attempt to extract an error message from response body
def _get_error_message(response): """Attempt to extract an error message from response body""" try: data = response.json() if "error_description" in data: return data['error_description'] if "error" in data: return data['error'] except Exception: pass ...
Creates a config file. Attempts to load data from legacy config files if they exist.
def make_config(path): """Creates a config file. Attempts to load data from legacy config files if they exist. """ apps, user = load_legacy_config() apps = {a.instance: a._asdict() for a in apps} users = {user_id(user): user._asdict()} if user else {} active_user = user_id(user) if user el...
Posts a new status. https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#posting-a-new-status
def post_status( app, user, status, visibility='public', media_ids=None, sensitive=False, spoiler_text=None, in_reply_to_id=None ): """ Posts a new status. https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#posting-a-new-status """ # Idempote...
Deletes a status with given ID. https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#deleting-a-status
def delete_status(app, user, status_id): """ Deletes a status with given ID. https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#deleting-a-status """ return http.delete(app, user, '/api/v1/statuses/{}'.format(status_id))
Given timeline response headers, returns the path to the next batch
def _get_next_path(headers): """Given timeline response headers, returns the path to the next batch""" links = headers.get('Link', '') matches = re.match('<([^>]+)>; rel="next"', links) if matches: parsed = urlparse(matches.group(1)) return "?".join([parsed.path, parsed.query])
Reply to the selected status
def reply(self): """Reply to the selected status""" status = self.get_selected_status() app, user = self.app, self.user if not app or not user: self.footer.draw_message("You must be logged in to reply", Color.RED) return compose_modal = ComposeModal(self....
Reblog or unreblog selected status.
def toggle_reblog(self): """Reblog or unreblog selected status.""" status = self.get_selected_status() assert status app, user = self.app, self.user if not app or not user: self.footer.draw_message("You must be logged in to reblog", Color.RED) return ...
Favourite or unfavourite selected status.
def toggle_favourite(self): """Favourite or unfavourite selected status.""" status = self.get_selected_status() assert status app, user = self.app, self.user if not app or not user: self.footer.draw_message("You must be logged in to favourite", Color.RED) ...
Move to the previous status in the timeline.
def select_previous(self): """Move to the previous status in the timeline.""" self.footer.clear_message() if self.selected == 0: self.footer.draw_message("Cannot move beyond first toot.", Color.GREEN) return old_index = self.selected new_index = self.sel...
Move to the next status in the timeline.
def select_next(self): """Move to the next status in the timeline.""" self.footer.clear_message() old_index = self.selected new_index = self.selected + 1 # Load more statuses if no more are available if self.selected + 1 >= len(self.statuses): self.fetch_nex...
Perform a full redraw of the UI.
def full_redraw(self): """Perform a full redraw of the UI.""" self.left.draw_statuses(self.statuses, self.selected) self.right.draw(self.get_selected_status()) self.header.draw(self.user) self.draw_footer_status()
Get the bottom-right corner of some text as would be drawn by draw_lines
def size_as_drawn(lines, screen_width): """Get the bottom-right corner of some text as would be drawn by draw_lines""" y = 0 x = 0 for line in lines: wrapped = list(wc_wrap(line, screen_width)) if len(wrapped) > 0: for wrapped_line in wrapped: x = len(wrapped_...
For a given account name, returns the Account object. Raises an exception if not found.
def _find_account(app, user, account_name): """For a given account name, returns the Account object. Raises an exception if not found. """ if not account_name: raise ConsoleError("Empty account name given") accounts = api.search_accounts(app, user, account_name) if account_name[0] == ...
When using broser login, username was not stored so look it up
def add_username(user, apps): """When using broser login, username was not stored so look it up""" if not user: return None apps = [a for a in apps if a.instance == user.instance] if not apps: return None from toot.api import verify_credentials creds = verify_credentials(apps....
Converts html to text, strips all tags.
def get_text(html): """Converts html to text, strips all tags.""" # Ignore warnings made by BeautifulSoup, if passed something that looks like # a file (e.g. a dot which matches current dict), it will warn that the file # should be opened instead of passing a filename. with warnings.catch_warnings(...
Attempt to convert html to plain text while keeping line breaks. Returns a list of paragraphs, each being a list of lines.
def parse_html(html): """Attempt to convert html to plain text while keeping line breaks. Returns a list of paragraphs, each being a list of lines. """ paragraphs = re.split("</?p[^>]*>", html) # Convert <br>s to line breaks and remove empty paragraphs paragraphs = [re.split("<br */?>", p) for ...
Given a Status contents in HTML, converts it into lines of plain text. Returns a generator yielding lines of content.
def format_content(content): """Given a Status contents in HTML, converts it into lines of plain text. Returns a generator yielding lines of content. """ paragraphs = parse_html(content) first = True for paragraph in paragraphs: if not first: yield "" for line in...
Lets user input multiple lines of text, terminated by EOF.
def multiline_input(): """Lets user input multiple lines of text, terminated by EOF.""" lines = [] while True: try: lines.append(input()) except EOFError: break return "\n".join(lines).strip()
Converts the table to a dict.
def to_dict(self): """Converts the table to a dict.""" return {"name": self.table_name, "kind": self.table_kind, "data": [r.to_dict() for r in self]}
Converts a string to a datetime.
def to_datetime(value): """Converts a string to a datetime.""" if value is None: return None if isinstance(value, six.integer_types): return parser.parse(value) return parser.isoparse(value)
Converts a string to a timedelta.
def to_timedelta(value): """Converts a string to a timedelta.""" if value is None: return None if isinstance(value, (six.integer_types, float)): return timedelta(microseconds=(float(value) / 10)) match = _TIMESPAN_PATTERN.match(value) if match: if match.group(1) == "-": ...
Enqueuing an ingest command from local files. :param pandas.DataFrame df: input dataframe to ingest. :param azure.kusto.ingest.IngestionProperties ingestion_properties: Ingestion properties.
def ingest_from_dataframe(self, df, ingestion_properties): """Enqueuing an ingest command from local files. :param pandas.DataFrame df: input dataframe to ingest. :param azure.kusto.ingest.IngestionProperties ingestion_properties: Ingestion properties. """ from pandas i...
Enqueuing an ingest command from local files. :param file_descriptor: a FileDescriptor to be ingested. :param azure.kusto.ingest.IngestionProperties ingestion_properties: Ingestion properties.
def ingest_from_file(self, file_descriptor, ingestion_properties): """Enqueuing an ingest command from local files. :param file_descriptor: a FileDescriptor to be ingested. :param azure.kusto.ingest.IngestionProperties ingestion_properties: Ingestion properties. """ file_descript...
Enqueuing an ingest command from azure blobs. :param azure.kusto.ingest.BlobDescriptor blob_descriptor: An object that contains a description of the blob to be ingested. :param azure.kusto.ingest.IngestionProperties ingestion_properties: Ingestion properties.
def ingest_from_blob(self, blob_descriptor, ingestion_properties): """Enqueuing an ingest command from azure blobs. :param azure.kusto.ingest.BlobDescriptor blob_descriptor: An object that contains a description of the blob to be ingested. :param azure.kusto.ingest.IngestionProperties ingestion_...
Converts Kusto tables into pandas DataFrame. :param azure.kusto.data._models.KustoResultTable table: Table received from the response. :return: pandas DataFrame. :rtype: pandas.DataFrame
def dataframe_from_result_table(table): import pandas as pd from ._models import KustoResultTable from dateutil.tz import UTC """Converts Kusto tables into pandas DataFrame. :param azure.kusto.data._models.KustoResultTable table: Table received from the response. :return: pandas DataFrame. ...
Converts array to a json string
def _convert_list_to_json(array): """ Converts array to a json string """ return json.dumps(array, skipkeys=False, allow_nan=False, indent=None, separators=(",", ":"))
Converts array to a json string
def _convert_dict_to_json(array): """ Converts array to a json string """ return json.dumps( array, skipkeys=False, allow_nan=False, indent=None, separators=(",", ":"), sort_keys=True, default=lambda o: o.__dict__, )
Assumed called on Travis, to prepare a package to be deployed This method prints on stdout for Travis. Return is obj to pass to sys.exit() directly
def travis_build_package(): """Assumed called on Travis, to prepare a package to be deployed This method prints on stdout for Travis. Return is obj to pass to sys.exit() directly """ travis_tag = os.environ.get("TRAVIS_TAG") if not travis_tag: print("TRAVIS_TAG environment variable is no...
Acquire tokens from AAD.
def acquire_authorization_header(self): """Acquire tokens from AAD.""" try: return self._acquire_authorization_header() except AdalError as error: if self._authentication_method is AuthenticationMethod.aad_username_password: kwargs = {"username": self._use...
Creates a KustoConnection string builder that will authenticate with AAD user name and password. :param str connection_string: Kusto connection string should by of the format: https://<clusterName>.kusto.windows.net :param str user_id: AAD user ID. :param str password: Corresponding ...
def with_aad_user_password_authentication(cls, connection_string, user_id, password, authority_id="common"): """Creates a KustoConnection string builder that will authenticate with AAD user name and password. :param str connection_string: Kusto connection string should by of the format: https...