Generates rst raw block for given image filename and format
182720
def get_imageblock(filename, format=''):
    
    _, extension = os.path.splitext(filename)

    with open(filename, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')

    return '\n\n.. raw:: html\n\n\t<img src="data:image/' + (format if format else extension[1:]) + ';base64,' + encoded_string +'">\n'
1019870
def qr2scad(stream):
    """"""

    img = Image.open(stream)

    # Convert to black and white 8-bit
    if img.mode != 'L':
        img = img.convert('L')

    # Invert color to get the right bounding box
    img = ImageOps.invert(img)

    bbox = img.getbbox()

    # Crop to only contain contents within the PDPs
    img = img.crop(bbox)

    width, height = img.size

    assert width == height,\
        'The QR code should be a square, but we found it to be %(w)sx%(h)s' % {
            'w': width,
            'h': height
        }

    qr_side = width

    # QR code superpixel size
    qr_pixel_size = (list(img.getdata()).index(0) / PDP_SIDE)

    # Get the resize factor from the PDP size
    new_size = qr_side / qr_pixel_size

    # Set a more reasonable size
    img = img.resize((new_size, new_size))
    qr_side = new_size

    img_matrix = img.load()

    result = 'module _qr_code_dot() {\n'
    result += '    cube([%(block_side)s, %(block_side)s, 1]);\n' % {
        'block_side': BLOCK_SIDE
    }
    result += '}\n'

    result += 'module qr_code() {\n'
    for row in range(qr_side):
        for column in range(qr_side):
            if img_matrix[column, row] != 0:
                result += '    translate([%(x)s, %(y)s, 0])' % {
                    'x': BLOCK_SIZE * column - qr_side / 2,
                    'y': -BLOCK_SIZE * row + qr_side / 2
                }
                result += ' _qr_code_dot();\n'
    result += '}\n'
    result += 'qr_code_size = %d;' % (qr_side)

    return result
1257748
def _image2array(filepath):
    '''
    
    '''
    im = Pimage.open(filepath).convert('RGB')
    (width, height) = im.size
    _r = np.array(list(im.getdata(0)))/255.0
    _g = np.array(list(im.getdata(1)))/255.0
    _b = np.array(list(im.getdata(2)))/255.0
    _r = _r.reshape((height, width))
    _g = _g.reshape((height, width))
    _b = _b.reshape((height, width))
    return _r, _g, _b
468890
def md5(filename):
    '''  '''

    if not os.path.exists(filename):
        return None
    digest = _md5()
    blocksize = 64 * 1024
    infile = open(filename, 'rb')
    block = infile.read(blocksize)
    while block:
        digest.update(block)
        block = infile.read(blocksize)
    infile.close()
    return digest.hexdigest()
787211
def convert(f, opts = {})
      opts = opts.dup
      f = f.to_s.downcase
      allowed = %w(jpeg jpg png)
      raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f)
      self.format_override = f == 'jpeg' ? 'jpg' : f
      opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality)
      write_opts.merge!(opts)
      get_image
    end
