idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
31,900 | def printPi ( self ) : assert self . pi is not None , "Calculate pi before calling printPi()" assert len ( self . mapping ) > 0 , "printPi() can only be used in combination with the direct or indirect method. Use print(mc.pi) if your subclass is called mc." for key , state in self . mapping . items ( ) : print ( state ... | Prints all states state and their steady state probabilities . Not recommended for large state spaces . |
31,901 | def launch_ipython ( argv = None ) : from . linux import launch_ipython as _launch_ipython_linux os . environ = { str ( k ) : str ( v ) for k , v in os . environ . items ( ) } try : from qtconsole . qtconsoleapp import JupyterQtConsoleApp except ImportError : sys . exit ( "ERROR: IPython QtConsole not installed in this... | Force usage of QtConsole under Windows |
31,902 | def launch_ipython ( argv = None , ipython_app = None ) : try : if ipython_app is None : from IPython . terminal . ipapp import TerminalIPythonApp as ipython_app from traitlets . config import Config except ImportError : sys . exit ( "ERROR: IPython not installed in this environment. " "Try with `conda install ipython`... | Launch IPython from this interpreter with custom args if needed . Chimera magic commands are also enabled automatically . |
31,903 | def launch_notebook ( argv = None ) : try : import nbformat . v4 as nbf from notebook . notebookapp import NotebookApp from notebook . services . contents import manager from traitlets . config import Config except ImportError : sys . exit ( "ERROR: Jupyter Notebook not installed in this environment. " "Try with `conda... | Launch a Jupyter Notebook with custom Untitled filenames and a prepopulated first cell with necessary boilerplate code . |
31,904 | def enable_chimera_inline ( ) : from IPython . display import IFrame from IPython . core . magic import register_line_magic import chimera import Midas @ register_line_magic def chimera_export_3D ( line ) : if chimera . viewer . __class__ . __name__ == 'NoGuiViewer' : print ( 'This magic requires a headless Chimera bui... | Enable IPython magic commands to run some Chimera actions |
31,905 | def chimera_view ( * molecules ) : try : import nglview as nv except ImportError : raise ImportError ( 'You must install nglview!' ) import chimera class _ChimeraStructure ( nv . Structure ) : def __init__ ( self , * molecules ) : if not molecules : raise ValueError ( 'Please supply at least one chimera.Molecule.' ) se... | Depicts the requested molecules with NGLViewer in a Python notebook . This method does not require a headless Chimera build however . |
31,906 | def enable_chimera ( verbose = False , nogui = True ) : if os . getenv ( 'CHIMERA_ENABLED' ) : return import chimera _pre_gui_patches ( ) if not nogui : chimera . registerPostGraphicsFunc ( _post_gui_patches ) try : import chimeraInit if verbose : chimera . replyobj . status ( 'initializing pychimera' ) except ImportEr... | Bypass script loading and initialize Chimera correctly once the env has been properly patched . |
31,907 | def patch_sys_version ( ) : if '|' in sys . version : sys_version = sys . version . split ( '|' ) sys . version = ' ' . join ( [ sys_version [ 0 ] . strip ( ) , sys_version [ - 1 ] . strip ( ) ] ) | Remove Continuum copyright statement to avoid parsing errors in IDLE |
31,908 | def patch_environ ( nogui = True ) : if 'CHIMERA' in os . environ : return paths = guess_chimera_path ( search_all = nogui ) CHIMERA_BASE = paths [ 0 ] if nogui : try : CHIMERA_BASE = next ( p for p in paths if 'headless' in p ) except StopIteration : pass if not os . path . isdir ( CHIMERA_BASE ) : sys . exit ( "Could... | Patch current environment variables so Chimera can start up and we can import its modules . |
31,909 | def guess_chimera_path ( search_all = False ) : paths = _search_chimera ( CHIMERA_BINARY , CHIMERA_LOCATIONS , CHIMERA_PREFIX , search_all = search_all ) if not paths and search_all : headless = '{0[0]}{1}{0[1]}' . format ( os . path . split ( CHIMERA_BINARY ) , '-headless' ) paths = _search_chimera ( headless , CHIMER... | Try to guess Chimera installation path . |
31,910 | def make_micro ( content , error = None , version = None , mode = None , mask = None , encoding = None , boost_error = True ) : return make ( content , error = error , version = version , mode = mode , mask = mask , encoding = encoding , micro = True , boost_error = boost_error ) | \ Creates a Micro QR Code . |
31,911 | def make_sequence ( content , error = None , version = None , mode = None , mask = None , encoding = None , boost_error = True , symbol_count = None ) : return QRCodeSequence ( map ( QRCode , encoder . encode_sequence ( content , error = error , version = version , mode = mode , mask = mask , encoding = encoding , boos... | \ Creates a sequence of QR Codes . |
31,912 | def designator ( self ) : version = str ( self . version ) return '-' . join ( ( version , self . error ) if self . error else ( version , ) ) | \ Returns the version and error correction level as string V - E where V represents the version number and E the error level . |
31,913 | def matrix_iter ( self , scale = 1 , border = None ) : return utils . matrix_iter ( self . matrix , self . _version , scale , border ) | \ Returns an iterator over the matrix which includes the border . |
31,914 | def show ( self , delete_after = 20 , scale = 10 , border = None , color = '#000' , background = '#fff' ) : import os import time import tempfile import webbrowser import threading try : from urlparse import urljoin from urllib import pathname2url except ImportError : from urllib . parse import urljoin from urllib . re... | \ Displays this QR code . |
31,915 | def svg_data_uri ( self , xmldecl = False , encode_minimal = False , omit_charset = False , nl = False , ** kw ) : return writers . as_svg_data_uri ( self . matrix , self . _version , xmldecl = xmldecl , nl = nl , encode_minimal = encode_minimal , omit_charset = omit_charset , ** kw ) | \ Converts the QR Code into a SVG data URI . |
31,916 | def png_data_uri ( self , ** kw ) : return writers . as_png_data_uri ( self . matrix , self . _version , ** kw ) | \ Converts the QR Code into a PNG data URI . |
31,917 | def terminal ( self , out = None , border = None ) : if out is None and sys . platform == 'win32' : try : writers . write_terminal_win ( self . matrix , self . _version , border ) except OSError : writers . write_terminal ( self . matrix , self . _version , sys . stdout , border ) else : writers . write_terminal ( self... | \ Serializes the matrix as ANSI escape code . |
31,918 | def save ( self , out , kind = None , ** kw ) : writers . save ( self . matrix , self . _version , out , kind , ** kw ) | \ Serializes the QR Code in one of the supported formats . The serialization format depends on the filename extension . |
31,919 | def terminal ( self , out = None , border = None ) : for qrcode in self : qrcode . terminal ( out = out , border = border ) | \ Serializes the sequence of QR Codes as ANSI escape code . |
31,920 | def save ( self , out , kind = None , ** kw ) : m = len ( self ) def prepare_fn_noop ( o , n ) : return o def prepare_filename ( o , n ) : return o . format ( m , n ) prepare_fn = prepare_fn_noop if m > 1 and isinstance ( out , str_type ) : dot_idx = out . rfind ( '.' ) if dot_idx > - 1 : out = out [ : dot_idx ] + '-{0... | \ Saves the sequence of QR Code to out . |
31,921 | def writable ( file_or_path , mode , encoding = None ) : f = file_or_path must_close = False try : file_or_path . write if encoding is not None : f = codecs . getwriter ( encoding ) ( file_or_path ) except AttributeError : f = open ( file_or_path , mode , encoding = encoding ) must_close = True try : yield f finally : ... | \ Returns a writable file - like object . |
31,922 | def as_svg_data_uri ( matrix , version , scale = 1 , border = None , color = '#000' , background = None , xmldecl = False , svgns = True , title = None , desc = None , svgid = None , svgclass = 'segno' , lineclass = 'qrline' , omitsize = False , unit = '' , encoding = 'utf-8' , svgversion = None , nl = False , encode_m... | \ Converts the matrix to a SVG data URI . |
31,923 | def write_svg_debug ( matrix , version , out , scale = 15 , border = None , fallback_color = 'fuchsia' , color_mapping = None , add_legend = True ) : clr_mapping = { 0x0 : '#fff' , 0x1 : '#000' , 0x2 : 'red' , 0x3 : 'orange' , 0x4 : 'gold' , 0x5 : 'green' , } if color_mapping is not None : clr_mapping . update ( color_... | \ Internal SVG serializer which is useful to debugging purposes . |
31,924 | def write_eps ( matrix , version , out , scale = 1 , border = None , color = '#000' , background = None ) : import textwrap def write_line ( writemeth , content ) : for line in textwrap . wrap ( content , 254 ) : writemeth ( line ) writemeth ( '\n' ) def rgb_to_floats ( clr ) : def to_float ( c ) : if isinstance ( c , ... | \ Serializes the QR Code as EPS document . |
31,925 | def as_png_data_uri ( matrix , version , scale = 1 , border = None , color = '#000' , background = '#fff' , compresslevel = 9 , addad = True ) : buff = io . BytesIO ( ) write_png ( matrix , version , buff , scale = scale , border = border , color = color , background = background , compresslevel = compresslevel , addad... | \ Converts the provided matrix into a PNG data URI . |
31,926 | def write_txt ( matrix , version , out , border = None , color = '1' , background = '0' ) : row_iter = matrix_iter ( matrix , version , scale = 1 , border = border ) colours = ( str ( background ) , str ( color ) ) with writable ( out , 'wt' ) as f : write = f . write for row in row_iter : write ( '' . join ( [ colours... | \ Serializes QR code in a text format . |
31,927 | def write_tex ( matrix , version , out , scale = 1 , border = None , color = 'black' , unit = 'pt' , url = None ) : def point ( x , y ) : return '\\pgfqpoint{{{0}{2}}}{{{1}{2}}}' . format ( x , y , unit ) check_valid_scale ( scale ) check_valid_border ( border ) border = get_border ( version , border ) with writable ( ... | \ Serializes the matrix as LaTeX PGF picture . |
31,928 | def write_terminal ( matrix , version , out , border = None ) : with writable ( out , 'wt' ) as f : write = f . write colours = [ '\033[{0}m' . format ( i ) for i in ( 7 , 49 ) ] for row in matrix_iter ( matrix , version , scale = 1 , border = border ) : prev_bit = - 1 cnt = 0 for bit in row : if bit == prev_bit : cnt ... | \ Function to write to a terminal which supports ANSI escape codes . |
31,929 | def write_terminal_win ( matrix , version , border = None ) : import sys import struct import ctypes write = sys . stdout . write std_out = ctypes . windll . kernel32 . GetStdHandle ( - 11 ) csbi = ctypes . create_string_buffer ( 22 ) res = ctypes . windll . kernel32 . GetConsoleScreenBufferInfo ( std_out , csbi ) if n... | \ Function to write a QR Code to a MS Windows terminal . |
31,930 | def _pack_bits_into_byte ( iterable ) : return ( reduce ( lambda x , y : ( x << 1 ) + y , e ) for e in zip_longest ( * [ iter ( iterable ) ] * 8 , fillvalue = 0x0 ) ) | \ Packs eight bits into one byte . |
31,931 | def save ( matrix , version , out , kind = None , ** kw ) : is_stream = False if kind is None : try : fname = out . name is_stream = True except AttributeError : fname = out ext = fname [ fname . rfind ( '.' ) + 1 : ] . lower ( ) else : ext = kind . lower ( ) if not is_stream and ext == 'svgz' : f = gzip . open ( out ,... | \ Serializes the matrix in any of the supported formats . |
31,932 | def parse ( args ) : parser = make_parser ( ) if not len ( args ) : parser . print_help ( ) sys . exit ( 1 ) parsed_args = parser . parse_args ( args ) if parsed_args . error == '-' : parsed_args . error = None version = parsed_args . version if version is not None : version = str ( version ) . upper ( ) if not parsed_... | \ Parses the arguments and returns the result . |
31,933 | def build_config ( config , filename = None ) : for clr in ( 'color' , 'background' ) : val = config . pop ( clr , None ) if val in ( 'transparent' , 'trans' ) : config [ clr ] = None elif val : config [ clr ] = val for name in ( 'svgid' , 'svgclass' , 'lineclass' ) : if config . get ( name , None ) is None : config . ... | \ Builds a configuration and returns it . The config contains only keywords which are supported by the serializer . Unsupported values are ignored . |
31,934 | def make_wifi_data ( ssid , password , security , hidden = False ) : def quotation_mark ( x ) : try : int ( x , 16 ) except ValueError : return '' return '"' escape = _escape_mecard data = 'WIFI:' if security : data += 'T:{0};' . format ( security . upper ( ) if security != 'nopass' else security ) data += 'S:{1}{0}{1}... | \ Creates WIFI configuration string . |
31,935 | def make_wifi ( ssid , password , security , hidden = False ) : return segno . make_qr ( make_wifi_data ( ssid , password , security , hidden ) ) | \ Creates a WIFI configuration QR Code . |
31,936 | def make_mecard_data ( name , reading = None , email = None , phone = None , videophone = None , memo = None , nickname = None , birthday = None , url = None , pobox = None , roomno = None , houseno = None , city = None , prefecture = None , zipcode = None , country = None ) : def make_multifield ( name , val ) : if va... | \ Creates a string encoding the contact information as MeCard . |
31,937 | def make_geo_data ( lat , lng ) : def float_to_str ( f ) : return '{0:.8f}' . format ( f ) . rstrip ( '0' ) return 'geo:{0},{1}' . format ( float_to_str ( lat ) , float_to_str ( lng ) ) | \ Creates a geo location URI . |
31,938 | def boost_error_level ( version , error , segments , eci , is_sa = False ) : if error not in ( consts . ERROR_LEVEL_H , None ) and len ( segments ) == 1 : levels = [ consts . ERROR_LEVEL_L , consts . ERROR_LEVEL_M , consts . ERROR_LEVEL_Q , consts . ERROR_LEVEL_H ] if version < 1 : levels . pop ( ) if version < consts ... | \ Increases the error level if possible . |
31,939 | def write_segment ( buff , segment , ver , ver_range , eci = False ) : mode = segment . mode append_bits = buff . append_bits if eci and mode == consts . MODE_BYTE and segment . encoding != consts . DEFAULT_BYTE_ENCODING : append_bits ( consts . MODE_ECI , 4 ) append_bits ( get_eci_assignment_number ( segment . encodin... | \ Writes a segment . |
31,940 | def write_terminator ( buff , capacity , ver , length ) : buff . extend ( [ 0 ] * min ( capacity - length , consts . TERMINATOR_LENGTH [ ver ] ) ) | \ Writes the terminator . |
31,941 | def write_padding_bits ( buff , version , length ) : if version not in ( consts . VERSION_M1 , consts . VERSION_M3 ) : buff . extend ( [ 0 ] * ( 8 - ( length % 8 ) ) ) | \ Writes padding bits if the data stream does not meet the codeword boundary . |
31,942 | def write_pad_codewords ( buff , version , capacity , length ) : write = buff . extend if version in ( consts . VERSION_M1 , consts . VERSION_M3 ) : write ( [ 0 ] * ( capacity - length ) ) else : pad_codewords = ( ( 1 , 1 , 1 , 0 , 1 , 1 , 0 , 0 ) , ( 0 , 0 , 0 , 1 , 0 , 0 , 0 , 1 ) ) for i in range ( capacity // 8 - l... | \ Writes the pad codewords iff the data does not fill the capacity of the symbol . |
31,943 | def add_alignment_patterns ( matrix , version ) : if version < 2 : return matrix_size = len ( matrix ) positions = consts . ALIGNMENT_POS [ version - 2 ] for pos_x in positions : for pos_y in positions : if pos_x - 6 == 0 and ( pos_y - 6 == 0 or pos_y + 7 == matrix_size ) or pos_y - 6 == 0 and pos_x + 7 == matrix_size ... | \ Adds the adjustment patterns to the matrix . For versions < 2 this is a no - op . |
31,944 | def make_blocks ( ec_infos , codewords ) : data_blocks , error_blocks = [ ] , [ ] offset = 0 for ec_info in ec_infos : for i in range ( ec_info . num_blocks ) : block = codewords [ offset : offset + ec_info . num_data ] data_blocks . append ( block ) error_blocks . append ( make_error_block ( ec_info , block ) ) offset... | \ Returns the data and error blocks . |
31,945 | def make_error_block ( ec_info , data_block ) : num_error_words = ec_info . num_total - ec_info . num_data error_block = bytearray ( data_block ) error_block . extend ( [ 0 ] * num_error_words ) gen = consts . GEN_POLY [ num_error_words ] gen_log = consts . GALIOS_LOG gen_exp = consts . GALIOS_EXP len_data = len ( data... | \ Creates the error code words for the provided data block . |
31,946 | def find_and_apply_best_mask ( matrix , version , is_micro , proposed_mask = None ) : matrix_size = len ( matrix ) is_better = lt best_score = _MAX_PENALTY_SCORE eval_mask = evaluate_mask if is_micro : is_better = gt best_score = - 1 eval_mask = evaluate_micro_mask function_matrix = make_matrix ( version ) add_finder_p... | \ Applies all mask patterns against the provided QR Code matrix and returns the best matrix and best pattern . |
31,947 | def apply_mask ( matrix , mask_pattern , matrix_size , is_encoding_region ) : for i in range ( matrix_size ) : for j in range ( matrix_size ) : if is_encoding_region ( i , j ) : matrix [ i ] [ j ] ^= mask_pattern ( i , j ) | \ Applies the provided mask pattern on the matrix . |
31,948 | def evaluate_mask ( matrix , matrix_size ) : return score_n1 ( matrix , matrix_size ) + score_n2 ( matrix , matrix_size ) + score_n3 ( matrix , matrix_size ) + score_n4 ( matrix , matrix_size ) | \ Evaluates the provided matrix of a QR code . |
31,949 | def score_n1 ( matrix , matrix_size ) : score = 0 for i in range ( matrix_size ) : prev_bit_row , prev_bit_col = - 1 , - 1 row_counter , col_counter = 0 , 0 for j in range ( matrix_size ) : bit = matrix [ i ] [ j ] if bit == prev_bit_row : row_counter += 1 else : if row_counter >= 5 : score += row_counter - 2 row_count... | \ Implements the penalty score feature 1 . |
31,950 | def score_n2 ( matrix , matrix_size ) : score = 0 for i in range ( matrix_size - 1 ) : for j in range ( matrix_size - 1 ) : bit = matrix [ i ] [ j ] if bit == matrix [ i ] [ j + 1 ] and bit == matrix [ i + 1 ] [ j ] and bit == matrix [ i + 1 ] [ j + 1 ] : score += 1 return score * 3 | \ Implements the penalty score feature 2 . |
31,951 | def score_n3 ( matrix , matrix_size ) : def is_match ( seq , start , end ) : start = max ( start , 0 ) end = min ( end , matrix_size ) for i in range ( start , end ) : if seq [ i ] == 0x1 : return False return True def find_occurrences ( seq ) : count = 0 idx = seq . find ( _N3_PATTERN ) while idx != - 1 : offset = idx... | \ Implements the penalty score feature 3 . |
31,952 | def score_n4 ( matrix , matrix_size ) : dark_modules = sum ( map ( sum , matrix ) ) total_modules = matrix_size ** 2 k = int ( abs ( dark_modules * 2 - total_modules ) * 10 // total_modules ) return 10 * k | \ Implements the penalty score feature 4 . |
31,953 | def evaluate_micro_mask ( matrix , matrix_size ) : sum1 = sum ( matrix [ i ] [ - 1 ] == 0x1 for i in range ( 1 , matrix_size ) ) sum2 = sum ( matrix [ - 1 ] [ i ] == 0x1 for i in range ( 1 , matrix_size ) ) return sum1 * 16 + sum2 if sum1 <= sum2 else sum2 * 16 + sum1 | \ Evaluates the provided matrix of a Micro QR code . |
31,954 | def calc_format_info ( version , error , mask_pattern ) : fmt = mask_pattern if version > 0 : if error == consts . ERROR_LEVEL_L : fmt += 0x08 elif error == consts . ERROR_LEVEL_H : fmt += 0x10 elif error == consts . ERROR_LEVEL_Q : fmt += 0x18 format_info = consts . FORMAT_INFO [ fmt ] else : fmt += consts . ERROR_LEV... | \ Returns the format information for the provided error level and mask patttern . |
31,955 | def add_format_info ( matrix , version , error , mask_pattern ) : is_micro = version < 1 format_info = calc_format_info ( version , error , mask_pattern ) offset = int ( is_micro ) for i in range ( 8 ) : bit = ( format_info >> i ) & 0x01 if i == 6 and not is_micro : offset += 1 matrix [ i + offset ] [ 8 ] = bit if not ... | \ Adds the format information into the provided matrix . |
31,956 | def add_version_info ( matrix , version ) : if version < 7 : return version_info = consts . VERSION_INFO [ version - 7 ] for i in range ( 6 ) : bit1 = ( version_info >> ( i * 3 ) ) & 0x01 bit2 = ( version_info >> ( ( i * 3 ) + 1 ) ) & 0x01 bit3 = ( version_info >> ( ( i * 3 ) + 2 ) ) & 0x01 matrix [ - 11 ] [ i ] = bit1... | \ Adds the version information to the matrix for versions < 7 this is a no - op . |
31,957 | def prepare_data ( content , mode , encoding , version = None ) : segments = Segments ( ) add_segment = segments . add_segment if isinstance ( content , ( str_type , bytes , numeric ) ) : add_segment ( make_segment ( content , mode , encoding ) ) return segments for item in content : seg_content , seg_mode , seg_encodi... | \ Returns an iterable of Segment instances . |
31,958 | def data_to_bytes ( data , encoding ) : if isinstance ( data , bytes ) : return data , len ( data ) , encoding or consts . DEFAULT_BYTE_ENCODING data = str ( data ) if encoding is not None : data = data . encode ( encoding ) else : try : encoding = consts . DEFAULT_BYTE_ENCODING data = data . encode ( encoding ) except... | \ Converts the provided data into bytes . If the data is already a byte sequence it will be left unchanged . |
31,959 | def normalize_version ( version ) : if version is None : return None error = False try : version = int ( version ) error = version < 1 except ( ValueError , TypeError ) : try : version = consts . MICRO_VERSION_MAPPING [ version . upper ( ) ] except ( KeyError , AttributeError ) : error = True if error or not 0 < versio... | \ Canonicalizes the provided version . |
31,960 | def normalize_errorlevel ( error , accept_none = False ) : if error is None : if not accept_none : raise ErrorLevelError ( 'The error level must be provided' ) return error try : return consts . ERROR_MAPPING [ error . upper ( ) ] except : if error in consts . ERROR_MAPPING . values ( ) : return error raise ErrorLevelE... | \ Returns a constant for the provided error level . |
31,961 | def get_mode_name ( mode_const ) : for name , val in consts . MODE_MAPPING . items ( ) : if val == mode_const : return name raise ModeError ( 'Unknown mode "{0}"' . format ( mode_const ) ) | \ Returns the mode name for the provided mode constant . |
31,962 | def get_error_name ( error_const ) : for name , val in consts . ERROR_MAPPING . items ( ) : if val == error_const : return name raise ErrorLevelError ( 'Unknown error level "{0}"' . format ( error_const ) ) | \ Returns the error name for the provided error constant . |
31,963 | def get_version_name ( version_const ) : if 0 < version_const < 41 : return version_const for name , v in consts . MICRO_VERSION_MAPPING . items ( ) : if v == version_const : return name raise VersionError ( 'Unknown version constant "{0}"' . format ( version_const ) ) | \ Returns the version name . |
31,964 | def is_kanji ( data ) : data_len = len ( data ) if not data_len or data_len % 2 : return False if _PY2 : data = ( ord ( c ) for c in data ) data_iter = iter ( data ) for i in range ( 0 , data_len , 2 ) : code = ( next ( data_iter ) << 8 ) | next ( data_iter ) if not ( 0x8140 <= code <= 0x9ffc or 0xe040 <= code <= 0xebb... | \ Returns if the data can be encoded in kanji mode . |
31,965 | def calc_structured_append_parity ( content ) : if not isinstance ( content , str_type ) : content = str ( content ) try : data = content . encode ( 'iso-8859-1' ) except UnicodeError : try : data = content . encode ( 'shift-jis' ) except ( LookupError , UnicodeError ) : data = content . encode ( 'utf-8' ) if _PY2 : da... | \ Calculates the parity data for the Structured Append mode . |
31,966 | def is_mode_supported ( mode , ver ) : ver = None if ver > 0 else ver try : return ver in consts . SUPPORTED_MODES [ mode ] except KeyError : raise ModeError ( 'Unknown mode "{0}"' . format ( mode ) ) | \ Returns if mode is supported by version . |
31,967 | def version_range ( version ) : if 0 < version < 10 : return consts . VERSION_RANGE_01_09 elif 9 < version < 27 : return consts . VERSION_RANGE_10_26 elif 26 < version < 41 : return consts . VERSION_RANGE_27_40 raise VersionError ( 'Unknown version "{0}"' . format ( version ) ) | \ Returns the version range for the provided version . This applies to QR Code versions only . |
31,968 | def get_eci_assignment_number ( encoding ) : try : return consts . ECI_ASSIGNMENT_NUM [ codecs . lookup ( encoding ) . name ] except KeyError : raise QRCodeError ( 'Unknown ECI assignment number for encoding "{0}".' . format ( encoding ) ) | \ Returns the ECI number for the provided encoding . |
31,969 | def get_data_mask_functions ( is_micro ) : def fn0 ( i , j ) : return ( i + j ) & 0x1 == 0 def fn1 ( i , j ) : return i & 0x1 == 0 def fn2 ( i , j ) : return j % 3 == 0 def fn3 ( i , j ) : return ( i + j ) % 3 == 0 def fn4 ( i , j ) : return ( i // 2 + j // 3 ) & 0x1 == 0 def fn5 ( i , j ) : tmp = i * j return ( tmp & ... | Returns the data mask functions . |
31,970 | def toints ( self ) : def grouper ( iterable , n , fillvalue = None ) : "Collect data into fixed-length chunks or blocks" return zip_longest ( * [ iter ( iterable ) ] * n , fillvalue = fillvalue ) return [ int ( '' . join ( map ( str , group ) ) , 2 ) for group in grouper ( self . _data , 8 , 0 ) ] | \ Returns an iterable of integers interpreting the content of seq as sequence of binary numbers of length 8 . |
31,971 | def color_to_webcolor ( color , allow_css3_colors = True , optimize = True ) : if color_is_black ( color ) : return '#000' elif color_is_white ( color ) : return '#fff' clr = color_to_rgb_or_rgba ( color ) alpha_channel = None if len ( clr ) == 4 : if allow_css3_colors : return 'rgba({0},{1},{2},{3})' . format ( * clr ... | \ Returns either a hexadecimal code or a color name . |
31,972 | def check_valid_border ( border ) : if border is not None and ( int ( border ) != border or border < 0 ) : raise ValueError ( 'The border must not a non-negative integer value. ' 'Got: "{0}"' . format ( border ) ) | \ Raises a ValueError iff border is negative . |
31,973 | def onStart ( self ) : curses . mousemask ( 0 ) self . paths . host_config ( ) version = Version ( ) if self . first_time [ 0 ] and self . first_time [ 1 ] != 'exists' : system = System ( ) thr = Thread ( target = system . start , args = ( ) , kwargs = { } ) thr . start ( ) countdown = 60 while thr . is_alive ( ) : npy... | Override onStart method for npyscreen |
31,974 | def setGroups ( self , groups , kerningGroupConversionRenameMaps = None ) : skipping = [ ] for name , members in groups . items ( ) : checked = [ ] for m in members : if m in self . font : checked . append ( m ) else : skipping . append ( m ) if checked : self . font . groups [ name ] = checked if skipping : if self . ... | Copy the groups into our font . |
31,975 | def setLib ( self , lib ) : for name , item in lib . items ( ) : self . font . lib [ name ] = item | Copy the lib items into our font . |
31,976 | def copyFeatures ( self , featureSource ) : if featureSource in self . sources : src , loc = self . sources [ featureSource ] if isinstance ( src . features . text , str ) : self . font . features . text = u"" + src . features . text elif isinstance ( src . features . text , unicode ) : self . font . features . text = ... | Copy the features from this source |
31,977 | def makeUnicodeMapFromSources ( self ) : values = { } for locationName , ( source , loc ) in self . sources . items ( ) : for glyph in source : if glyph . unicodes is not None : if glyph . name not in values : values [ glyph . name ] = { } for u in glyph . unicodes : values [ glyph . name ] [ u ] = 1 for name , u in va... | Create a dict with glyphName - > unicode value pairs using the data in the sources . If all master glyphs have the same unicode value this value will be used in the map . If master glyphs have conflicting value a warning will be printed no value will be used . If only a single master has a value that value will be used... |
31,978 | def getAvailableGlyphnames ( self ) : glyphNames = { } for locationName , ( source , loc ) in self . sources . items ( ) : for glyph in source : glyphNames [ glyph . name ] = 1 names = sorted ( glyphNames . keys ( ) ) return names | Return a list of all glyphnames we have masters for . |
31,979 | def addInfo ( self , instanceLocation = None , sources = None , copySourceName = None ) : if instanceLocation is None : instanceLocation = self . locationObject infoObject = self . font . info infoMasters = [ ] if sources is None : sources = self . sources items = [ ] for sourceName , ( source , sourceLocation ) in sou... | Add font info data . |
31,980 | def _copyFontInfo ( self , targetInfo , sourceInfo ) : infoAttributes = [ "versionMajor" , "versionMinor" , "copyright" , "trademark" , "note" , "openTypeGaspRangeRecords" , "openTypeHeadCreated" , "openTypeHeadFlags" , "openTypeNameDesigner" , "openTypeNameDesignerURL" , "openTypeNameManufacturer" , "openTypeNameManuf... | Copy the non - calculating fields from the source info . |
31,981 | def _calculateGlyph ( self , targetGlyphObject , instanceLocationObject , glyphMasters ) : sources = None items = [ ] for item in glyphMasters : locationObject = item [ 'location' ] fontObject = item [ 'font' ] glyphName = item [ 'glyphName' ] if not glyphName in fontObject : continue glyphObject = MathGlyph ( fontObje... | Build a Mutator object for this glyph . |
31,982 | def save ( self ) : for name in self . mutedGlyphsNames : if name not in self . font : continue if self . logger : self . logger . info ( "removing muted glyph %s" , name ) del self . font [ name ] directory = os . path . dirname ( os . path . normpath ( self . path ) ) if directory and not os . path . exists ( directo... | Save the UFO . |
31,983 | def save ( self , pretty = True ) : self . endInstance ( ) if pretty : _indent ( self . root , whitespace = self . _whiteSpace ) tree = ET . ElementTree ( self . root ) tree . write ( self . path , encoding = "utf-8" , method = 'xml' , xml_declaration = True ) if self . logger : self . logger . info ( "Writing %s" , se... | Save the xml . Make pretty if necessary . |
31,984 | def _makeLocationElement ( self , locationObject , name = None ) : locElement = ET . Element ( "location" ) if name is not None : locElement . attrib [ 'name' ] = name for dimensionName , dimensionValue in locationObject . items ( ) : dimElement = ET . Element ( 'dimension' ) dimElement . attrib [ 'name' ] = dimensionN... | Convert Location object to an locationElement . |
31,985 | def reportProgress ( self , state , action , text = None , tick = None ) : if self . progressFunc is not None : self . progressFunc ( state = state , action = action , text = text , tick = tick ) | If we want to keep other code updated about our progress . |
31,986 | def getSourcePaths ( self , makeGlyphs = True , makeKerning = True , makeInfo = True ) : paths = [ ] for name in self . sources . keys ( ) : paths . append ( self . sources [ name ] [ 0 ] . path ) return paths | Return a list of paths referenced in the document . |
31,987 | def process ( self , makeGlyphs = True , makeKerning = True , makeInfo = True ) : if self . logger : self . logger . info ( "Reading %s" , self . path ) self . readInstances ( makeGlyphs = makeGlyphs , makeKerning = makeKerning , makeInfo = makeInfo ) self . reportProgress ( "done" , 'stop' ) | Process the input file and generate the instances . |
31,988 | def readWarp ( self ) : warpDict = { } for warpAxisElement in self . root . findall ( ".warp/axis" ) : axisName = warpAxisElement . attrib . get ( "name" ) warpDict [ axisName ] = [ ] for warpPoint in warpAxisElement . findall ( ".map" ) : inputValue = float ( warpPoint . attrib . get ( "input" ) ) outputValue = float ... | Read the warp element |
31,989 | def readAxes ( self ) : for axisElement in self . root . findall ( ".axes/axis" ) : axis = { } axis [ 'name' ] = name = axisElement . attrib . get ( "name" ) axis [ 'tag' ] = axisElement . attrib . get ( "tag" ) axis [ 'minimum' ] = float ( axisElement . attrib . get ( "minimum" ) ) axis [ 'maximum' ] = float ( axisEle... | Read the axes element . |
31,990 | def readSources ( self ) : for sourceCount , sourceElement in enumerate ( self . root . findall ( ".sources/source" ) ) : filename = sourceElement . attrib . get ( 'filename' ) sourcePath = os . path . abspath ( os . path . join ( os . path . dirname ( self . path ) , filename ) ) sourceName = sourceElement . attrib . ... | Read the source elements . |
31,991 | def locationFromElement ( self , element ) : elementLocation = None for locationElement in element . findall ( '.location' ) : elementLocation = self . readLocationElement ( locationElement ) break return elementLocation | Find the MutatorMath location of this element either by name or from a child element . |
31,992 | def readInstance ( self , key , makeGlyphs = True , makeKerning = True , makeInfo = True ) : attrib , value = key for instanceElement in self . root . findall ( '.instances/instance' ) : if instanceElement . attrib . get ( attrib ) == value : self . _readSingleInstanceElement ( instanceElement , makeGlyphs = makeGlyphs... | Read a single instance element . |
31,993 | def readInstances ( self , makeGlyphs = True , makeKerning = True , makeInfo = True ) : for instanceElement in self . root . findall ( '.instances/instance' ) : self . _readSingleInstanceElement ( instanceElement , makeGlyphs = makeGlyphs , makeKerning = makeKerning , makeInfo = makeInfo ) | Read all instance elements . |
31,994 | def readInfoElement ( self , infoElement , instanceObject ) : infoLocation = self . locationFromElement ( infoElement ) instanceObject . addInfo ( infoLocation , copySourceName = self . infoSource ) | Read the info element . |
31,995 | def readKerningElement ( self , kerningElement , instanceObject ) : kerningLocation = self . locationFromElement ( kerningElement ) instanceObject . addKerning ( kerningLocation ) | Read the kerning element . |
31,996 | def readGlyphElement ( self , glyphElement , instanceObject ) : glyphName = glyphElement . attrib . get ( 'name' ) if glyphName is None : raise MutatorError ( "Glyph object without name attribute." ) mute = glyphElement . attrib . get ( "mute" ) if mute == "1" : instanceObject . muteGlyph ( glyphName ) return unicodes ... | Read the glyph element . |
31,997 | def group_by ( self , key_names = [ ] , key = lambda x : x , result_func = lambda x : x ) : result = [ ] ordered = sorted ( self , key = key ) grouped = itertools . groupby ( ordered , key ) for k , g in grouped : can_enumerate = isinstance ( k , list ) or isinstance ( k , tuple ) and len ( k ) > 0 key_prop = { } for i... | Groups an enumerable on given key selector . Index of key name corresponds to index of key lambda function . |
31,998 | def inventory ( self , choices = None ) : status = ( True , None ) if not choices : return ( False , 'No choices made' ) try : items = { 'repos' : [ ] , 'tools' : { } , 'images' : { } , 'built' : { } , 'running' : { } , 'enabled' : { } } tools = Template ( self . manifest ) . list_tools ( ) for choice in choices : for ... | Return a dictionary of the inventory items and status |
31,999 | def _start_priority_containers ( self , groups , group_orders , tool_d ) : vent_cfg = Template ( self . path_dirs . cfg_file ) cfg_groups = vent_cfg . option ( 'groups' , 'start_order' ) if cfg_groups [ 0 ] : cfg_groups = cfg_groups [ 1 ] . split ( ',' ) else : cfg_groups = [ ] all_groups = sorted ( set ( groups ) ) s_... | Select containers based on priorities to start |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.