idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
242,700 | def com_google_fonts_check_family_control_chars ( ttFonts ) : unacceptable_cc_list = [ "uni0001" , "uni0002" , "uni0003" , "uni0004" , "uni0005" , "uni0006" , "uni0007" , "uni0008" , "uni0009" , "uni000A" , "uni000B" , "uni000C" , "uni000E" , "uni000F" , "uni0010" , "uni0011" , "uni0012" , "uni0013" , "uni0014" , "uni0... | Does font file include unacceptable control character glyphs? |
242,701 | def gfonts_repo_structure ( fonts ) : from fontbakery . utils import get_absolute_path abspath = get_absolute_path ( fonts [ 0 ] ) return abspath . split ( os . path . sep ) [ - 3 ] in [ "ufl" , "ofl" , "apache" ] | The family at the given font path follows the files and directory structure typical of a font project hosted on the Google Fonts repo on GitHub ? |
242,702 | def com_google_fonts_check_repo_dirname_match_nameid_1 ( fonts , gfonts_repo_structure ) : from fontTools . ttLib import TTFont from fontbakery . utils import ( get_name_entry_strings , get_absolute_path , get_regular ) regular = get_regular ( fonts ) if not regular : yield FAIL , "The font seems to lack a regular." en... | Directory name in GFonts repo structure must match NameID 1 of the regular . |
242,703 | def com_google_fonts_check_family_panose_proportion ( ttFonts ) : failed = False proportion = None for ttFont in ttFonts : if proportion is None : proportion = ttFont [ 'OS/2' ] . panose . bProportion if proportion != ttFont [ 'OS/2' ] . panose . bProportion : failed = True if failed : yield FAIL , ( "PANOSE proportion... | Fonts have consistent PANOSE proportion? |
242,704 | def com_google_fonts_check_family_panose_familytype ( ttFonts ) : failed = False familytype = None for ttfont in ttFonts : if familytype is None : familytype = ttfont [ 'OS/2' ] . panose . bFamilyType if familytype != ttfont [ 'OS/2' ] . panose . bFamilyType : failed = True if failed : yield FAIL , ( "PANOSE family typ... | Fonts have consistent PANOSE family type? |
242,705 | def com_google_fonts_check_code_pages ( ttFont ) : if not hasattr ( ttFont [ 'OS/2' ] , "ulCodePageRange1" ) or not hasattr ( ttFont [ 'OS/2' ] , "ulCodePageRange2" ) or ( ttFont [ 'OS/2' ] . ulCodePageRange1 == 0 and ttFont [ 'OS/2' ] . ulCodePageRange2 == 0 ) : yield FAIL , ( "No code pages defined in the OS/2 table"... | Check code page character ranges |
242,706 | def com_google_fonts_check_glyf_unused_data ( ttFont ) : try : expected_glyphs = len ( ttFont . getGlyphOrder ( ) ) actual_glyphs = len ( ttFont [ 'glyf' ] . glyphs ) diff = actual_glyphs - expected_glyphs if diff < 0 : yield FAIL , Message ( "unreachable-data" , ( "Glyf table has unreachable data at the end of " " the... | Is there any unused data at the end of the glyf table? |
242,707 | def com_google_fonts_check_points_out_of_bounds ( ttFont ) : failed = False out_of_bounds = [ ] for glyphName in ttFont [ 'glyf' ] . keys ( ) : glyph = ttFont [ 'glyf' ] [ glyphName ] coords = glyph . getCoordinates ( ttFont [ 'glyf' ] ) [ 0 ] for x , y in coords : if x < glyph . xMin or x > glyph . xMax or y < glyph .... | Check for points out of bounds . |
242,708 | def com_daltonmaag_check_ufolint ( font ) : import subprocess ufolint_cmd = [ "ufolint" , font ] try : subprocess . check_output ( ufolint_cmd , stderr = subprocess . STDOUT ) except subprocess . CalledProcessError as e : yield FAIL , ( "ufolint failed the UFO source. Output follows :" "\n\n{}\n" ) . format ( e . outpu... | Run ufolint on UFO source directory . |
242,709 | def com_daltonmaag_check_required_fields ( ufo_font ) : recommended_fields = [ ] for field in [ "unitsPerEm" , "ascender" , "descender" , "xHeight" , "capHeight" , "familyName" ] : if ufo_font . info . __dict__ . get ( "_" + field ) is None : recommended_fields . append ( field ) if recommended_fields : yield FAIL , f"... | Check that required fields are present in the UFO fontinfo . |
242,710 | def com_daltonmaag_check_recommended_fields ( ufo_font ) : recommended_fields = [ ] for field in [ "postscriptUnderlineThickness" , "postscriptUnderlinePosition" , "versionMajor" , "versionMinor" , "styleName" , "copyright" , "openTypeOS2Panose" ] : if ufo_font . info . __dict__ . get ( "_" + field ) is None : recommen... | Check that recommended fields are present in the UFO fontinfo . |
242,711 | def com_daltonmaag_check_unnecessary_fields ( ufo_font ) : unnecessary_fields = [ ] for field in [ "openTypeNameUniqueID" , "openTypeNameVersion" , "postscriptUniqueID" , "year" ] : if ufo_font . info . __dict__ . get ( "_" + field ) is not None : unnecessary_fields . append ( field ) if unnecessary_fields : yield WARN... | Check that no unnecessary fields are present in the UFO fontinfo . |
242,712 | def setup_argparse ( self , argument_parser ) : import glob import logging import argparse def get_fonts ( pattern ) : fonts_to_check = [ ] for fullpath in glob . glob ( pattern ) : fullpath_absolute = os . path . abspath ( fullpath ) if fullpath_absolute . lower ( ) . endswith ( ".ufo" ) and os . path . isdir ( fullpa... | Set up custom arguments needed for this profile . |
242,713 | def com_google_fonts_check_whitespace_widths ( ttFont ) : from fontbakery . utils import get_glyph_name space_name = get_glyph_name ( ttFont , 0x0020 ) nbsp_name = get_glyph_name ( ttFont , 0x00A0 ) space_width = ttFont [ 'hmtx' ] [ space_name ] [ 0 ] nbsp_width = ttFont [ 'hmtx' ] [ nbsp_name ] [ 0 ] if space_width > ... | Whitespace and non - breaking space have the same width? |
242,714 | def update_by_config ( self , config_dict ) : policy_enabling_map = self . _get_enabling_map ( config_dict ) self . enabled_policies = [ ] for policy_name , is_policy_enabled in policy_enabling_map . items ( ) : if not self . _is_policy_exists ( policy_name ) : self . _warn_unexistent_policy ( policy_name ) continue if... | Update policies set by the config dictionary . |
242,715 | def _build_cmdargs ( argv ) : parser = _build_arg_parser ( ) namespace = parser . parse_args ( argv [ 1 : ] ) cmdargs = vars ( namespace ) return cmdargs | Build command line arguments dict to use ; - displaying usages - vint . linting . env . build_environment |
242,716 | def parse ( self , lint_target ) : decoder = Decoder ( default_decoding_strategy ) decoded = decoder . decode ( lint_target . read ( ) ) decoded_and_lf_normalized = decoded . replace ( '\r\n' , '\n' ) return self . parse_string ( decoded_and_lf_normalized ) | Parse vim script file and return the AST . |
242,717 | def parse_string ( self , string ) : lines = string . split ( '\n' ) reader = vimlparser . StringReader ( lines ) parser = vimlparser . VimLParser ( self . _enable_neovim ) ast = parser . parse ( reader ) ast [ 'pos' ] = { 'col' : 1 , 'i' : 0 , 'lnum' : 1 } for plugin in self . plugins : plugin . process ( ast ) return... | Parse vim script string and return the AST . |
242,718 | def parse_string_expr ( self , string_expr_node ) : string_expr_node_value = string_expr_node [ 'value' ] string_expr_str = string_expr_node_value [ 1 : - 1 ] if string_expr_node_value [ 0 ] == "'" : string_expr_str = string_expr_str . replace ( "''" , "'" ) else : string_expr_str = string_expr_str . replace ( '\\"' , ... | Parse a string node content . |
242,719 | def is_builtin_variable ( id_node ) : if NodeType ( id_node [ 'type' ] ) is not NodeType . IDENTIFIER : return False id_value = id_node [ 'value' ] if id_value . startswith ( 'v:' ) : return True if is_builtin_function ( id_node ) : return True if id_value in [ 'key' , 'val' ] : return is_on_lambda_string_context ( id_... | Whether the specified node is a builtin identifier . |
242,720 | def is_builtin_function ( id_node ) : if NodeType ( id_node [ 'type' ] ) is not NodeType . IDENTIFIER : return False id_value = id_node [ 'value' ] if not is_function_identifier ( id_node ) : return False return id_value in BuiltinFunctions | Whether the specified node is a builtin function name identifier . The given identifier should be a child node of NodeType . CALL . |
242,721 | def attach_identifier_attributes ( self , ast ) : redir_assignment_parser = RedirAssignmentParser ( ) ast_with_parsed_redir = redir_assignment_parser . process ( ast ) map_and_filter_parser = CallNodeParser ( ) ast_with_parse_map_and_filter_and_redir = map_and_filter_parser . process ( ast_with_parsed_redir ) traverse ... | Attach 5 flags to the AST . |
242,722 | def create_violation_report ( self , node , lint_context ) : return { 'name' : self . name , 'level' : self . level , 'description' : self . description , 'reference' : self . reference , 'position' : { 'line' : node [ 'pos' ] [ 'lnum' ] , 'column' : node [ 'pos' ] [ 'col' ] , 'path' : lint_context [ 'lint_target' ] . ... | Returns a violation report for the node . |
242,723 | def get_policy_config ( self , lint_context ) : policy_config = lint_context [ 'config' ] . get ( 'policies' , { } ) . get ( self . __class__ . __name__ , { } ) return policy_config | Returns a config of the concrete policy . For example a config of ProhibitSomethingEvil is located on config . policies . ProhibitSomethingEvil . |
242,724 | def get_violation_if_found ( self , node , lint_context ) : if self . is_valid ( node , lint_context ) : return None return self . create_violation_report ( node , lint_context ) | Returns a violation if the node is invalid . |
242,725 | def import_all_policies ( ) : pkg_name = _get_policy_package_name_for_test ( ) pkg_path_list = pkg_name . split ( '.' ) pkg_path = str ( Path ( _get_vint_root ( ) , * pkg_path_list ) . resolve ( ) ) for _ , module_name , is_pkg in pkgutil . iter_modules ( [ pkg_path ] ) : if not is_pkg : module_fqn = pkg_name + '.' + m... | Import all policies that were registered by vint . linting . policy_registry . |
242,726 | def process ( self , ast ) : id_classifier = IdentifierClassifier ( ) attached_ast = id_classifier . attach_identifier_attributes ( ast ) self . _scope_tree_builder . enter_new_scope ( ScopeVisibility . SCRIPT_LOCAL ) traverse ( attached_ast , on_enter = self . _enter_handler , on_leave = self . _leave_handler ) self .... | Build a scope tree and links between scopes and identifiers by the specified ast . You can access the built scope tree and the built links by . scope_tree and . link_registry . |
242,727 | def cli ( argv = None ) : kwargs = parse_arguments ( argv or sys . argv [ 1 : ] ) log_level = kwargs . pop ( 'log_level' ) logging . basicConfig ( format = '%(levelname)s | %(message)s' , level = log_level ) logger = logging . getLogger ( __name__ ) sub_log_level = logging . ERROR if log_level == logging . getLevelName... | CLI entry point for mozdownload . |
242,728 | def query_builds_by_revision ( self , revision , job_type_name = 'Build' , debug_build = False ) : builds = set ( ) try : self . logger . info ( 'Querying {url} for list of builds for revision: {revision}' . format ( url = self . client . server_url , revision = revision ) ) option_hash = None for key , values in self ... | Retrieve build folders for a given revision with the help of Treeherder . |
242,729 | def urljoin ( * fragments ) : parts = [ fragment . rstrip ( '/' ) for fragment in fragments [ : len ( fragments ) - 1 ] ] parts . append ( fragments [ - 1 ] ) return '/' . join ( parts ) | Concatenate multi part strings into urls . |
242,730 | def create_md5 ( path ) : m = hashlib . md5 ( ) with open ( path , "rb" ) as f : while True : data = f . read ( 8192 ) if not data : break m . update ( data ) return m . hexdigest ( ) | Create the md5 hash of a file using the hashlib library . |
242,731 | def filter ( self , filter ) : if hasattr ( filter , '__call__' ) : return [ entry for entry in self . entries if filter ( entry ) ] else : pattern = re . compile ( filter , re . IGNORECASE ) return [ entry for entry in self . entries if pattern . match ( entry ) ] | Filter entries by calling function or applying regex . |
242,732 | def handle_starttag ( self , tag , attrs ) : if not tag == 'a' : return for attr in attrs : if attr [ 0 ] == 'href' : url = urllib . unquote ( attr [ 1 ] ) self . active_url = url . rstrip ( '/' ) . split ( '/' ) [ - 1 ] return | Callback for when a tag gets opened . |
242,733 | def handle_data ( self , data ) : if not self . active_url : return if data . strip ( '/' ) == self . active_url : self . entries . append ( self . active_url ) | Callback when the data of a tag has been collected . |
242,734 | def dst ( self , dt ) : dst_start_date = self . first_sunday ( dt . year , 3 ) + timedelta ( days = 7 ) + timedelta ( hours = 2 ) dst_end_date = self . first_sunday ( dt . year , 11 ) + timedelta ( hours = 2 ) if dst_start_date <= dt . replace ( tzinfo = None ) < dst_end_date : return timedelta ( hours = 1 ) else : ret... | Calculate delta for daylight saving . |
242,735 | def first_sunday ( self , year , month ) : date = datetime ( year , month , 1 , 0 ) days_until_sunday = 6 - date . weekday ( ) return date + timedelta ( days = days_until_sunday ) | Get the first sunday of a month . |
242,736 | def binary ( self ) : def _get_binary ( ) : parser = self . _create_directory_parser ( self . path ) if not parser . entries : raise errors . NotFoundError ( 'No entries found' , self . path ) pattern = re . compile ( self . binary_regex , re . IGNORECASE ) for entry in parser . entries : try : self . _binary = pattern... | Return the name of the build . |
242,737 | def url ( self ) : return urllib . quote ( urljoin ( self . path , self . binary ) , safe = '%/:=&?~#+!$,;\'@()*[]|' ) | Return the URL of the build . |
242,738 | def filename ( self ) : if self . _filename is None : if os . path . splitext ( self . destination ) [ 1 ] : target_file = self . destination else : target_file = os . path . join ( self . destination , self . build_filename ( self . binary ) ) self . _filename = os . path . abspath ( target_file ) return self . _filen... | Return the local filename of the build . |
242,739 | def download ( self ) : def total_seconds ( td ) : if hasattr ( td , 'total_seconds' ) : return td . total_seconds ( ) else : return ( td . microseconds + ( td . seconds + td . days * 24 * 3600 ) * 10 ** 6 ) / 10 ** 6 if os . path . isfile ( os . path . abspath ( self . filename ) ) : self . logger . info ( "File has a... | Download the specified file . |
242,740 | def show_matching_builds ( self , builds ) : self . logger . info ( 'Found %s build%s: %s' % ( len ( builds ) , len ( builds ) > 1 and 's' or '' , len ( builds ) > 10 and ' ... ' . join ( [ ', ' . join ( builds [ : 5 ] ) , ', ' . join ( builds [ - 5 : ] ) ] ) or ', ' . join ( builds ) ) ) | Output the matching builds . |
242,741 | def is_build_dir ( self , folder_name ) : url = '%s/' % urljoin ( self . base_url , self . monthly_build_list_regex , folder_name ) if self . application in APPLICATIONS_MULTI_LOCALE and self . locale != 'multi' : url = '%s/' % urljoin ( url , self . locale ) parser = self . _create_directory_parser ( url ) pattern = r... | Return whether or not the given dir contains a build . |
242,742 | def get_build_info_for_date ( self , date , build_index = None ) : url = urljoin ( self . base_url , self . monthly_build_list_regex ) has_time = date and date . time ( ) self . logger . info ( 'Retrieving list of builds from %s' % url ) parser = self . _create_directory_parser ( url ) regex = r'%(DATE)s-(\d+-)+%(BRANC... | Return the build information for a given date . |
242,743 | def monthly_build_list_regex ( self ) : return r'nightly/%(YEAR)s/%(MONTH)s/' % { 'YEAR' : self . date . year , 'MONTH' : str ( self . date . month ) . zfill ( 2 ) } | Return the regex for the folder containing builds of a month . |
242,744 | def filename ( self ) : if os . path . splitext ( self . destination ) [ 1 ] : target_file = self . destination else : parsed_url = urlparse ( self . url ) source_filename = ( parsed_url . path . rpartition ( '/' ) [ - 1 ] or parsed_url . hostname ) target_file = os . path . join ( self . destination , source_filename ... | File name of the downloaded file . |
242,745 | def query_versions ( self , version = None ) : if version not in RELEASE_AND_CANDIDATE_LATEST_VERSIONS : return [ version ] url = urljoin ( self . base_url , 'releases/' ) parser = self . _create_directory_parser ( url ) if version : versions = parser . filter ( RELEASE_AND_CANDIDATE_LATEST_VERSIONS [ version ] ) from ... | Check specified version and resolve special values . |
242,746 | def build_list_regex ( self ) : regex = 'tinderbox-builds/%(BRANCH)s-%(PLATFORM)s%(L10N)s%(DEBUG)s/' return regex % { 'BRANCH' : self . branch , 'PLATFORM' : '' if self . locale_build else self . platform_regex , 'L10N' : 'l10n' if self . locale_build else '' , 'DEBUG' : '-debug' if self . debug_build else '' } | Return the regex for the folder which contains the list of builds . |
242,747 | def date_matches ( self , timestamp ) : if self . date is None : return False timestamp = datetime . fromtimestamp ( float ( timestamp ) , self . timezone ) if self . date . date ( ) == timestamp . date ( ) : return True return False | Determine whether the timestamp date is equal to the argument date . |
242,748 | def get_build_info_for_index ( self , build_index = None ) : url = urljoin ( self . base_url , self . build_list_regex ) self . logger . info ( 'Retrieving list of builds from %s' % url ) parser = self . _create_directory_parser ( url ) parser . entries = parser . filter ( r'^\d+$' ) if self . timestamp : parser . entr... | Get additional information for the build at the given index . |
242,749 | def create_default_options_getter ( ) : options = [ ] try : ttyname = subprocess . check_output ( args = [ 'tty' ] ) . strip ( ) options . append ( b'ttyname=' + ttyname ) except subprocess . CalledProcessError as e : log . warning ( 'no TTY found: %s' , e ) display = os . environ . get ( 'DISPLAY' ) if display is not ... | Return current TTY and DISPLAY settings for GnuPG pinentry . |
242,750 | def write ( p , line ) : log . debug ( '%s <- %r' , p . args , line ) p . stdin . write ( line ) p . stdin . flush ( ) | Send and flush a single line to the subprocess stdin . |
242,751 | def expect ( p , prefixes , confidential = False ) : resp = p . stdout . readline ( ) log . debug ( '%s -> %r' , p . args , resp if not confidential else '********' ) for prefix in prefixes : if resp . startswith ( prefix ) : return resp [ len ( prefix ) : ] raise UnexpectedError ( resp ) | Read a line and return it without required prefix . |
242,752 | def interact ( title , description , prompt , binary , options ) : args = [ binary ] p = subprocess . Popen ( args = args , stdin = subprocess . PIPE , stdout = subprocess . PIPE , env = os . environ ) p . args = args expect ( p , [ b'OK' ] ) title = util . assuan_serialize ( title . encode ( 'ascii' ) ) write ( p , b'... | Use GPG pinentry program to interact with the user . |
242,753 | def get_passphrase ( self , prompt = 'Passphrase:' ) : passphrase = None if self . cached_passphrase_ack : passphrase = self . cached_passphrase_ack . get ( ) if passphrase is None : passphrase = interact ( title = '{} passphrase' . format ( self . device_name ) , prompt = prompt , description = None , binary = self . ... | Ask the user for passphrase . |
242,754 | def export_public_keys ( self , identities ) : public_keys = [ ] with self . device : for i in identities : pubkey = self . device . pubkey ( identity = i ) vk = formats . decompress_pubkey ( pubkey = pubkey , curve_name = i . curve_name ) public_key = formats . export_public_key ( vk = vk , label = i . to_string ( ) )... | Export SSH public keys from the device . |
242,755 | def sign_ssh_challenge ( self , blob , identity ) : msg = _parse_ssh_blob ( blob ) log . debug ( '%s: user %r via %r (%r)' , msg [ 'conn' ] , msg [ 'user' ] , msg [ 'auth' ] , msg [ 'key_type' ] ) log . debug ( 'nonce: %r' , msg [ 'nonce' ] ) fp = msg [ 'public_key' ] [ 'fingerprint' ] log . debug ( 'fingerprint: %s' ,... | Sign given blob using a private key on the device . |
242,756 | def fingerprint ( blob ) : digest = hashlib . md5 ( blob ) . digest ( ) return ':' . join ( '{:02x}' . format ( c ) for c in bytearray ( digest ) ) | Compute SSH fingerprint for specified blob . |
242,757 | def parse_pubkey ( blob ) : fp = fingerprint ( blob ) s = io . BytesIO ( blob ) key_type = util . read_frame ( s ) log . debug ( 'key type: %s' , key_type ) assert key_type in SUPPORTED_KEY_TYPES , key_type result = { 'blob' : blob , 'type' : key_type , 'fingerprint' : fp } if key_type == SSH_NIST256_KEY_TYPE : curve_n... | Parse SSH public key from given blob . |
242,758 | def export_public_key ( vk , label ) : key_type , blob = serialize_verifying_key ( vk ) log . debug ( 'fingerprint: %s' , fingerprint ( blob ) ) b64 = base64 . b64encode ( blob ) . decode ( 'ascii' ) return u'{} {} {}\n' . format ( key_type . decode ( 'ascii' ) , b64 , label ) | Export public key to text format . |
242,759 | def import_public_key ( line ) : log . debug ( 'loading SSH public key: %r' , line ) file_type , base64blob , name = line . split ( ) blob = base64 . b64decode ( base64blob ) result = parse_pubkey ( blob ) result [ 'name' ] = name . encode ( 'utf-8' ) assert result [ 'type' ] == file_type . encode ( 'ascii' ) log . deb... | Parse public key textual format as saved at a . pub file . |
242,760 | def parse_packets ( stream ) : reader = util . Reader ( stream ) while True : try : value = reader . readfmt ( 'B' ) except EOFError : return log . debug ( 'prefix byte: %s' , bin ( value ) ) assert util . bit ( value , 7 ) == 1 tag = util . low_bits ( value , 6 ) if util . bit ( value , 6 ) == 0 : length_type = util .... | Support iterative parsing of available GPG packets . |
242,761 | def digest_packets ( packets , hasher ) : data_to_hash = io . BytesIO ( ) for p in packets : data_to_hash . write ( p [ '_to_hash' ] ) hasher . update ( data_to_hash . getvalue ( ) ) return hasher . digest ( ) | Compute digest on specified packets according to _to_hash field . |
242,762 | def load_by_keygrip ( pubkey_bytes , keygrip ) : stream = io . BytesIO ( pubkey_bytes ) packets = list ( parse_packets ( stream ) ) packets_per_pubkey = [ ] for p in packets : if p [ 'type' ] == 'pubkey' : packets_per_pubkey . append ( [ ] ) packets_per_pubkey [ - 1 ] . append ( p ) for packets in packets_per_pubkey : ... | Return public key and first user ID for specified keygrip . |
242,763 | def load_signature ( stream , original_data ) : signature , = list ( parse_packets ( ( stream ) ) ) hash_alg = HASH_ALGORITHMS [ signature [ 'hash_alg' ] ] digest = digest_packets ( [ { '_to_hash' : original_data } , signature ] , hasher = hashlib . new ( hash_alg ) ) assert signature [ 'hash_prefix' ] == digest [ : 2 ... | Load signature from stream and compute GPG digest for verification . |
242,764 | def remove_armor ( armored_data ) : stream = io . BytesIO ( armored_data ) lines = stream . readlines ( ) [ 3 : - 1 ] data = base64 . b64decode ( b'' . join ( lines ) ) payload , checksum = data [ : - 3 ] , data [ - 3 : ] assert util . crc24 ( payload ) == checksum return payload | Decode armored data into its binary form . |
242,765 | def remove_file ( path , remove = os . remove , exists = os . path . exists ) : try : remove ( path ) except OSError : if exists ( path ) : raise | Remove file and raise OSError if still exists . |
242,766 | def unix_domain_socket_server ( sock_path ) : log . debug ( 'serving on %s' , sock_path ) remove_file ( sock_path ) server = socket . socket ( socket . AF_UNIX , socket . SOCK_STREAM ) server . bind ( sock_path ) server . listen ( 1 ) try : yield server finally : remove_file ( sock_path ) | Create UNIX - domain socket on specified path . |
242,767 | def handle_connection ( conn , handler , mutex ) : try : log . debug ( 'welcome agent' ) with contextlib . closing ( conn ) : while True : msg = util . read_frame ( conn ) with mutex : reply = handler . handle ( msg = msg ) util . send ( conn , reply ) except EOFError : log . debug ( 'goodbye agent' ) except Exception ... | Handle a single connection using the specified protocol handler in a loop . |
242,768 | def retry ( func , exception_type , quit_event ) : while True : if quit_event . is_set ( ) : raise StopIteration try : return func ( ) except exception_type : pass | Run the function retrying when the specified exception_type occurs . |
242,769 | def spawn ( func , kwargs ) : t = threading . Thread ( target = func , kwargs = kwargs ) t . start ( ) yield t . join ( ) | Spawn a thread and join it after the context is over . |
242,770 | def run_process ( command , environ ) : log . info ( 'running %r with %r' , command , environ ) env = dict ( os . environ ) env . update ( environ ) try : p = subprocess . Popen ( args = command , env = env ) except OSError as e : raise OSError ( 'cannot run %r: %s' % ( command , e ) ) log . debug ( 'subprocess %d is r... | Run the specified process and wait until it finishes . |
242,771 | def check_output ( args , env = None , sp = subprocess ) : log . debug ( 'calling %s with env %s' , args , env ) output = sp . check_output ( args = args , env = env ) log . debug ( 'output: %r' , output ) return output | Call an external binary and return its stdout . |
242,772 | def get_agent_sock_path ( env = None , sp = subprocess ) : args = [ util . which ( 'gpgconf' ) , '--list-dirs' ] output = check_output ( args = args , env = env , sp = sp ) lines = output . strip ( ) . split ( b'\n' ) dirs = dict ( line . split ( b':' , 1 ) for line in lines ) log . debug ( '%s: %s' , args , dirs ) ret... | Parse gpgconf output to find out GPG agent UNIX socket path . |
242,773 | def connect_to_agent ( env = None , sp = subprocess ) : sock_path = get_agent_sock_path ( sp = sp , env = env ) check_output ( args = [ 'gpg-connect-agent' , '/bye' ] , sp = sp ) sock = socket . socket ( socket . AF_UNIX , socket . SOCK_STREAM ) sock . connect ( sock_path ) return sock | Connect to GPG agent s UNIX socket . |
242,774 | def sendline ( sock , msg , confidential = False ) : log . debug ( '<- %r' , ( '<snip>' if confidential else msg ) ) sock . sendall ( msg + b'\n' ) | Send a binary message followed by EOL . |
242,775 | def recvline ( sock ) : reply = io . BytesIO ( ) while True : c = sock . recv ( 1 ) if not c : return None if c == b'\n' : break reply . write ( c ) result = reply . getvalue ( ) log . debug ( '-> %r' , result ) return result | Receive a single line from the socket . |
242,776 | def parse_term ( s ) : size , s = s . split ( b':' , 1 ) size = int ( size ) return s [ : size ] , s [ size : ] | Parse single s - expr term from bytes . |
242,777 | def parse ( s ) : if s . startswith ( b'(' ) : s = s [ 1 : ] name , s = parse_term ( s ) values = [ name ] while not s . startswith ( b')' ) : value , s = parse ( s ) values . append ( value ) return values , s [ 1 : ] return parse_term ( s ) | Parse full s - expr from bytes . |
242,778 | def parse_sig ( sig ) : label , sig = sig assert label == b'sig-val' algo_name = sig [ 0 ] parser = { b'rsa' : _parse_rsa_sig , b'ecdsa' : _parse_ecdsa_sig , b'eddsa' : _parse_eddsa_sig , b'dsa' : _parse_dsa_sig } [ algo_name ] return parser ( args = sig [ 1 : ] ) | Parse signature integer values from s - expr . |
242,779 | def sign_digest ( sock , keygrip , digest , sp = subprocess , environ = None ) : hash_algo = 8 assert len ( digest ) == 32 assert communicate ( sock , 'RESET' ) . startswith ( b'OK' ) ttyname = check_output ( args = [ 'tty' ] , sp = sp ) . strip ( ) options = [ 'ttyname={}' . format ( ttyname ) ] display = ( environ or... | Sign a digest using specified key using GPG agent . |
242,780 | def get_gnupg_components ( sp = subprocess ) : args = [ util . which ( 'gpgconf' ) , '--list-components' ] output = check_output ( args = args , sp = sp ) components = dict ( re . findall ( '(.*):.*:(.*)' , output . decode ( 'utf-8' ) ) ) log . debug ( 'gpgconf --list-components: %s' , components ) return components | Parse GnuPG components paths . |
242,781 | def gpg_command ( args , env = None ) : if env is None : env = os . environ cmd = get_gnupg_binary ( neopg_binary = env . get ( 'NEOPG_BINARY' ) ) return [ cmd ] + args | Prepare common GPG command line arguments . |
242,782 | def export_public_key ( user_id , env = None , sp = subprocess ) : args = gpg_command ( [ '--export' , user_id ] ) result = check_output ( args = args , env = env , sp = sp ) if not result : log . error ( 'could not find public key %r in local GPG keyring' , user_id ) raise KeyError ( user_id ) return result | Export GPG public key for specified user_id . |
242,783 | def export_public_keys ( env = None , sp = subprocess ) : args = gpg_command ( [ '--export' ] ) result = check_output ( args = args , env = env , sp = sp ) if not result : raise KeyError ( 'No GPG public keys found at env: {!r}' . format ( env ) ) return result | Export all GPG public keys . |
242,784 | def create_agent_signer ( user_id ) : sock = connect_to_agent ( env = os . environ ) keygrip = get_keygrip ( user_id ) def sign ( digest ) : return sign_digest ( sock = sock , keygrip = keygrip , digest = digest ) return sign | Sign digest with existing GPG keys using gpg - agent tool . |
242,785 | def msg_name ( code ) : ids = { v : k for k , v in COMMANDS . items ( ) } return ids [ code ] | Convert integer message code into a string name . |
242,786 | def _legacy_pubs ( buf ) : leftover = buf . read ( ) if leftover : log . warning ( 'skipping leftover: %r' , leftover ) code = util . pack ( 'B' , msg_code ( 'SSH_AGENT_RSA_IDENTITIES_ANSWER' ) ) num = util . pack ( 'L' , 0 ) return util . frame ( code , num ) | SSH v1 public keys are not supported . |
242,787 | def handle ( self , msg ) : debug_msg = ': {!r}' . format ( msg ) if self . debug else '' log . debug ( 'request: %d bytes%s' , len ( msg ) , debug_msg ) buf = io . BytesIO ( msg ) code , = util . recv ( buf , '>B' ) if code not in self . methods : log . warning ( 'Unsupported command: %s (%d)' , msg_name ( code ) , co... | Handle SSH message from the SSH client and return the response . |
242,788 | def list_pubs ( self , buf ) : assert not buf . read ( ) keys = self . conn . parse_public_keys ( ) code = util . pack ( 'B' , msg_code ( 'SSH2_AGENT_IDENTITIES_ANSWER' ) ) num = util . pack ( 'L' , len ( keys ) ) log . debug ( 'available keys: %s' , [ k [ 'name' ] for k in keys ] ) for i , k in enumerate ( keys ) : lo... | SSH v2 public keys are serialized and returned . |
242,789 | def sign_message ( self , buf ) : key = formats . parse_pubkey ( util . read_frame ( buf ) ) log . debug ( 'looking for %s' , key [ 'fingerprint' ] ) blob = util . read_frame ( buf ) assert util . read_frame ( buf ) == b'' assert not buf . read ( ) for k in self . conn . parse_public_keys ( ) : if ( k [ 'fingerprint' ]... | SSH v2 public key authentication is performed . |
242,790 | def recv ( conn , size ) : try : fmt = size size = struct . calcsize ( fmt ) except TypeError : fmt = None try : _read = conn . recv except AttributeError : _read = conn . read res = io . BytesIO ( ) while size > 0 : buf = _read ( size ) if not buf : raise EOFError size = size - len ( buf ) res . write ( buf ) res = re... | Receive bytes from connection socket or stream . |
242,791 | def bytes2num ( s ) : res = 0 for i , c in enumerate ( reversed ( bytearray ( s ) ) ) : res += c << ( i * 8 ) return res | Convert MSB - first bytes to an unsigned integer . |
242,792 | def num2bytes ( value , size ) : res = [ ] for _ in range ( size ) : res . append ( value & 0xFF ) value = value >> 8 assert value == 0 return bytes ( bytearray ( list ( reversed ( res ) ) ) ) | Convert an unsigned integer to MSB - first bytes with specified size . |
242,793 | def frame ( * msgs ) : res = io . BytesIO ( ) for msg in msgs : res . write ( msg ) msg = res . getvalue ( ) return pack ( 'L' , len ( msg ) ) + msg | Serialize MSB - first length - prefixed frame . |
242,794 | def split_bits ( value , * bits ) : result = [ ] for b in reversed ( bits ) : mask = ( 1 << b ) - 1 result . append ( value & mask ) value = value >> b assert value == 0 result . reverse ( ) return result | Split integer value into list of ints according to bits list . |
242,795 | def readfmt ( stream , fmt ) : size = struct . calcsize ( fmt ) blob = stream . read ( size ) return struct . unpack ( fmt , blob ) | Read and unpack an object from stream using a struct format string . |
242,796 | def setup_logging ( verbosity , filename = None ) : levels = [ logging . WARNING , logging . INFO , logging . DEBUG ] level = levels [ min ( verbosity , len ( levels ) - 1 ) ] logging . root . setLevel ( level ) fmt = logging . Formatter ( '%(asctime)s %(levelname)-12s %(message)-100s ' '[%(filename)s:%(lineno)d]' ) hd... | Configure logging for this tool . |
242,797 | def which ( cmd ) : try : from shutil import which as _which except ImportError : from backports . shutil_which import which as _which full_path = _which ( cmd ) if full_path is None : raise OSError ( 'Cannot find {!r} in $PATH' . format ( cmd ) ) log . debug ( 'which %r => %r' , cmd , full_path ) return full_path | Return full path to specified command or raise OSError if missing . |
242,798 | def readfmt ( self , fmt ) : size = struct . calcsize ( fmt ) blob = self . read ( size ) obj , = struct . unpack ( fmt , blob ) return obj | Read a specified object using a struct format string . |
242,799 | def read ( self , size = None ) : blob = self . s . read ( size ) if size is not None and len ( blob ) < size : raise EOFError if self . _captured : self . _captured . write ( blob ) return blob | Read size bytes from stream . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.