text
stringlengths
18
773k
def _post_process_yaml_data(self, fixture_data: Dict[str, Dict[str, Any]], relationship_columns: Set[str], ) -> Tuple[Dict[str, Dict[str, Any]], List[str]]: """ Convert and normalize identifier strings to Ide...
def _ensure_env(self, env: Union[jinja2.Environment, None]): """ Make sure the jinja environment is minimally configured. """ if not env: env = jinja2.Environment() if not env.loader: env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename...
def _preloading_env(self): """ A "stripped" jinja environment. """ ctx = self.env.globals try: ctx['random_model'] = lambda *a, **kw: None ctx['random_models'] = lambda *a, **kw: None yield self.env finally: ctx['random_mode...
def get_instance(name, cls='system', storage=None, storage_parameters=None, unsecure=None, *args, **kwargs): """ Get a cloud object storage instance. Args: name (str): File name, path or URL. cls (str): Type of class to instantiate. 'raw', 'buffered' or 'system'...
def mount(storage=None, name='', storage_parameters=None, unsecure=None, extra_root=None): """ Mount a new storage. Args: storage (str): Storage name. name (str): File URL. If storage is not specified, URL scheme will be used as storage value. storage_parameter...
def _system_parameters(**kwargs): """ Returns system keyword arguments removing Nones. Args: kwargs: system keyword arguments. Returns: dict: system keyword arguments. """ return {key: value for key, value in kwargs.items() if (value is not None or value == {})}
def manual_argument_parsing(argv): """sadness because argparse doesn't quite do what we want.""" # Special case these for a better error message if not argv or argv == ['-h'] or argv == ['--help']: print_help_and_exit() try: dashdash_index = argv.index('--') except ValueError: ...
def make_entry_point(patches, original_entry_point): """Use this to make a console_script entry point for your application which applies patches. :param patches: iterable of pymonkey patches to apply. Ex: ('my-patch,) :param original_entry_point: Such as 'pip' """ def entry(argv=None): ...
def client(self): """ Storage client Returns: client """ if self._client is None: self._client = self._get_client() return self._client
def exists(self, path=None, client_kwargs=None, assume_exists=None): """ Return True if path refers to an existing path. Args: path (str): Path or URL. client_kwargs (dict): Client arguments. assume_exists (bool or None): This value define the value to return...
def getctime(self, path=None, client_kwargs=None, header=None): """ Return the creation time of path. Args: path (str): File path or URL. client_kwargs (dict): Client arguments. header (dict): Object header. Returns: float: The number of ...
def getmtime(self, path=None, client_kwargs=None, header=None): """ Return the time of last access of path. Args: path (str): File path or URL. client_kwargs (dict): Client arguments. header (dict): Object header. Returns: float: The numb...
def _get_time(header, keys, name): """ Get time from header Args: header (dict): Object header. keys (tuple of str): Header keys. name (str): Method name. Returns: float: The number of seconds since the epoch """ for key i...
def getsize(self, path=None, client_kwargs=None, header=None): """ Return the size, in bytes, of path. Args: path (str): File path or URL. client_kwargs (dict): Client arguments. header (dict): Object header. Returns: int: Size in bytes. ...
def _getsize_from_header(self, header): """ Return the size from header Args: header (dict): Object header. Returns: int: Size in bytes. """ # By default, assumes that information are in a standard HTTP header for key in self._SIZE_KEYS: ...
def isdir(self, path=None, client_kwargs=None, virtual_dir=True, assume_exists=None): """ Return True if path is an existing directory. Args: path (str): Path or URL. client_kwargs (dict): Client arguments. virtual_dir (bool): If True, checks if...
def isfile(self, path=None, client_kwargs=None, assume_exists=None): """ Return True if path is an existing regular file. Args: path (str): Path or URL. client_kwargs (dict): Client arguments. assume_exists (bool or None): This value define the value to retur...
def head(self, path=None, client_kwargs=None, header=None): """ Returns object HTTP header. Args: path (str): Path or URL. client_kwargs (dict): Client arguments. header (dict): Object header. Returns: dict: HTTP header. """ ...
def relpath(self, path): """ Get path relative to storage. args: path (str): Absolute path or URL. Returns: str: relative path. """ for root in self.roots: # Root is regex, convert to matching root string if isinstance(roo...
def is_locator(self, path, relative=False): """ Returns True if path refer to a locator. Depending the storage, locator may be a bucket or container name, a hostname, ... args: path (str): path or URL. relative (bool): Path is relative to current root. ...
def split_locator(self, path): """ Split the path into a pair (locator, path). args: path (str): Absolute path or URL. Returns: tuple of str: locator, path. """ relative = self.relpath(path) try: locator, tail = relative.split...
def make_dir(self, path, relative=False): """ Make a directory. Args: path (str): Path or URL. relative (bool): Path is relative to current root. """ if not relative: path = self.relpath(path) self._make_dir(self.get_client_kwargs(self...
def remove(self, path, relative=False): """ Remove an object. Args: path (str): Path or URL. relative (bool): Path is relative to current root. """ if not relative: path = self.relpath(path) self._remove(self.get_client_kwargs(path))
def ensure_dir_path(self, path, relative=False): """ Ensure the path is a dir path. Should end with '/' except for schemes and locators. Args: path (str): Path or URL. relative (bool): Path is relative to current root. Returns: path: dir pat...
def list_objects(self, path='', relative=False, first_level=False, max_request_entries=None): """ List objects. Args: path (str): Path or URL. relative (bool): Path is relative to current root. first_level (bool): It True, returns only fi...
def stat(self, path=None, client_kwargs=None, header=None): """ Get the status of an object. Args: path (str): File path or URL. client_kwargs (dict): Client arguments. header (dict): Object header. Returns: os.stat_result: Stat result ob...
def init(uri=None, alembic_ini=None, engine=None, create=False): """ Initialize a connection. Create tables if requested.""" if uri and engine: raise ValueError("uri and engine cannot both be specified") if uri is None and not engine: uri = 'sqlite:////tmp/datanommer.db' log.warni...
def add(envelope): """ Take a dict-like fedmsg envelope and store the headers and message in the table. """ message = envelope['body'] timestamp = message.get('timestamp', None) try: if timestamp: timestamp = datetime.datetime.utcfromtimestamp(timestamp) else: ...
def get_or_create(cls, name): """ Return the instance of the class with the specified name. If it doesn't already exist, create it. """ obj = cls.query.filter_by(name=name).one_or_none() if obj: return obj try: with session.begin_nested(): ...
def grep(cls, start=None, end=None, page=1, rows_per_page=100, order="asc", msg_id=None, users=None, not_users=None, packages=None, not_packages=None, categories=None, not_categories=None, topics=None, not_topics=None, contains=N...
def isdir(path): """ Return True if path is an existing directory. Equivalent to "os.path.isdir". Args: path (path-like object): Path or URL. Returns: bool: True if directory exists. """ system = get_instance(path) # User may use directory path without trailing '/' ...
def relpath(path, start=None): """ Return a relative file path to path either from the current directory or from an optional start directory. For storage objects, "path" and "start" are relative to storage root. "/" are not stripped on storage objects path. The ending slash is required on ...
def samefile(path1, path2): """ Return True if both pathname arguments refer to the same file or directory. Equivalent to "os.path.samefile". Args: path1 (path-like object): Path or URL. path2 (path-like object): Path or URL. Returns: bool: True if same file or directory. ...
def splitdrive(path): """ Split the path into a pair (drive, tail) where drive is either a mount point or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path. Equivalent to "os.path.split...
def handle_os_exceptions(): """ Handles pycosio exceptions and raise standard OS exceptions. """ try: yield # Convert pycosio exception to equivalent OSError except ObjectException: exc_type, exc_value, _ = exc_info() raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value...
def listdir(path='.'): """ Return a list containing the names of the entries in the directory given by path. Equivalent to "os.listdir". Args: path (path-like object): Path or URL. Returns: list of str: Entries names. """ return [name.rstrip('/') for name, _ in ...
def makedirs(name, mode=0o777, exist_ok=False): """ Super-mkdir; create a leaf directory and all intermediate ones. Works like mkdir, except that any intermediate path segment (not just the rightmost) will be created if it does not exist. Equivalent to "os.makedirs". Args: name (path-l...
def mkdir(path, mode=0o777, dir_fd=None): """ Create a directory named path with numeric mode mode. Equivalent to "os.mkdir". Args: path (path-like object): Path or URL. mode (int): The mode parameter is passed to os.mkdir(); see the os.mkdir() description for how it is int...
def remove(path, dir_fd=None): """ Remove a file. Equivalent to "os.remove" and "os.unlink". Args: path (path-like object): Path or URL. dir_fd: directory descriptors; see the os.remove() description for how it is interpreted. Not supported on cloud storage obje...
def rmdir(path, dir_fd=None): """ Remove a directory. Equivalent to "os.rmdir". Args: path (path-like object): Path or URL. dir_fd: directory descriptors; see the os.rmdir() description for how it is interpreted. Not supported on cloud storage objects. """ ...
def scandir(path='.'): """ Return an iterator of os.DirEntry objects corresponding to the entries in the directory given by path. The entries are yielded in arbitrary order, and the special entries '.' and '..' are not included. Equivalent to "os.scandir". Args: path (path-like object)...
def _scandir_generator(is_bytes, scandir_path, system): """ scandir generator Args: is_bytes (bool): True if DirEntry must handle path as bytes. scandir_path (str): Path. system (pycosio._core.io_system.SystemBase subclass): Storage system. Yields: DirEntry:...
def name(self): """ The entry’s base filename, relative to the scandir() path argument. Returns: str: name. """ name = self._name.rstrip('/') if self._bytes_path: name = fsencode(name) return name
def path(self): """ The entry’s full path name: equivalent to os.path.join(scandir_path, entry.name) where scandir_path is the scandir() path argument. The path is only absolute if the scandir() path argument was absolute. Returns: str: name. """ ...
def is_dir(self, follow_symlinks=True): """ Return True if this entry is a directory or a symbolic link pointing to a directory; return False if the entry is or points to any other kind of file, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. ...
def is_file(self, follow_symlinks=True): """ Return True if this entry is a file or a symbolic link pointing to a file; return False if the entry is or points to a directory or other non-file entry, or if it doesn’t exist anymore. The result is cached on the os.DirEntry object. ...
def stat(self, follow_symlinks=True): """ Return a stat_result object for this entry. The result is cached on the os.DirEntry object. Args: follow_symlinks (bool): Follow symlinks. Not supported on cloud storage objects. Returns: os.stat...
def close(self): """ Flush the write buffers of the stream if applicable and close the object. """ if self._writable and not self._closed: self._closed = True with self._seek_lock: self._flush_raw_or_buffered() if self._seek: ...
def flush(self): """ Flush the write buffers of the stream if applicable. """ if self._writable: with self._seek_lock: self._flush_raw_or_buffered() # Clear the buffer self._write_buffer = bytearray(self._buffer_size) ...
def _flush_raw_or_buffered(self): """ Flush using raw of buffered methods. """ # Flush only if bytes written # This avoid no required process/thread # creation and network call. # This step is performed by raw stream. if self._buffer_seek and self._seek: ...
def peek(self, size=-1): """ Return bytes from the stream without advancing the position. Args: size (int): Number of bytes to read. -1 to read the full stream. Returns: bytes: bytes read """ if not self._readable: rai...
def _preload_range(self): """Preload data for reading""" queue = self._read_queue size = self._buffer_size start = self._seek end = int(start + size * self._max_buffers) workers_submit = self._workers.submit indexes = tuple(range(start, end, size)) # Drop...
def read(self, size=-1): """ Read and return up to size bytes, with at most one call to the underlying raw stream’s. Use at most one call to the underlying raw stream’s read method. Args: size (int): Number of bytes to read. -1 to read the stream unt...
def readinto(self, b): """ Read bytes into a pre-allocated, writable bytes-like object b, and return the number of bytes read. Args: b (bytes-like object): buffer. Returns: int: number of bytes read """ if not self._readable: ...
def seek(self, offset, whence=SEEK_SET): """ Change the stream position to the given byte offset. Args: offset: Offset is interpreted relative to the position indicated by whence. whence: The default value for whence is SEEK_SET. Values fo...
def write(self, b): """ Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written. Args: b (bytes-like object): Bytes to write. Returns: int: The number of bytes written. """ if not self._w...
def create(content, error='H', version=None, mode=None, encoding=None): """When creating a QR code only the content to be encoded is required, all the other properties of the code will be guessed based on the contents given. This function will return a :class:`QRCode` object. Unless you are familiar wi...
def _detect_content_type(self, content, encoding): """This method tries to auto-detect the type of the data. It first tries to see if the data is a valid integer, in which case it returns numeric. Next, it tests the data to see if it is 'alphanumeric.' QR Codes use a special table with v...
def _pick_best_fit(self, content): """This method return the smallest possible QR code version number that will fit the specified data with the given error level. """ import math for version in range(1, 41): #Get the maximum possible capacity capa...
def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255), background=(255, 255, 255, 255), quiet_zone=4): """Displays this QR code. This method is mainly intended for debugging purposes. This method saves the output of the :py:meth:`png` method (with a default scaling...
def get_png_size(self, scale=1, quiet_zone=4): """This is method helps users determine what *scale* to use when creating a PNG of this QR code. It is meant mostly to be used in the console to help the user determine the pixel size of the code using various scales. This method wi...
def png(self, file, scale=1, module_color=(0, 0, 0, 255), background=(255, 255, 255, 255), quiet_zone=4): """This method writes the QR code out as an PNG image. The resulting PNG has a bit depth of 1. The file parameter is used to specify where to write the image to. It can either be...
def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255), background=(255, 255, 255, 255), quiet_zone=4): """This method uses the png render and returns the PNG image encoded as base64 string. This can be useful for creating dynamic PNG images for web developmen...
def xbm(self, scale=1, quiet_zone=4): """Returns a string representing an XBM image of the QR code. The XBM format is a black and white image format that looks like a C header file. Because displaying QR codes in Tkinter is the primary use case for this renderer, this m...
def svg(self, file, scale=1, module_color='#000', background=None, quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode', lineclass='pyqrline', omithw=False, debug=False): """This method writes the QR code out as an SVG document. The code is drawn by...
def eps(self, file, scale=1, module_color=(0, 0, 0), background=None, quiet_zone=4): """This method writes the QR code out as an EPS document. The code is drawn by only writing the data modules corresponding to a 1. They are drawn using a line, such that contiguous modules in a row ...
def terminal(self, module_color='default', background='reverse', quiet_zone=4): """This method returns a string containing ASCII escape codes, such that if printed to a compatible terminal, it will display a vaild QR code. The code is printed using ASCII escape codes tha...
def _get_writable(stream_or_path, mode): """This method returns a tuple containing the stream and a flag to indicate if the stream should be automatically closed. The `stream_or_path` parameter is returned if it is an open writable stream. Otherwise, it treats the `stream_or_path` parameter as a file p...
def _get_png_size(version, scale, quiet_zone=4): """See: QRCode.get_png_size This function was abstracted away from QRCode to allow for the output of QR codes during the build process, i.e. for debugging. It works just the same except you must specify the code's version. This is needed to calculate...
def _terminal(code, module_color='default', background='reverse', quiet_zone=4): """This method returns a string containing ASCII escape codes, such that if printed to a terminal, it will display a vaild QR code. The module_color and the background color should be keys in the tables.term_colors table fo...
def _text(code, quiet_zone=4): """This method returns a text based representation of the QR code. This is useful for debugging purposes. """ buf = io.StringIO() border_row = '0' * (len(code[0]) + (quiet_zone*2)) #Every QR code start with a quiet zone at the top for b in range(quiet_zone): ...
def _xbm(code, scale=1, quiet_zone=4): """This function will format the QR code as a X BitMap. This can be used to display the QR code with Tkinter. """ try: str = unicode # Python 2 except NameError: str = __builtins__['str'] buf = io.StringIO() # Calculate th...
def _svg(code, version, file, scale=1, module_color='#000', background=None, quiet_zone=4, xmldecl=True, svgns=True, title=None, svgclass='pyqrcode', lineclass='pyqrline', omithw=False, debug=False): """This function writes the QR code out as an SVG document. The code is drawn by drawing only ...
def _png(code, version, file, scale=1, module_color=(0, 0, 0, 255), background=(255, 255, 255, 255), quiet_zone=4, debug=False): """See: pyqrcode.QRCode.png() This function was abstracted away from QRCode to allow for the output of QR codes during the build process, i.e. for debugging. It works ...
def _eps(code, version, file_or_path, scale=1, module_color=(0, 0, 0), background=None, quiet_zone=4): """This function writes the QR code out as an EPS document. The code is drawn by drawing only the modules corresponding to a 1. They are drawn using a line, such that contiguous modules in a row ...
def _hex_to_rgb(color): """\ Helper function to convert a color provided in hexadecimal format as RGB triple. """ if color[0] == '#': color = color[1:] if len(color) == 3: color = color[0] * 2 + color[1] * 2 + color[2] * 2 if len(color) != 6: raise ValueError('Input #...
def grouper(self, n, iterable, fillvalue=None): """This generator yields a set of tuples, where the iterable is broken into n sized chunks. If the iterable is not evenly sized then fillvalue will be appended to the last tuple to make up the difference. This function is copied fr...
def get_data_length(self): """QR codes contain a "data length" field. This method creates this field. A binary string representing the appropriate length is returned. """ #The "data length" field varies by the type of code and its mode. #discover how long the "data lengt...
def encode(self): """This method encodes the data into a binary string using the appropriate algorithm specified by the mode. """ if self.mode == tables.modes['alphanumeric']: encoded = self.encode_alphanumeric() elif self.mode == tables.modes['numeric']: ...
def encode_alphanumeric(self): """This method encodes the QR code's data if its mode is alphanumeric. It returns the data encoded as a binary string. """ #Convert the string to upper case self.data = self.data.upper() #Change the data such that it uses a QR code ascii ta...
def encode_numeric(self): """This method encodes the QR code's data if its mode is numeric. It returns the data encoded as a binary string. """ with io.StringIO() as buf: #Break the number into groups of three digits for triplet in self.grouper(3, self.data): ...
def encode_bytes(self): """This method encodes the QR code's data if its mode is 8 bit mode. It returns the data encoded as a binary string. """ with io.StringIO() as buf: for char in self.data: if not isinstance(char, int): buf.write('{{0:...
def encode_kanji(self): """This method encodes the QR code's data if its mode is kanji. It returns the data encoded as a binary string. """ def two_bytes(data): """Output two byte character code as a single integer.""" def next_byte(b): """Make sur...
def add_data(self): """This function properly constructs a QR code's data string. It takes into account the interleaving pattern required by the standard. """ #Encode the data into a QR code self.buffer.write(self.binary_string(self.mode, 4)) self.buffer.write(self.get_da...
def terminate_bits(self, payload): """This method adds zeros to the end of the encoded data so that the encoded data is of the correct length. It returns a binary string containing the bits to be added. """ data_capacity = tables.data_capacity[self.version][self.error][0] ...
def delimit_words(self): """This method takes the existing encoded binary string and returns a binary string that will pad it such that the encoded string contains only full bytes. """ bits_short = 8 - (len(self.buffer.getvalue()) % 8) #The string already falls o...
def add_words(self): """The data block must fill the entire data capacity of the QR code. If we fall short, then we must add bytes to the end of the encoded data field. The value of these bytes are specified in the standard. """ data_blocks = len(self.buffer.getvalue()) // 8 ...
def make_error_block(self, block, block_number): """This function constructs the error correction block of the given data block. This is *very complicated* process. To understand the code you need to read: * http://www.thonky.com/qr-code-tutorial/part-2-error-correction/ * http:...
def make_code(self): """This method returns the best possible QR code.""" from copy import deepcopy #Get the size of the underlying matrix matrix_size = tables.version_size[self.version] #Create a template matrix we will build the codes with row = [' ' for x in range(ma...
def add_detection_pattern(self, m): """This method add the detection patterns to the QR code. This lets the scanner orient the pattern. It is required for all QR codes. The detection pattern consists of three boxes located at the upper left, upper right, and lower left corners of the mat...
def add_position_pattern(self, m): """This method draws the position adjustment patterns onto the QR Code. All QR code versions larger than one require these special boxes called position adjustment patterns. """ #Version 1 does not have a position adjustment pattern if s...
def add_version_pattern(self, m): """For QR codes with a version 7 or higher, a special pattern specifying the code's version is required. For further information see: http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string """ ...
def make_masks(self, template): """This method generates all seven masks so that the best mask can be determined. The template parameter is a code matrix that will server as the base for all the generated masks. """ from copy import deepcopy nmasks = len(tables.mask_patt...
def choose_best_mask(self): """This method returns the index of the "best" mask as defined by having the lowest total penalty score. The penalty rules are defined by the standard. The mask with the lowest total score should be the easiest to read by optical scanners. """ ...
def add_type_pattern(self, m, type_bits): """This will add the pattern to the QR code that represents the error level and the type of mask used to make the code. """ field = iter(type_bits) for i in range(7): bit = int(next(field)) #Skip the timing bits ...
def split_pulls(all_issues, project="arokem/python-matlab-bridge"): """split a list of closed issues into non-PR Issues and Pull Requests""" pulls = [] issues = [] for i in all_issues: if is_pull_request(i): pull = get_pull_request(project, i['number'], auth=True) pulls.a...
def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False): """Get all issues closed since a particular point in time. period can either be a datetime object, or a timedelta object. In the latter case, it is used as a time before the present. """ which =...
def sorted_by_field(issues, field='closed_at', reverse=False): """Return a list of issues sorted by closing date date.""" return sorted(issues, key = lambda i:i[field], reverse=reverse)
def report(issues, show_urls=False): """Summary report about a list of issues, printing number and title. """ # titles may have unicode in them, so we must encode everything below if show_urls: for i in issues: print(u'#%d: %s' % (i['number'], i[...
def encode_ndarray(obj): """Write a numpy array and its shape to base64 buffers""" shape = obj.shape if len(shape) == 1: shape = (1, obj.shape[0]) if obj.flags.c_contiguous: obj = obj.T elif not obj.flags.f_contiguous: obj = asfortranarray(obj.T) else: obj = obj.T...