idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
240,900 | def config ( filename ) : Config = collections . namedtuple ( 'Config' , [ 'git' , 'lock_file' , 'version' , 'name' , 'src' , 'dst' , 'files' , 'post_commands' , ] ) return [ Config ( ** d ) for d in _get_config_generator ( filename ) ] | Construct Config object and return a list . |
240,901 | def _get_files_config ( src_dir , files_list ) : FilesConfig = collections . namedtuple ( 'FilesConfig' , [ 'src' , 'dst' , 'post_commands' ] ) return [ FilesConfig ( ** d ) for d in _get_files_generator ( src_dir , files_list ) ] | Construct FileConfig object and return a list . |
240,902 | def _get_config ( filename ) : i = interpolation . Interpolator ( interpolation . TemplateWithDefaults , os . environ ) with open ( filename , 'r' ) as stream : try : interpolated_config = i . interpolate ( stream . read ( ) ) return yaml . safe_load ( interpolated_config ) except yaml . parser . ParserError as e : msg... | Parse the provided YAML file and return a dict . |
240,903 | def _get_dst_dir ( dst_dir ) : wd = os . getcwd ( ) _makedirs ( dst_dir ) return os . path . join ( wd , dst_dir ) | Prefix the provided string with working directory and return a str . |
240,904 | def _makedirs ( path ) : dirname , _ = os . path . split ( path ) try : os . makedirs ( dirname ) except OSError as exc : if exc . errno == errno . EEXIST : pass else : raise | Create a base directory of the provided path and return None . |
240,905 | def main ( ctx , config , debug ) : ctx . obj = { } ctx . obj [ 'args' ] = { } ctx . obj [ 'args' ] [ 'debug' ] = debug ctx . obj [ 'args' ] [ 'config' ] = config | gilt - A GIT layering tool . |
240,906 | def overlay ( ctx ) : args = ctx . obj . get ( 'args' ) filename = args . get ( 'config' ) debug = args . get ( 'debug' ) _setup ( filename ) for c in config . config ( filename ) : with fasteners . InterProcessLock ( c . lock_file ) : util . print_info ( '{}:' . format ( c . name ) ) if not os . path . exists ( c . sr... | Install gilt dependencies |
240,907 | def clone ( name , repository , destination , debug = False ) : msg = ' - cloning {} to {}' . format ( name , destination ) util . print_info ( msg ) cmd = sh . git . bake ( 'clone' , repository , destination ) util . run_command ( cmd , debug = debug ) | Clone the specified repository into a temporary directory and return None . |
240,908 | def _get_version ( version , debug = False ) : if not any ( ( _has_branch ( version , debug ) , _has_tag ( version , debug ) , _has_commit ( version , debug ) ) ) : cmd = sh . git . bake ( 'fetch' ) util . run_command ( cmd , debug = debug ) cmd = sh . git . bake ( 'checkout' , version ) util . run_command ( cmd , debu... | Handle switching to the specified version and return None . |
240,909 | def _has_commit ( version , debug = False ) : if _has_tag ( version , debug ) or _has_branch ( version , debug ) : return False cmd = sh . git . bake ( 'cat-file' , '-e' , version ) try : util . run_command ( cmd , debug = debug ) return True except sh . ErrorReturnCode : return False | Determine a version is a local git commit sha or not . |
240,910 | def _has_tag ( version , debug = False ) : cmd = sh . git . bake ( 'show-ref' , '--verify' , '--quiet' , "refs/tags/{}" . format ( version ) ) try : util . run_command ( cmd , debug = debug ) return True except sh . ErrorReturnCode : return False | Determine a version is a local git tag name or not . |
240,911 | def run_command ( cmd , debug = False ) : if debug : msg = ' PWD: {}' . format ( os . getcwd ( ) ) print_warn ( msg ) msg = ' COMMAND: {}' . format ( cmd ) print_warn ( msg ) cmd ( ) | Execute the given command and return None . |
240,912 | def build_sh_cmd ( cmd , cwd = None ) : args = cmd . split ( ) return getattr ( sh , args [ 0 ] ) . bake ( _cwd = cwd , * args [ 1 : ] ) | Build a sh . Command from a string . |
240,913 | def copy ( src , dst ) : try : shutil . copytree ( src , dst ) except OSError as exc : if exc . errno == errno . ENOTDIR : shutil . copy ( src , dst ) else : raise | Handle the copying of a file or directory . |
240,914 | def to_dict ( self ) : return { 'schema' : self . schema , 'name' : self . name , 'columns' : [ col . to_dict ( ) for col in self . _columns ] , 'foreign_keys' : self . foreign_keys . to_dict ( ) , 'ref_keys' : self . ref_keys . to_dict ( ) } | Serialize representation of the table for local caching . |
240,915 | def list_profiles ( ) : profiles = { } user = os . path . expanduser ( "~" ) for f in os . listdir ( user ) : if f . startswith ( ".db.py_" ) : profile = load_from_json ( os . path . join ( user , f ) ) tables = profile . pop ( 'tables' , None ) if tables : profile [ 'metadata' ] = True else : profile [ 'metadata' ] = ... | Lists all of the database profiles available |
240,916 | def remove_profile ( name , s3 = False ) : user = os . path . expanduser ( "~" ) if s3 : f = os . path . join ( user , S3_PROFILE_ID + name ) else : f = os . path . join ( user , DBPY_PROFILE_ID + name ) try : try : open ( f ) except : raise Exception ( "Profile '{0}' does not exist. Could not find file {1}" . format (... | Removes a profile from your config |
240,917 | def tables ( self ) : if len ( self . _tables ) == 0 : self . refresh_schema ( self . _exclude_system_tables , self . _use_cache ) return self . _tables | A lazy loaded reference to the table metadata for the DB . |
240,918 | def save_credentials ( self , profile = "default" ) : f = profile_path ( DBPY_PROFILE_ID , profile ) dump_to_json ( f , self . credentials ) | Save your database credentials so you don t have to save them in script . |
240,919 | def save_metadata ( self , profile = "default" ) : if len ( self . tables ) > 0 : f = profile_path ( DBPY_PROFILE_ID , profile ) dump_to_json ( f , self . to_dict ( ) ) | Save the database credentials plus the database properties to your db . py profile . |
240,920 | def credentials ( self ) : if self . filename : db_filename = os . path . join ( os . getcwd ( ) , self . filename ) else : db_filename = None return { "username" : self . username , "password" : self . password , "hostname" : self . hostname , "port" : self . port , "filename" : db_filename , "dbname" : self . dbname ... | Dict representation of all credentials for the database . |
240,921 | def find_table ( self , search ) : tables = [ ] for table in self . tables : if glob . fnmatch . fnmatch ( table . name , search ) : tables . append ( table ) return TableSet ( tables ) | Aggresively search through your database s schema for a table . |
240,922 | def find_column ( self , search , data_type = None ) : if isinstance ( data_type , str ) : data_type = [ data_type ] cols = [ ] for table in self . tables : for col in vars ( table ) : if glob . fnmatch . fnmatch ( col , search ) : if data_type and isinstance ( getattr ( table , col ) , Column ) and getattr ( table , c... | Aggresively search through your database s schema for a column . |
240,923 | def query ( self , q , data = None , union = True , limit = None ) : if data : q = self . _apply_handlebars ( q , data , union ) if limit : q = self . _assign_limit ( q , limit ) return pd . read_sql ( q , self . con ) | Query your database with a raw string . |
240,924 | def query_from_file ( self , filename , data = None , union = True , limit = None ) : with open ( filename ) as fp : q = fp . read ( ) return self . query ( q , data = data , union = union , limit = limit ) | Query your database from a file . |
240,925 | def refresh_schema ( self , exclude_system_tables = True , use_cache = False ) : col_meta , table_meta = self . _get_db_metadata ( exclude_system_tables , use_cache ) tables = self . _gen_tables_from_col_tuples ( col_meta ) if use_cache : self . _tables = TableSet ( [ Table ( self . con , self . _query_templates , tabl... | Pulls your database s schema again and looks for any new tables and columns . |
240,926 | def to_dict ( self ) : db_dict = self . credentials db_dict . update ( self . tables . to_dict ( ) ) return db_dict | Dict representation of the database as credentials plus tables dict representation . |
240,927 | def profile_path ( profile_id , profile ) : user = os . path . expanduser ( "~" ) return os . path . join ( user , profile_id + profile ) | Create full path to given provide for the current user . |
240,928 | def load_from_json ( file_path ) : if os . path . exists ( file_path ) : raw_data = open ( file_path , 'rb' ) . read ( ) return json . loads ( base64 . decodestring ( raw_data ) . decode ( 'utf-8' ) ) | Load the stored data from json and return as a dict . |
240,929 | def save_credentials ( self , profile ) : filename = profile_path ( S3_PROFILE_ID , profile ) creds = { "access_key" : self . access_key , "secret_key" : self . secret_key } dump_to_json ( filename , creds ) | Saves credentials to a dotfile so you can open them grab them later . |
240,930 | def to_dict ( self ) : return { 'schema' : self . schema , 'table' : self . table , 'name' : self . name , 'type' : self . type } | Serialize representation of the column for local caching . |
240,931 | def rate_limit ( self , rate_limit ) : self . _rate_limit = bool ( rate_limit ) self . _rate_limit_last_call = None self . clear_memoized ( ) | Turn on or off rate limiting |
240,932 | def language ( self , lang ) : lang = lang . lower ( ) if self . _lang == lang : return url = self . _api_url tmp = url . replace ( "/{0}." . format ( self . _lang ) , "/{0}." . format ( lang ) ) self . _api_url = tmp self . _lang = lang self . clear_memoized ( ) | Set the language to use ; attempts to change the API URL |
240,933 | def refresh_interval ( self , refresh_interval ) : if isinstance ( refresh_interval , int ) and refresh_interval > 0 : self . _refresh_interval = refresh_interval else : self . _refresh_interval = None | Set the new cache refresh interval |
240,934 | def login ( self , username , password , strict = True ) : params = { "action" : "query" , "meta" : "tokens" , "type" : "login" , "format" : "json" , } token_res = self . _get_response ( params ) if "query" in token_res and "tokens" in token_res [ "query" ] : token = token_res [ "query" ] [ "tokens" ] [ "logintoken" ] ... | Login as specified user |
240,935 | def set_api_url ( self , api_url = "https://{lang}.wikipedia.org/w/api.php" , lang = "en" ) : old_api_url = self . _api_url old_lang = self . _lang self . _lang = lang . lower ( ) self . _api_url = api_url . format ( lang = self . _lang ) try : self . _get_site_info ( ) self . __supported_languages = None except MediaW... | Set the API URL and language |
240,936 | def _reset_session ( self ) : headers = { "User-Agent" : self . _user_agent } self . _session = requests . Session ( ) self . _session . headers . update ( headers ) self . _is_logged_in = False | Set session information |
240,937 | def random ( self , pages = 1 ) : if pages is None or pages < 1 : raise ValueError ( "Number of pages must be greater than 0" ) query_params = { "list" : "random" , "rnnamespace" : 0 , "rnlimit" : pages } request = self . wiki_request ( query_params ) titles = [ page [ "title" ] for page in request [ "query" ] [ "rando... | Request a random page title or list of random titles |
240,938 | def search ( self , query , results = 10 , suggestion = False ) : self . _check_query ( query , "Query must be specified" ) search_params = { "list" : "search" , "srprop" : "" , "srlimit" : results , "srsearch" : query , } if suggestion : search_params [ "srinfo" ] = "suggestion" raw_results = self . wiki_request ( sea... | Search for similar titles |
240,939 | def suggest ( self , query ) : res , suggest = self . search ( query , results = 1 , suggestion = True ) try : title = suggest or res [ 0 ] except IndexError : title = None return title | Gather suggestions based on the provided title or None if no suggestions found |
240,940 | def geosearch ( self , latitude = None , longitude = None , radius = 1000 , title = None , auto_suggest = True , results = 10 , ) : def test_lat_long ( val ) : if not isinstance ( val , Decimal ) : error = ( "Latitude and Longitude must be specified either as " "a Decimal or in formats that can be coerced into " "a Dec... | Search for pages that relate to the provided geocoords or near the page |
240,941 | def opensearch ( self , query , results = 10 , redirect = True ) : self . _check_query ( query , "Query must be specified" ) query_params = { "action" : "opensearch" , "search" : query , "limit" : ( 100 if results > 100 else results ) , "redirects" : ( "resolve" if redirect else "return" ) , "warningsaserror" : True , ... | Execute a MediaWiki opensearch request similar to search box suggestions and conforming to the OpenSearch specification |
240,942 | def prefixsearch ( self , prefix , results = 10 ) : self . _check_query ( prefix , "Prefix must be specified" ) query_params = { "list" : "prefixsearch" , "pssearch" : prefix , "pslimit" : ( "max" if results > 500 else results ) , "psnamespace" : 0 , "psoffset" : 0 , } raw_results = self . wiki_request ( query_params )... | Perform a prefix search using the provided prefix string |
240,943 | def summary ( self , title , sentences = 0 , chars = 0 , auto_suggest = True , redirect = True ) : page_info = self . page ( title , auto_suggest = auto_suggest , redirect = redirect ) return page_info . summarize ( sentences , chars ) | Get the summary for the title in question |
240,944 | def categorytree ( self , category , depth = 5 ) : def __cat_tree_rec ( cat , depth , tree , level , categories , links ) : tree [ cat ] = dict ( ) tree [ cat ] [ "depth" ] = level tree [ cat ] [ "sub-categories" ] = dict ( ) tree [ cat ] [ "links" ] = list ( ) tree [ cat ] [ "parent-categories" ] = list ( ) parent_cat... | Generate the Category Tree for the given categories |
240,945 | def page ( self , title = None , pageid = None , auto_suggest = True , redirect = True , preload = False ) : if ( title is None or title . strip ( ) == "" ) and pageid is None : raise ValueError ( "Either a title or a pageid must be specified" ) elif title : if auto_suggest : temp_title = self . suggest ( title ) if te... | Get MediaWiki page based on the provided title or pageid |
240,946 | def wiki_request ( self , params ) : params [ "format" ] = "json" if "action" not in params : params [ "action" ] = "query" limit = self . _rate_limit last_call = self . _rate_limit_last_call if limit and last_call and last_call + self . _min_wait > datetime . now ( ) : wait_time = ( last_call + self . _min_wait ) - da... | Make a request to the MediaWiki API using the given search parameters |
240,947 | def _get_site_info ( self ) : response = self . wiki_request ( { "meta" : "siteinfo" , "siprop" : "extensions|general" } ) query = response . get ( "query" , None ) if query is None or query . get ( "general" , None ) is None : raise MediaWikiException ( "Missing query in response" ) gen = query . get ( "general" , Non... | Parse out the Wikimedia site information including API Version and Extensions |
240,948 | def _check_error_response ( response , query ) : if "error" in response : http_error = [ "HTTP request timed out." , "Pool queue is full" ] geo_error = [ "Page coordinates unknown." , "One of the parameters gscoord, gspage, gsbbox is required" , "Invalid coordinate provided" , ] err = response [ "error" ] [ "info" ] if... | check for default error messages and throw correct exception |
240,949 | def _get_response ( self , params ) : return self . _session . get ( self . _api_url , params = params , timeout = self . _timeout ) . json ( encoding = "utf8" ) | wrap the call to the requests package |
240,950 | def _post_response ( self , params ) : return self . _session . post ( self . _api_url , data = params , timeout = self . _timeout ) . json ( encoding = "utf8" ) | wrap a post call to the requests package |
240,951 | def parse_all_arguments ( func ) : args = dict ( ) if sys . version_info < ( 3 , 0 ) : func_args = inspect . getargspec ( func ) if func_args . defaults is not None : val = len ( func_args . defaults ) for i , itm in enumerate ( func_args . args [ - val : ] ) : args [ itm ] = func_args . defaults [ i ] else : func_args... | determine all positional and named arguments as a dict |
240,952 | def str_or_unicode ( text ) : encoding = sys . stdout . encoding if sys . version_info > ( 3 , 0 ) : return text . encode ( encoding ) . decode ( encoding ) return text . encode ( encoding ) | handle python 3 unicode and python 2 . 7 byte strings |
240,953 | def is_relative_url ( url ) : if url . startswith ( "#" ) : return None if url . find ( "://" ) > 0 or url . startswith ( "//" ) : return False return True | simple method to determine if a url is relative or absolute |
240,954 | def read_file ( filepath ) : with io . open ( filepath , "r" ) as filepointer : res = filepointer . read ( ) return res | read the file |
240,955 | def _pull_content_revision_parent ( self ) : if self . _revision_id is None : query_params = { "prop" : "extracts|revisions" , "explaintext" : "" , "rvprop" : "ids" , } query_params . update ( self . __title_query_param ( ) ) request = self . mediawiki . wiki_request ( query_params ) page_info = request [ "query" ] [ "... | combine the pulling of these three properties |
240,956 | def section ( self , section_title ) : section = "== {0} ==" . format ( section_title ) try : content = self . content index = content . index ( section ) + len ( section ) while True : if content [ index + 1 ] == "=" : index += 1 else : break except ValueError : return None except IndexError : pass try : next_index = ... | Plain text section content |
240,957 | def parse_section_links ( self , section_title ) : soup = BeautifulSoup ( self . html , "html.parser" ) headlines = soup . find_all ( "span" , { "class" : "mw-headline" } ) tmp_soup = BeautifulSoup ( section_title , "html.parser" ) tmp_sec_title = tmp_soup . get_text ( ) . lower ( ) id_tag = None for headline in headli... | Parse all links within a section |
240,958 | def __load ( self , redirect = True , preload = False ) : query_params = { "prop" : "info|pageprops" , "inprop" : "url" , "ppprop" : "disambiguation" , "redirects" : "" , } query_params . update ( self . __title_query_param ( ) ) request = self . mediawiki . wiki_request ( query_params ) query = request [ "query" ] pag... | load the basic page information |
240,959 | def _raise_page_error ( self ) : if hasattr ( self , "title" ) : raise PageError ( title = self . title ) else : raise PageError ( pageid = self . pageid ) | raise the correct type of page error |
240,960 | def _raise_disambiguation_error ( self , page , pageid ) : query_params = { "prop" : "revisions" , "rvprop" : "content" , "rvparse" : "" , "rvlimit" : 1 , } query_params . update ( self . __title_query_param ( ) ) request = self . mediawiki . wiki_request ( query_params ) html = request [ "query" ] [ "pages" ] [ pageid... | parse and throw a disambiguation error |
240,961 | def _parse_section_links ( self , id_tag ) : soup = BeautifulSoup ( self . html , "html.parser" ) info = soup . find ( "span" , { "id" : id_tag } ) all_links = list ( ) if info is None : return all_links for node in soup . find ( id = id_tag ) . parent . next_siblings : if not isinstance ( node , Tag ) : continue elif ... | given a section id parse the links in the unordered list |
240,962 | def _parse_sections ( self ) : def _list_to_dict ( _dict , path , sec ) : tmp = _dict for elm in path [ : - 1 ] : tmp = tmp [ elm ] tmp [ sec ] = OrderedDict ( ) self . _sections = list ( ) section_regexp = r"\n==* .* ==*\n" found_obj = re . findall ( section_regexp , self . content ) res = OrderedDict ( ) path = list ... | parse sections and TOC |
240,963 | def __pull_combined_properties ( self ) : query_params = { "titles" : self . title , "prop" : "extracts|redirects|links|coordinates|categories|extlinks" , "continue" : dict ( ) , "explaintext" : "" , "exintro" : "" , "rdprop" : "title" , "rdlimit" : "max" , "plnamespace" : 0 , "pllimit" : "max" , "colimit" : "max" , "c... | something here ... |
240,964 | def is_armed ( self ) : alarm_code = self . get_armed_status ( ) if alarm_code == YALE_STATE_ARM_FULL : return True if alarm_code == YALE_STATE_ARM_PARTIAL : return True return False | Return True or False if the system is armed in any way |
240,965 | def linkify ( props ) : match = props [ 'match' ] protocol = match . group ( 1 ) url = match . group ( 2 ) href = protocol + url if props [ 'block' ] [ 'type' ] == BLOCK_TYPES . CODE : return href link_props = { 'href' : href , } if href . startswith ( 'www' ) : link_props [ 'href' ] = 'http://' + href return DOM . cre... | Wrap plain URLs with link tags . |
240,966 | def for_kind ( kind_map , type_ , fallback_key ) : if type_ not in kind_map : if fallback_key not in kind_map : raise ConfigException ( '"%s" is not in the config and has no fallback' % type_ ) config = kind_map [ fallback_key ] else : config = kind_map [ type_ ] if isinstance ( config , dict ) : if 'element' not in co... | Create an Options object from any mapping . |
240,967 | def render ( self , content_state = None ) : if content_state is None : content_state = { } blocks = content_state . get ( 'blocks' , [ ] ) wrapper_state = WrapperState ( self . block_map , blocks ) document = DOM . create_element ( ) entity_map = content_state . get ( 'entityMap' , { } ) min_depth = 0 for block in blo... | Starts the export process on a given piece of content state . |
240,968 | def build_command_groups ( self , block ) : text = block [ 'text' ] commands = sorted ( self . build_commands ( block ) ) grouped = groupby ( commands , Command . key ) listed = list ( groupby ( commands , Command . key ) ) sliced = [ ] i = 0 for start_index , commands in grouped : if i < len ( listed ) - 1 : stop_inde... | Creates block modification commands grouped by start index with the text to apply them on . |
240,969 | def build_commands ( self , block ) : text_commands = Command . start_stop ( 'text' , 0 , len ( block [ 'text' ] ) ) style_commands = self . build_style_commands ( block ) entity_commands = self . build_entity_commands ( block ) return text_commands + style_commands + entity_commands | Build all of the manipulation commands for a given block . - One pair to set the text . - Multiple pairs for styles . - Multiple pairs for entities . |
240,970 | def run ( commands , shell = None , prompt_template = "default" , speed = 1 , quiet = False , test_mode = False , commentecho = False , ) : if not quiet : secho ( "We'll do it live!" , fg = "red" , bold = True ) secho ( "STARTING SESSION: Press Ctrl-C at any time to exit." , fg = "yellow" , bold = True , ) click . paus... | Main function for magic - running a list of commands . |
240,971 | def play ( quiet , session_file , shell , speed , prompt , commentecho ) : run ( session_file . readlines ( ) , shell = shell , speed = speed , quiet = quiet , test_mode = TESTING , prompt_template = prompt , commentecho = commentecho , ) | Play a session file . |
240,972 | def demo ( quiet , shell , speed , prompt , commentecho ) : run ( DEMO , shell = shell , speed = speed , test_mode = TESTING , prompt_template = prompt , quiet = quiet , commentecho = commentecho , ) | Run a demo doitlive session . |
240,973 | def echo ( message = None , file = None , nl = True , err = False , color = None , carriage_return = False ) : message = message or "" if carriage_return and nl : click_echo ( message + "\r\n" , file , False , err , color ) elif carriage_return and not nl : click_echo ( message + "\r" , file , False , err , color ) els... | Patched click echo function . |
240,974 | def magictype ( text , prompt_template = "default" , speed = 1 ) : echo_prompt ( prompt_template ) cursor_position = 0 return_to_regular_type = False with raw_mode ( ) : while True : char = text [ cursor_position : cursor_position + speed ] in_char = getchar ( ) if in_char in { ESC , CTRLC } : echo ( carriage_return = ... | Echo each character in text as keyboard characters are pressed . Characters are echo d speed characters at a time . |
240,975 | def regulartype ( prompt_template = "default" ) : echo_prompt ( prompt_template ) command_string = "" cursor_position = 0 with raw_mode ( ) : while True : in_char = getchar ( ) if in_char in { ESC , CTRLC } : echo ( carriage_return = True ) raise click . Abort ( ) elif in_char == TAB : echo ( "\r" , nl = True ) return ... | Echo each character typed . Unlike magictype this echos the characters the user is pressing . |
240,976 | def regularrun ( shell , prompt_template = "default" , aliases = None , envvars = None , extra_commands = None , speed = 1 , test_mode = False , commentecho = False , ) : loop_again = True command_string = regulartype ( prompt_template ) if command_string == TAB : loop_again = False return loop_again run_command ( comm... | Allow user to run their own live commands until CTRL - Z is pressed again . |
240,977 | def magicrun ( text , shell , prompt_template = "default" , aliases = None , envvars = None , extra_commands = None , speed = 1 , test_mode = False , commentecho = False , ) : goto_regulartype = magictype ( text , prompt_template , speed ) if goto_regulartype : return goto_regulartype run_command ( text , shell , alias... | Echo out each character in text as keyboard characters are pressed wait for a RETURN keypress then run the text in a shell context . |
240,978 | def run_commands ( self ) : more = 0 prompt = sys . ps1 for command in self . commands : try : prompt = sys . ps2 if more else sys . ps1 try : magictype ( command , prompt_template = prompt , speed = self . speed ) except EOFError : self . write ( "\n" ) break else : if command . strip ( ) == "exit()" : return more = s... | Automatically type and execute all commands . |
240,979 | def interact ( self , banner = None ) : try : sys . ps1 except AttributeError : sys . ps1 = ">>>" try : sys . ps2 except AttributeError : sys . ps2 = "... " cprt = ( 'Type "help", "copyright", "credits" or "license" for ' "more information." ) if banner is None : self . write ( "Python %s on %s\n%s\n" % ( sys . version... | Run an interactive session . |
240,980 | def start_ipython_player ( commands , speed = 1 ) : PlayerTerminalIPythonApp . commands = commands PlayerTerminalIPythonApp . speed = speed PlayerTerminalIPythonApp . launch_instance ( ) | Starts a new magic IPython shell . |
240,981 | def on_feed_key ( self , key_press ) : if key_press . key in { Keys . Escape , Keys . ControlC } : echo ( carriage_return = True ) raise Abort ( ) if key_press . key == Keys . Backspace : if self . current_command_pos > 0 : self . current_command_pos -= 1 return key_press ret = None if key_press . key != Keys . CPRResp... | Handles the magictyping when a key is pressed |
240,982 | def init_shell ( self ) : self . shell = PlayerTerminalInteractiveShell . instance ( commands = self . commands , speed = self . speed , parent = self , display_banner = False , profile_dir = self . profile_dir , ipython_dir = self . ipython_dir , user_ns = self . user_ns , ) self . shell . configurables . append ( sel... | initialize the InteractiveShell instance |
240,983 | def raw_mode ( ) : if WIN : yield else : import tty import termios if not isatty ( sys . stdin ) : f = open ( "/dev/tty" ) fd = f . fileno ( ) else : fd = sys . stdin . fileno ( ) f = None try : old_settings = termios . tcgetattr ( fd ) tty . setraw ( fd ) except termios . error : pass try : yield finally : try : termi... | Enables terminal raw mode during the context . |
240,984 | def int_to_string ( number , alphabet , padding = None ) : output = "" alpha_len = len ( alphabet ) while number : number , digit = divmod ( number , alpha_len ) output += alphabet [ digit ] if padding : remainder = max ( padding - len ( output ) , 0 ) output = output + alphabet [ 0 ] * remainder return output [ : : - ... | Convert a number to a string using the given alphabet . The output has the most significant digit first . |
240,985 | def string_to_int ( string , alphabet ) : number = 0 alpha_len = len ( alphabet ) for char in string : number = number * alpha_len + alphabet . index ( char ) return number | Convert a string to a number using the given alphabet . The input is assumed to have the most significant digit first . |
240,986 | def decode ( self , string , legacy = False ) : if legacy : string = string [ : : - 1 ] return _uu . UUID ( int = string_to_int ( string , self . _alphabet ) ) | Decode a string according to the current alphabet into a UUID Raises ValueError when encountering illegal characters or a too - long string . |
240,987 | def set_alphabet ( self , alphabet ) : new_alphabet = list ( sorted ( set ( alphabet ) ) ) if len ( new_alphabet ) > 1 : self . _alphabet = new_alphabet self . _alpha_len = len ( self . _alphabet ) else : raise ValueError ( "Alphabet with more than " "one unique symbols required." ) | Set the alphabet to be used for new UUIDs . |
240,988 | def encoded_length ( self , num_bytes = 16 ) : factor = math . log ( 256 ) / math . log ( self . _alpha_len ) return int ( math . ceil ( factor * num_bytes ) ) | Returns the string length of the shortened UUID . |
240,989 | def asm_module ( exprs , dst_reg , sym_to_reg , triple_or_target = None ) : if not llvmlite_available : raise RuntimeError ( "llvmlite module unavailable! can't assemble..." ) target = llvm_get_target ( triple_or_target ) M = ll . Module ( ) fntype = ll . FunctionType ( ll . VoidType ( ) , [ ] ) func = ll . Function ( ... | Generate an LLVM module for a list of expressions |
240,990 | def asm_binary ( exprs , dst_reg , sym_to_reg , triple_or_target = None ) : if not llvmlite_available : raise RuntimeError ( "llvmlite module unavailable! can't assemble..." ) target = llvm_get_target ( triple_or_target ) M = asm_module ( exprs , dst_reg , sym_to_reg , target ) M = llvm . parse_assembly ( str ( M ) ) M... | Compile and assemble an expression for a given architecture . |
240,991 | def expr_contains ( e , o ) : if o == e : return True if e . has_args ( ) : for a in e . args ( ) : if expr_contains ( a , o ) : return True return False | Returns true if o is in e |
240,992 | def zext ( self , n ) : if n <= self . nbits : raise ValueError ( "n must be > %d bits" % self . nbits ) mba_ret = self . __new_mba ( n ) ret = mba_ret . from_cst ( 0 ) for i in range ( self . nbits ) : ret . vec [ i ] = self . vec [ i ] return mba_ret . from_vec ( ret ) | Zero - extend the variable to n bits . n bits must be stricly larger than the actual number of bits or a ValueError is thrown |
240,993 | def sext ( self , n ) : if n <= self . nbits : raise ValueError ( "n must be > %d bits" % self . nbits ) mba_ret = self . __new_mba ( n ) ret = mba_ret . from_cst ( 0 ) for i in range ( self . nbits ) : ret . vec [ i ] = self . vec [ i ] last_bit = self . vec [ self . nbits - 1 ] for i in range ( self . nbits , n ) : r... | Sign - extend the variable to n bits . n bits must be stricly larger than the actual number of bits or a ValueError is thrown |
240,994 | def evaluate ( self , values ) : ret = self . mba . evaluate ( self . vec , values ) if isinstance ( ret , six . integer_types ) : return ret return self . from_vec ( self . mba , ret ) | Evaluates the expression to an integer |
240,995 | def vectorial_decomp ( self , symbols ) : try : symbols = [ s . vec for s in symbols ] N = sum ( map ( lambda s : len ( s ) , symbols ) ) symbols_ = Vector ( N ) i = 0 for v in symbols : for s in v : symbols_ [ i ] = s i += 1 symbols = symbols_ except TypeError : pass return self . mba . vectorial_decomp ( symbols , se... | Compute the vectorial decomposition of the expression according to the given symbols . |
240,996 | def var ( self , name ) : ret = self . from_vec ( self . var_symbols ( name ) ) ret . name = name return ret | Get an n - bit named symbolic variable |
240,997 | def permut2expr ( self , P ) : if len ( P ) > ( 1 << self . nbits ) : raise ValueError ( "P must not contain more than %d elements" % ( 1 << self . nbits ) ) X = self . var ( 'X' ) ret = super ( MBA , self ) . permut2expr ( P , X . vec ) return self . from_vec ( ret ) , X | Convert a substitution table into an arybo application |
240,998 | def response_hook ( self , r , ** kwargs ) : if r . status_code == 401 : www_authenticate = r . headers . get ( 'www-authenticate' , '' ) . lower ( ) auth_type = _auth_type_from_header ( www_authenticate ) if auth_type is not None : return self . retry_using_http_NTLM_auth ( 'www-authenticate' , 'Authorization' , r , a... | The actual hook handler . |
240,999 | def dummy ( DF , cols = None ) : dummies = ( get_dummies ( DF [ col ] ) for col in ( DF . columns if cols is None else cols ) ) return concat ( dummies , axis = 1 , keys = DF . columns ) | Dummy code select columns of a DataFrame . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.