144643
def _from_docstring_rst(doc):
    

    def format_fn(line, status):
        """ format function """

        if re_from_data.match(line):
            line = re_from_data.sub(r"**\1** ", line)
            status["add_line"] = True
        line = re_from_defaults.sub(r"*\1*", line)
        if status["listing"]:
            # parameters
            if re_from_param.match(line):
                m = re_from_param.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", line)
            # is continuation line
            else:
                line = " " * 4 + line.lstrip()
        # in .rst format code samples use double backticks vs single ones for
        # .md This converts them.
        line = re_lone_backtick.sub("``", line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
142336
def to_rst(cls) -> str:
        """"""
        sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n'
        blank_line = '|' + 78 * ' ' + '|\n'
        table = ''
        for group in cls.groups:
            table += sep_line
            table += blank_line
            table += '|' + '**{}**'.format(group.name).center(78) + '|\n'
            table += blank_line
            for error in group.errors:
                table += sep_line
                table += ('|' + error.code.center(6) + '| ' +
                          error.short_desc.ljust(70) + '|\n')
        table += sep_line
        return table
323517
def load_protocols(filename, _integer_base=10):
    """""""
    spaces = re.compile(b"[ \t]+|\n")
    dct = DADict(_name=filename)
    try:
        with open(filename, "rb") as fdesc:
            for line in fdesc:
                try:
                    shrp = line.find(b"#")
                    if shrp >= 0:
                        line = line[:shrp]
                    line = line.strip()
                    if not line:
                        continue
                    lt = tuple(re.split(spaces, line))
                    if len(lt) < 2 or not lt[0]:
                        continue
                    dct[lt[0]] = int(lt[1], _integer_base)
                except Exception as e:
                    log_loading.info(
                        "Couldn't parse file [%s]: line [%r] (%s)",
                        filename,
                        line,
                        e,
                    )
    except IOError:
        log_loading.info("Can't open %s file", filename)
    return dct
1286677
def blockgen(bytes, block_size=16):
    '''  '''
    for i in range(0, len(bytes), block_size):
        block = bytes[i:i + block_size]
        block_len = len(block)
        if block_len > 0:
            yield block
        if block_len < block_size:
            break
989533
def to_png
      data = ""
      to_png_stream Proc.new { |chunk| data += chunk }
      yield data if block_given?
      data
    end
887405
def _GenerateChunk(self, length):
    """"""

    while 1:
      to_read = min(length, self.RECV_BLOCK_SIZE)
      if to_read == 0:
        return

      data = self.rfile.read(to_read)
      if not data:
        return

      yield data
      length -= len(data)
1100515
def rec2latex(r, filename, empty=""):
    """"""
    with open(filename, "w") as latex:
        latex.write(s_rec2latex(r, empty=empty))
    return filename
75555
def md2pypi(filename):
    '''
    
    '''
    content = io.open(filename).read()

    for match in RE_MD_CODE_BLOCK.finditer(content):
        rst_block = '\n'.join(
            ['.. code-block:: {language}'.format(**match.groupdict()).replace('markdown', ''), ''] +
            ['    {0}'.format(l) for l in match.group('lines').split('\n')] +
            ['']
        )
        content = content.replace(match.group(0), rst_block)

    refs = dict(RE_LINK_REF.findall(content))
    content = RE_LINK_REF.sub('.. _\g<key>: \g<url>', content)
    content = RE_SELF_LINK.sub('`\g<1>`_', content)
    content = RE_LINK_TO_URL.sub('`\g<text> <\g<url>>`_', content)

    for match in RE_BADGE.finditer(content):
        params = match.groupdict()
        params['badge'] = refs[match.group('badge')]
        params['target'] = refs[match.group('target')]
        content = content.replace(match.group(0), RST_BADGE.format(**params))

    for match in RE_IMAGE.finditer(content):
        url = match.group('url')
        if not url.startswith('http'):
            url = '/'.join((GITHUB_REPOSITORY, 'raw/master', url))

        rst_block = '\n'.join([
            '.. image:: {0}'.format(url),
            '  :alt: {0}'.format(match.group('text'))
        ])
        content = content.replace(match.group(0), rst_block)

    # Must occur after badges
    for match in RE_LINK_TO_REF.finditer(content):
        content = content.replace(match.group(0), '`{text} <{url}>`_'.format(
            text=match.group('text'),
            url=refs[match.group('ref')]
        ))

    for match in RE_TITLE.finditer(content):
        underchar = RST_TITLE_LEVELS[len(match.group('level')) - 1]
        title = match.group('title')
        underline = underchar * len(title)

        full_title = '\n'.join((title, underline))
        content = content.replace(match.group(0), full_title)

    content = RE_CODE.sub('``\g<1>``', content)

    return content
194374
def _get_image_data(image, colors):
    
    lzw_code_size, coded_bits = _lzw_encode(image, colors)
    coded_bytes = ''.join(
        '{{:0{}b}}'.format(nbits).format(val) for val, nbits in coded_bits)
    coded_bytes = '0' * ((8 - len(coded_bytes)) % 8) + coded_bytes
    coded_data = list(
        reversed([
            int(coded_bytes[8*i:8*(i+1)], 2)
            for i in range(len(coded_bytes) // 8)
        ])
    )
    output = [struct.pack('<B', lzw_code_size)]
    # Must output the data in blocks of length 255
    block_length = min(255, len(coded_data))
    while block_length > 0:
        block = struct.pack(
            '<{}B'.format(block_length + 1),
            block_length,
            *coded_data[:block_length]
        )
        output.append(block)
        coded_data = coded_data[block_length:]
        block_length = min(255, len(coded_data))
    return b''.join(output)
500066
def as_new_format(self, format="ATR"):
        
        first_data = len(self.header)
        raw = self.rawdata[first_data:]
        data = add_atr_header(raw)
        newraw = SegmentData(data)
        image = self.__class__(newraw)
        return image
416681
def file_to_md5(filename, block_size=8192):
    
    md5 = hashlib.md5()
    with open(filename, 'rb') as f:
        while True:
            data = f.read(block_size)
            if not data:
                break
            md5.update(data)
    return md5.hexdigest()
495072
def rm_raw(ctx, dataset, kwargs):
    ""

    kwargs = parse_kwargs(kwargs)
    data(dataset, **ctx.obj).rm_raw(**kwargs)