idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
242,200 | def process_code_block ( self , block ) : if block [ 'type' ] != self . code : return block attr = PandocAttributes ( block [ 'attributes' ] , 'markdown' ) if self . match == 'all' : pass elif self . match == 'fenced' and block . get ( 'indent' ) : return self . new_text_block ( content = ( '\n' + block [ 'icontent' ] + '\n' ) ) elif self . match == 'strict' and 'input' not in attr . classes : return self . new_text_block ( content = block [ 'raw' ] ) elif self . match not in list ( attr . classes ) + [ 'fenced' , 'strict' ] : return self . new_text_block ( content = block [ 'raw' ] ) # set input / output status of cell if 'output' in attr . classes and 'json' in attr . classes : block [ 'IO' ] = 'output' elif 'input' in attr . classes : block [ 'IO' ] = 'input' attr . classes . remove ( 'input' ) else : block [ 'IO' ] = 'input' if self . caption_comments : # override attributes id and caption with those set in # comments, if they exist id , caption = get_caption_comments ( block [ 'content' ] ) if id : attr . id = id if caption : attr [ 'caption' ] = caption try : # determine the language as the first class that # is in the block attributes and also in the list # of languages language = set ( attr . classes ) . intersection ( languages ) . pop ( ) attr . classes . remove ( language ) except KeyError : language = None block [ 'language' ] = language block [ 'attributes' ] = attr # ensure one identifier for python code if language in ( 'python' , 'py' , '' , None ) : block [ 'language' ] = self . python # add alternate language execution magic elif language != self . python and self . magic : block [ 'content' ] = CodeMagician . magic ( language ) + block [ 'content' ] block [ 'language' ] = language return self . new_code_block ( * * block ) | Parse block attributes | 508 | 4 |
242,201 | def parse_blocks ( self , text ) : code_matches = [ m for m in self . code_pattern . finditer ( text ) ] # determine where the limits of the non code bits are # based on the code block edges text_starts = [ 0 ] + [ m . end ( ) for m in code_matches ] text_stops = [ m . start ( ) for m in code_matches ] + [ len ( text ) ] text_limits = list ( zip ( text_starts , text_stops ) ) # list of the groups from the code blocks code_blocks = [ self . new_code_block ( * * m . groupdict ( ) ) for m in code_matches ] text_blocks = [ self . new_text_block ( content = text [ i : j ] ) for i , j in text_limits ] # remove indents list ( map ( self . pre_process_code_block , code_blocks ) ) # remove blank line at start and end of markdown list ( map ( self . pre_process_text_block , text_blocks ) ) # create a list of the right length all_blocks = list ( range ( len ( text_blocks ) + len ( code_blocks ) ) ) # NOTE: the behaviour here is a bit fragile in that we # assume that cells must alternate between code and # markdown. This isn't the case, as we could have # consecutive code cells, and we get around this by # stripping out empty cells. i.e. two consecutive code cells # have an empty markdown cell between them which is stripped # out because it is empty. # cells must alternate in order all_blocks [ : : 2 ] = text_blocks all_blocks [ 1 : : 2 ] = code_blocks # remove possible empty text cells all_blocks = [ cell for cell in all_blocks if cell [ 'content' ] ] return all_blocks | Extract the code and non - code blocks from given markdown text . | 413 | 15 |
242,202 | def create_code_cell ( block ) : code_cell = nbbase . new_code_cell ( source = block [ 'content' ] ) attr = block [ 'attributes' ] if not attr . is_empty : code_cell . metadata = nbbase . NotebookNode ( { 'attributes' : attr . to_dict ( ) } ) execution_count = attr . kvs . get ( 'n' ) if not execution_count : code_cell . execution_count = None else : code_cell . execution_count = int ( execution_count ) return code_cell | Create a notebook code cell from a block . | 133 | 9 |
242,203 | def create_markdown_cell ( block ) : kwargs = { 'cell_type' : block [ 'type' ] , 'source' : block [ 'content' ] } markdown_cell = nbbase . new_markdown_cell ( * * kwargs ) return markdown_cell | Create a markdown cell from a block . | 67 | 9 |
242,204 | def create_cells ( self , blocks ) : cells = [ ] for block in blocks : if ( block [ 'type' ] == self . code ) and ( block [ 'IO' ] == 'input' ) : code_cell = self . create_code_cell ( block ) cells . append ( code_cell ) elif ( block [ 'type' ] == self . code and block [ 'IO' ] == 'output' and cells [ - 1 ] . cell_type == 'code' ) : cells [ - 1 ] . outputs = self . create_outputs ( block ) elif block [ 'type' ] == self . markdown : markdown_cell = self . create_markdown_cell ( block ) cells . append ( markdown_cell ) else : raise NotImplementedError ( "{} is not supported as a cell" "type" . format ( block [ 'type' ] ) ) return cells | Turn the list of blocks into a list of notebook cells . | 198 | 12 |
242,205 | def to_notebook ( self , s , * * kwargs ) : all_blocks = self . parse_blocks ( s ) if self . pre_code_block [ 'content' ] : # TODO: if first block is markdown, place after? all_blocks . insert ( 0 , self . pre_code_block ) blocks = [ self . process_code_block ( block ) for block in all_blocks ] cells = self . create_cells ( blocks ) nb = nbbase . new_notebook ( cells = cells ) return nb | Convert the markdown string s to an IPython notebook . | 122 | 13 |
242,206 | def write_resources ( self , resources ) : for filename , data in list ( resources . get ( 'outputs' , { } ) . items ( ) ) : # Determine where to write the file to dest = os . path . join ( self . output_dir , filename ) path = os . path . dirname ( dest ) if path and not os . path . isdir ( path ) : os . makedirs ( path ) # Write file with open ( dest , 'wb' ) as f : f . write ( data ) | Write the output data in resources returned by exporter to files . | 114 | 13 |
242,207 | def string2json ( self , string ) : kwargs = { 'cls' : BytesEncoder , # use the IPython bytes encoder 'indent' : 1 , 'sort_keys' : True , 'separators' : ( ',' , ': ' ) , } return cast_unicode ( json . dumps ( string , * * kwargs ) , 'utf-8' ) | Convert json into its string representation . Used for writing outputs to markdown . | 88 | 16 |
242,208 | def create_attributes ( self , cell , cell_type = None ) : if self . strip_outputs or not hasattr ( cell , 'execution_count' ) : return 'python' attrs = cell . metadata . get ( 'attributes' ) attr = PandocAttributes ( attrs , 'dict' ) if 'python' in attr . classes : attr . classes . remove ( 'python' ) if 'input' in attr . classes : attr . classes . remove ( 'input' ) if cell_type == 'figure' : attr . kvs . pop ( 'caption' , '' ) attr . classes . append ( 'figure' ) attr . classes . append ( 'output' ) return attr . to_html ( ) elif cell_type == 'input' : # ensure python goes first so that github highlights it attr . classes . insert ( 0 , 'python' ) attr . classes . insert ( 1 , 'input' ) if cell . execution_count : attr . kvs [ 'n' ] = cell . execution_count return attr . to_markdown ( format = '{classes} {id} {kvs}' ) else : return attr . to_markdown ( ) | Turn the attribute dict into an attribute string for the code block . | 273 | 13 |
242,209 | def dequote ( s ) : if len ( s ) < 2 : return s elif ( s [ 0 ] == s [ - 1 ] ) and s . startswith ( ( '"' , "'" ) ) : return s [ 1 : - 1 ] else : return s | Remove excess quotes from a string . | 59 | 7 |
242,210 | def data2uri ( data , data_type ) : MIME_MAP = { 'image/jpeg' : 'jpeg' , 'image/png' : 'png' , 'text/plain' : 'text' , 'text/html' : 'html' , 'text/latex' : 'latex' , 'application/javascript' : 'html' , 'image/svg+xml' : 'svg' , } inverse_map = { v : k for k , v in list ( MIME_MAP . items ( ) ) } mime_type = inverse_map [ data_type ] uri = r"data:{mime};base64,{data}" return uri . format ( mime = mime_type , data = data [ mime_type ] . replace ( '\n' , '' ) ) | Convert base64 data into a data uri with the given data_type . | 185 | 17 |
242,211 | def magic ( self , alias ) : if alias in self . aliases : return self . aliases [ alias ] else : return "%%{}\n" . format ( alias ) | Returns the appropriate IPython code magic when called with an alias for a language . | 36 | 16 |
242,212 | def knit ( self , input_file , opts_chunk = 'eval=FALSE' ) : # use temporary files at both ends to allow stdin / stdout tmp_in = tempfile . NamedTemporaryFile ( mode = 'w+' ) tmp_out = tempfile . NamedTemporaryFile ( mode = 'w+' ) tmp_in . file . write ( input_file . read ( ) ) tmp_in . file . flush ( ) tmp_in . file . seek ( 0 ) self . _knit ( tmp_in . name , tmp_out . name , opts_chunk ) tmp_out . file . flush ( ) return tmp_out | Use Knitr to convert the r - markdown input_file into markdown returning a file object . | 146 | 22 |
242,213 | def is_path_protected ( path ) : protected = True for exclude_path in TERMS_EXCLUDE_URL_PREFIX_LIST : if path . startswith ( exclude_path ) : protected = False for contains_path in TERMS_EXCLUDE_URL_CONTAINS_LIST : if contains_path in path : protected = False if path in TERMS_EXCLUDE_URL_LIST : protected = False if path . startswith ( ACCEPT_TERMS_PATH ) : protected = False return protected | returns True if given path is to be protected otherwise False | 120 | 12 |
242,214 | def process_request ( self , request ) : LOGGER . debug ( 'termsandconditions.middleware' ) current_path = request . META [ 'PATH_INFO' ] if DJANGO_VERSION <= ( 2 , 0 , 0 ) : user_authenticated = request . user . is_authenticated ( ) else : user_authenticated = request . user . is_authenticated if user_authenticated and is_path_protected ( current_path ) : for term in TermsAndConditions . get_active_terms_not_agreed_to ( request . user ) : # Check for querystring and include it if there is one qs = request . META [ 'QUERY_STRING' ] current_path += '?' + qs if qs else '' return redirect_to_terms_accept ( current_path , term . slug ) return None | Process each request to app to ensure terms have been accepted | 189 | 11 |
242,215 | def get_context_data ( self , * * kwargs ) : context = super ( TermsView , self ) . get_context_data ( * * kwargs ) context [ 'terms_base_template' ] = getattr ( settings , 'TERMS_BASE_TEMPLATE' , DEFAULT_TERMS_BASE_TEMPLATE ) return context | Pass additional context data | 83 | 4 |
242,216 | def get_initial ( self ) : LOGGER . debug ( 'termsandconditions.views.AcceptTermsView.get_initial' ) terms = self . get_terms ( self . kwargs ) return_to = self . request . GET . get ( 'returnTo' , '/' ) return { 'terms' : terms , 'returnTo' : return_to } | Override of CreateView method queries for which T&C to accept and catches returnTo from URL | 82 | 19 |
242,217 | def post ( self , request , * args , * * kwargs ) : return_url = request . POST . get ( 'returnTo' , '/' ) terms_ids = request . POST . getlist ( 'terms' ) if not terms_ids : # pragma: nocover return HttpResponseRedirect ( return_url ) if DJANGO_VERSION <= ( 2 , 0 , 0 ) : user_authenticated = request . user . is_authenticated ( ) else : user_authenticated = request . user . is_authenticated if user_authenticated : user = request . user else : # Get user out of saved pipeline from django-socialauth if 'partial_pipeline' in request . session : user_pk = request . session [ 'partial_pipeline' ] [ 'kwargs' ] [ 'user' ] [ 'pk' ] user = User . objects . get ( id = user_pk ) else : return HttpResponseRedirect ( '/' ) store_ip_address = getattr ( settings , 'TERMS_STORE_IP_ADDRESS' , True ) if store_ip_address : ip_address = request . META . get ( getattr ( settings , 'TERMS_IP_HEADER_NAME' , DEFAULT_TERMS_IP_HEADER_NAME ) ) else : ip_address = "" for terms_id in terms_ids : try : new_user_terms = UserTermsAndConditions ( user = user , terms = TermsAndConditions . objects . get ( pk = int ( terms_id ) ) , ip_address = ip_address ) new_user_terms . save ( ) except IntegrityError : # pragma: nocover pass return HttpResponseRedirect ( return_url ) | Handles POST request . | 392 | 5 |
242,218 | def form_valid ( self , form ) : LOGGER . debug ( 'termsandconditions.views.EmailTermsView.form_valid' ) template = get_template ( "termsandconditions/tc_email_terms.html" ) template_rendered = template . render ( { "terms" : form . cleaned_data . get ( 'terms' ) } ) LOGGER . debug ( "Email Terms Body:" ) LOGGER . debug ( template_rendered ) try : send_mail ( form . cleaned_data . get ( 'email_subject' , _ ( 'Terms' ) ) , template_rendered , settings . DEFAULT_FROM_EMAIL , [ form . cleaned_data . get ( 'email_address' ) ] , fail_silently = False ) messages . add_message ( self . request , messages . INFO , _ ( "Terms and Conditions Sent." ) ) except SMTPException : # pragma: no cover messages . add_message ( self . request , messages . ERROR , _ ( "An Error Occurred Sending Your Message." ) ) self . success_url = form . cleaned_data . get ( 'returnTo' , '/' ) or '/' return super ( EmailTermsView , self ) . form_valid ( form ) | Override of CreateView method sends the email . | 274 | 9 |
242,219 | def form_invalid ( self , form ) : LOGGER . debug ( "Invalid Email Form Submitted" ) messages . add_message ( self . request , messages . ERROR , _ ( "Invalid Email Address." ) ) return super ( EmailTermsView , self ) . form_invalid ( form ) | Override of CreateView method logs invalid email form submissions . | 65 | 11 |
242,220 | def terms_required ( view_func ) : @ wraps ( view_func , assigned = available_attrs ( view_func ) ) def _wrapped_view ( request , * args , * * kwargs ) : """Method to wrap the view passed in""" # If user has not logged in, or if they have logged in and already agreed to the terms, let the view through if DJANGO_VERSION <= ( 2 , 0 , 0 ) : user_authenticated = request . user . is_authenticated ( ) else : user_authenticated = request . user . is_authenticated if not user_authenticated or not TermsAndConditions . get_active_terms_not_agreed_to ( request . user ) : return view_func ( request , * args , * * kwargs ) # Otherwise, redirect to terms accept current_path = request . path login_url_parts = list ( urlparse ( ACCEPT_TERMS_PATH ) ) querystring = QueryDict ( login_url_parts [ 4 ] , mutable = True ) querystring [ 'returnTo' ] = current_path login_url_parts [ 4 ] = querystring . urlencode ( safe = '/' ) return HttpResponseRedirect ( urlunparse ( login_url_parts ) ) return _wrapped_view | This decorator checks to see if the user is logged in and if so if they have accepted the site terms . | 287 | 23 |
242,221 | def get_active ( slug = DEFAULT_TERMS_SLUG ) : active_terms = cache . get ( 'tandc.active_terms_' + slug ) if active_terms is None : try : active_terms = TermsAndConditions . objects . filter ( date_active__isnull = False , date_active__lte = timezone . now ( ) , slug = slug ) . latest ( 'date_active' ) cache . set ( 'tandc.active_terms_' + slug , active_terms , TERMS_CACHE_SECONDS ) except TermsAndConditions . DoesNotExist : # pragma: nocover LOGGER . error ( "Requested Terms and Conditions that Have Not Been Created." ) return None return active_terms | Finds the latest of a particular terms and conditions | 170 | 10 |
242,222 | def get_active_terms_ids ( ) : active_terms_ids = cache . get ( 'tandc.active_terms_ids' ) if active_terms_ids is None : active_terms_dict = { } active_terms_ids = [ ] active_terms_set = TermsAndConditions . objects . filter ( date_active__isnull = False , date_active__lte = timezone . now ( ) ) . order_by ( 'date_active' ) for active_terms in active_terms_set : active_terms_dict [ active_terms . slug ] = active_terms . id active_terms_dict = OrderedDict ( sorted ( active_terms_dict . items ( ) , key = lambda t : t [ 0 ] ) ) for terms in active_terms_dict : active_terms_ids . append ( active_terms_dict [ terms ] ) cache . set ( 'tandc.active_terms_ids' , active_terms_ids , TERMS_CACHE_SECONDS ) return active_terms_ids | Returns a list of the IDs of of all terms and conditions | 235 | 12 |
242,223 | def get_active_terms_list ( ) : active_terms_list = cache . get ( 'tandc.active_terms_list' ) if active_terms_list is None : active_terms_list = TermsAndConditions . objects . filter ( id__in = TermsAndConditions . get_active_terms_ids ( ) ) . order_by ( 'slug' ) cache . set ( 'tandc.active_terms_list' , active_terms_list , TERMS_CACHE_SECONDS ) return active_terms_list | Returns all the latest active terms and conditions | 125 | 8 |
242,224 | def get_active_terms_not_agreed_to ( user ) : if TERMS_EXCLUDE_USERS_WITH_PERM is not None : if user . has_perm ( TERMS_EXCLUDE_USERS_WITH_PERM ) and not user . is_superuser : # Django's has_perm() returns True if is_superuser, we don't want that return [ ] not_agreed_terms = cache . get ( 'tandc.not_agreed_terms_' + user . get_username ( ) ) if not_agreed_terms is None : try : LOGGER . debug ( "Not Agreed Terms" ) not_agreed_terms = TermsAndConditions . get_active_terms_list ( ) . exclude ( userterms__in = UserTermsAndConditions . objects . filter ( user = user ) ) . order_by ( 'slug' ) cache . set ( 'tandc.not_agreed_terms_' + user . get_username ( ) , not_agreed_terms , TERMS_CACHE_SECONDS ) except ( TypeError , UserTermsAndConditions . DoesNotExist ) : return [ ] return not_agreed_terms | Checks to see if a specified user has agreed to all the latest terms and conditions | 278 | 17 |
242,225 | def show_terms_if_not_agreed ( context , field = TERMS_HTTP_PATH_FIELD ) : request = context [ 'request' ] url = urlparse ( request . META [ field ] ) not_agreed_terms = TermsAndConditions . get_active_terms_not_agreed_to ( request . user ) if not_agreed_terms and is_path_protected ( url . path ) : return { 'not_agreed_terms' : not_agreed_terms , 'returnTo' : url . path } else : return { } | Displays a modal on a current page if a user has not yet agreed to the given terms . If terms are not specified the default slug is used . | 127 | 32 |
242,226 | def user_accept_terms ( backend , user , uid , social_user = None , * args , * * kwargs ) : LOGGER . debug ( 'user_accept_terms' ) if TermsAndConditions . get_active_terms_not_agreed_to ( user ) : return redirect_to_terms_accept ( '/' ) else : return { 'social_user' : social_user , 'user' : user } | Check if the user has accepted the terms and conditions after creation . | 97 | 13 |
242,227 | def redirect_to_terms_accept ( current_path = '/' , slug = 'default' ) : redirect_url_parts = list ( urlparse ( ACCEPT_TERMS_PATH ) ) if slug != 'default' : redirect_url_parts [ 2 ] += slug querystring = QueryDict ( redirect_url_parts [ 4 ] , mutable = True ) querystring [ TERMS_RETURNTO_PARAM ] = current_path redirect_url_parts [ 4 ] = querystring . urlencode ( safe = '/' ) return HttpResponseRedirect ( urlunparse ( redirect_url_parts ) ) | Redirect the user to the terms and conditions accept page . | 138 | 12 |
242,228 | def user_terms_updated ( sender , * * kwargs ) : LOGGER . debug ( "User T&C Updated Signal Handler" ) if kwargs . get ( 'instance' ) . user : cache . delete ( 'tandc.not_agreed_terms_' + kwargs . get ( 'instance' ) . user . get_username ( ) ) | Called when user terms and conditions is changed - to force cache clearing | 82 | 14 |
242,229 | def terms_updated ( sender , * * kwargs ) : LOGGER . debug ( "T&C Updated Signal Handler" ) cache . delete ( 'tandc.active_terms_ids' ) cache . delete ( 'tandc.active_terms_list' ) if kwargs . get ( 'instance' ) . slug : cache . delete ( 'tandc.active_terms_' + kwargs . get ( 'instance' ) . slug ) for utandc in UserTermsAndConditions . objects . all ( ) : cache . delete ( 'tandc.not_agreed_terms_' + utandc . user . get_username ( ) ) | Called when terms and conditions is changed - to force cache clearing | 150 | 13 |
242,230 | def paginate ( parser , token , paginator_class = None ) : # Validate arguments. try : tag_name , tag_args = token . contents . split ( None , 1 ) except ValueError : msg = '%r tag requires arguments' % token . contents . split ( ) [ 0 ] raise template . TemplateSyntaxError ( msg ) # Use a regexp to catch args. match = PAGINATE_EXPRESSION . match ( tag_args ) if match is None : msg = 'Invalid arguments for %r tag' % tag_name raise template . TemplateSyntaxError ( msg ) # Retrieve objects. kwargs = match . groupdict ( ) objects = kwargs . pop ( 'objects' ) # The variable name must be present if a nested context variable is passed. if '.' in objects and kwargs [ 'var_name' ] is None : msg = ( '%(tag)r tag requires a variable name `as` argumnent if the ' 'queryset is provided as a nested context variable (%(objects)s). ' 'You must either pass a direct queryset (e.g. taking advantage ' 'of the `with` template tag) or provide a new variable name to ' 'store the resulting queryset (e.g. `%(tag)s %(objects)s as ' 'objects`).' ) % { 'tag' : tag_name , 'objects' : objects } raise template . TemplateSyntaxError ( msg ) # Call the node. return PaginateNode ( paginator_class , objects , * * kwargs ) | Paginate objects . | 347 | 5 |
242,231 | def get_pages ( parser , token ) : # Validate args. try : tag_name , args = token . contents . split ( None , 1 ) except ValueError : var_name = 'pages' else : args = args . split ( ) if len ( args ) == 2 and args [ 0 ] == 'as' : var_name = args [ 1 ] else : msg = 'Invalid arguments for %r tag' % tag_name raise template . TemplateSyntaxError ( msg ) # Call the node. return GetPagesNode ( var_name ) | Add to context the list of page links . | 118 | 9 |
242,232 | def show_pages ( parser , token ) : # Validate args. if len ( token . contents . split ( ) ) != 1 : msg = '%r tag takes no arguments' % token . contents . split ( ) [ 0 ] raise template . TemplateSyntaxError ( msg ) # Call the node. return ShowPagesNode ( ) | Show page links . | 71 | 4 |
242,233 | def show_current_number ( parser , token ) : # Validate args. try : tag_name , args = token . contents . split ( None , 1 ) except ValueError : key = None number = None tag_name = token . contents [ 0 ] var_name = None else : # Use a regexp to catch args. match = SHOW_CURRENT_NUMBER_EXPRESSION . match ( args ) if match is None : msg = 'Invalid arguments for %r tag' % tag_name raise template . TemplateSyntaxError ( msg ) # Retrieve objects. groupdict = match . groupdict ( ) key = groupdict [ 'key' ] number = groupdict [ 'number' ] var_name = groupdict [ 'var_name' ] # Call the node. return ShowCurrentNumberNode ( number , key , var_name ) | Show the current page number or insert it in the context . | 182 | 12 |
242,234 | def page_template ( template , key = PAGE_LABEL ) : def decorator ( view ) : @ wraps ( view ) def decorated ( request , * args , * * kwargs ) : # Trust the developer: he wrote ``context.update(extra_context)`` # in his view. extra_context = kwargs . setdefault ( 'extra_context' , { } ) extra_context [ 'page_template' ] = template # Switch the template when the request is Ajax. querystring_key = request . GET . get ( QS_KEY , request . POST . get ( QS_KEY , PAGE_LABEL ) ) if request . is_ajax ( ) and querystring_key == key : kwargs [ TEMPLATE_VARNAME ] = template return view ( request , * args , * * kwargs ) return decorated return decorator | Return a view dynamically switching template if the request is Ajax . | 190 | 12 |
242,235 | def _get_template ( querystring_key , mapping ) : default = None try : template_and_keys = mapping . items ( ) except AttributeError : template_and_keys = mapping for template , key in template_and_keys : if key is None : key = PAGE_LABEL default = template if key == querystring_key : return template return default | Return the template corresponding to the given querystring_key . | 79 | 12 |
242,236 | def get_queryset ( self ) : if self . queryset is not None : queryset = self . queryset if hasattr ( queryset , '_clone' ) : queryset = queryset . _clone ( ) elif self . model is not None : queryset = self . model . _default_manager . all ( ) else : msg = '{0} must define ``queryset`` or ``model``' raise ImproperlyConfigured ( msg . format ( self . __class__ . __name__ ) ) return queryset | Get the list of items for this view . | 126 | 9 |
242,237 | def get_context_object_name ( self , object_list ) : if self . context_object_name : return self . context_object_name elif hasattr ( object_list , 'model' ) : object_name = object_list . model . _meta . object_name . lower ( ) return smart_str ( '{0}_list' . format ( object_name ) ) else : return None | Get the name of the item to be used in the context . | 91 | 13 |
242,238 | def get_page_template ( self , * * kwargs ) : opts = self . object_list . model . _meta return '{0}/{1}{2}{3}.html' . format ( opts . app_label , opts . object_name . lower ( ) , self . template_name_suffix , self . page_template_suffix , ) | Return the template name used for this request . | 84 | 9 |
242,239 | def render_link ( self ) : extra_context = { 'add_nofollow' : settings . ADD_NOFOLLOW , 'page' : self , 'querystring_key' : self . querystring_key , } if self . is_current : template_name = 'el_pagination/current_link.html' else : template_name = 'el_pagination/page_link.html' if settings . USE_NEXT_PREVIOUS_LINKS : if self . is_previous : template_name = 'el_pagination/previous_link.html' if self . is_next : template_name = 'el_pagination/next_link.html' if template_name not in _template_cache : _template_cache [ template_name ] = loader . get_template ( template_name ) template = _template_cache [ template_name ] with self . context . push ( * * extra_context ) : return template . render ( self . context . flatten ( ) ) | Render the page as a link . | 229 | 7 |
242,240 | def previous ( self ) : if self . _page . has_previous ( ) : return self . _endless_page ( self . _page . previous_page_number ( ) , label = settings . PREVIOUS_LABEL ) return '' | Return the previous page . | 54 | 5 |
242,241 | def next ( self ) : if self . _page . has_next ( ) : return self . _endless_page ( self . _page . next_page_number ( ) , label = settings . NEXT_LABEL ) return '' | Return the next page . | 51 | 5 |
242,242 | def start_index ( self ) : paginator = self . paginator # Special case, return zero if no items. if paginator . count == 0 : return 0 elif self . number == 1 : return 1 return ( ( self . number - 2 ) * paginator . per_page + paginator . first_page + 1 ) | Return the 1 - based index of the first item on this page . | 71 | 14 |
242,243 | def end_index ( self ) : paginator = self . paginator # Special case for the last page because there can be orphans. if self . number == paginator . num_pages : return paginator . count return ( self . number - 1 ) * paginator . per_page + paginator . first_page | Return the 1 - based index of the last item on this page . | 67 | 14 |
242,244 | def get_page_numbers ( current_page , num_pages , extremes = DEFAULT_CALLABLE_EXTREMES , arounds = DEFAULT_CALLABLE_AROUNDS , arrows = DEFAULT_CALLABLE_ARROWS ) : page_range = range ( 1 , num_pages + 1 ) pages = [ ] if current_page != 1 : if arrows : pages . append ( 'first' ) pages . append ( 'previous' ) # Get first and last pages (extremes). first = page_range [ : extremes ] pages . extend ( first ) last = page_range [ - extremes : ] # Get the current pages (arounds). current_start = current_page - 1 - arounds if current_start < 0 : current_start = 0 current_end = current_page + arounds if current_end > num_pages : current_end = num_pages current = page_range [ current_start : current_end ] # Mix first with current pages. to_add = current if extremes : diff = current [ 0 ] - first [ - 1 ] if diff > 1 : pages . append ( None ) elif diff < 1 : to_add = current [ abs ( diff ) + 1 : ] pages . extend ( to_add ) # Mix current with last pages. if extremes : diff = last [ 0 ] - current [ - 1 ] to_add = last if diff > 1 : pages . append ( None ) elif diff < 1 : to_add = last [ abs ( diff ) + 1 : ] pages . extend ( to_add ) if current_page != num_pages : pages . append ( 'next' ) if arrows : pages . append ( 'last' ) return pages | Default callable for page listing . | 372 | 7 |
242,245 | def _make_elastic_range ( begin , end ) : # Limit growth for huge numbers of pages. starting_factor = max ( 1 , ( end - begin ) // 100 ) factor = _iter_factors ( starting_factor ) left_half , right_half = [ ] , [ ] left_val , right_val = begin , end right_val = end while left_val < right_val : left_half . append ( left_val ) right_half . append ( right_val ) next_factor = next ( factor ) left_val = begin + next_factor right_val = end - next_factor # If the trends happen to meet exactly at one point, retain it. if left_val == right_val : left_half . append ( left_val ) right_half . reverse ( ) return left_half + right_half | Generate an S - curved range of pages . | 184 | 10 |
242,246 | def get_elastic_page_numbers ( current_page , num_pages ) : if num_pages <= 10 : return list ( range ( 1 , num_pages + 1 ) ) if current_page == 1 : pages = [ 1 ] else : pages = [ 'first' , 'previous' ] pages . extend ( _make_elastic_range ( 1 , current_page ) ) if current_page != num_pages : pages . extend ( _make_elastic_range ( current_page , num_pages ) [ 1 : ] ) pages . extend ( [ 'next' , 'last' ] ) return pages | Alternative callable for page listing . | 136 | 7 |
242,247 | def get_prepopulated_value ( field , instance ) : if hasattr ( field . populate_from , '__call__' ) : # AutoSlugField(populate_from=lambda instance: ...) return field . populate_from ( instance ) else : # AutoSlugField(populate_from='foo') attr = getattr ( instance , field . populate_from ) return callable ( attr ) and attr ( ) or attr | Returns preliminary value based on populate_from . | 100 | 9 |
242,248 | def get_uniqueness_lookups ( field , instance , unique_with ) : for original_lookup_name in unique_with : if '__' in original_lookup_name : field_name , inner_lookup = original_lookup_name . split ( '__' , 1 ) else : field_name , inner_lookup = original_lookup_name , None try : other_field = instance . _meta . get_field ( field_name ) except FieldDoesNotExist : raise ValueError ( 'Could not find attribute %s.%s referenced' ' by %s.%s (see constraint `unique_with`)' % ( instance . _meta . object_name , field_name , instance . _meta . object_name , field . name ) ) if field == other_field : raise ValueError ( 'Attribute %s.%s references itself in `unique_with`.' ' Please use "unique=True" for this case.' % ( instance . _meta . object_name , field_name ) ) value = getattr ( instance , field_name ) if not value : if other_field . blank : field_object = instance . _meta . get_field ( field_name ) if isinstance ( field_object , ForeignKey ) : lookup = '%s__isnull' % field_name yield lookup , True break raise ValueError ( 'Could not check uniqueness of %s.%s with' ' respect to %s.%s because the latter is empty.' ' Please ensure that "%s" is declared *after*' ' all fields listed in unique_with.' % ( instance . _meta . object_name , field . name , instance . _meta . object_name , field_name , field . name ) ) if isinstance ( other_field , DateField ) : # DateTimeField is a DateField subclass inner_lookup = inner_lookup or 'day' if '__' in inner_lookup : raise ValueError ( 'The `unique_with` constraint in %s.%s' ' is set to "%s", but AutoSlugField only' ' accepts one level of nesting for dates' ' (e.g. "date__month").' % ( instance . _meta . object_name , field . name , original_lookup_name ) ) parts = [ 'year' , 'month' , 'day' ] try : granularity = parts . index ( inner_lookup ) + 1 except ValueError : raise ValueError ( 'expected one of %s, got "%s" in "%s"' % ( parts , inner_lookup , original_lookup_name ) ) else : for part in parts [ : granularity ] : lookup = '%s__%s' % ( field_name , part ) yield lookup , getattr ( value , part ) else : # TODO: this part should be documented as it involves recursion if inner_lookup : if not hasattr ( value , '_meta' ) : raise ValueError ( 'Could not resolve lookup "%s" in `unique_with` of %s.%s' % ( original_lookup_name , instance . _meta . object_name , field . name ) ) for inner_name , inner_value in get_uniqueness_lookups ( field , value , [ inner_lookup ] ) : yield original_lookup_name , inner_value else : yield field_name , value | Returns a dict able tuple of lookups to ensure uniqueness of a slug . | 744 | 15 |
242,249 | def derivative_colors ( colors ) : return set ( [ ( 'on_' + c ) for c in colors ] + [ ( 'bright_' + c ) for c in colors ] + [ ( 'on_bright_' + c ) for c in colors ] ) | Return the names of valid color variants given the base colors . | 59 | 12 |
242,250 | def split_into_formatters ( compound ) : merged_segs = [ ] # These occur only as prefixes, so they can always be merged: mergeable_prefixes = [ 'no' , 'on' , 'bright' , 'on_bright' ] for s in compound . split ( '_' ) : if merged_segs and merged_segs [ - 1 ] in mergeable_prefixes : merged_segs [ - 1 ] += '_' + s else : merged_segs . append ( s ) return merged_segs | Split a possibly compound format string into segments . | 121 | 9 |
242,251 | def location ( self , x = None , y = None ) : # Save position and move to the requested column, row, or both: self . stream . write ( self . save ) if x is not None and y is not None : self . stream . write ( self . move ( y , x ) ) elif x is not None : self . stream . write ( self . move_x ( x ) ) elif y is not None : self . stream . write ( self . move_y ( y ) ) try : yield finally : # Restore original cursor position: self . stream . write ( self . restore ) | Return a context manager for temporarily moving the cursor . | 130 | 10 |
242,252 | def fullscreen ( self ) : self . stream . write ( self . enter_fullscreen ) try : yield finally : self . stream . write ( self . exit_fullscreen ) | Return a context manager that enters fullscreen mode while inside it and restores normal mode on leaving . | 38 | 19 |
242,253 | def hidden_cursor ( self ) : self . stream . write ( self . hide_cursor ) try : yield finally : self . stream . write ( self . normal_cursor ) | Return a context manager that hides the cursor while inside it and makes it visible on leaving . | 40 | 18 |
242,254 | def _resolve_formatter ( self , attr ) : if attr in COLORS : return self . _resolve_color ( attr ) elif attr in COMPOUNDABLES : # Bold, underline, or something that takes no parameters return self . _formatting_string ( self . _resolve_capability ( attr ) ) else : formatters = split_into_formatters ( attr ) if all ( f in COMPOUNDABLES for f in formatters ) : # It's a compound formatter, like "bold_green_on_red". Future # optimization: combine all formatting into a single escape # sequence. return self . _formatting_string ( u'' . join ( self . _resolve_formatter ( s ) for s in formatters ) ) else : return ParametrizingString ( self . _resolve_capability ( attr ) ) | Resolve a sugary or plain capability name color or compound formatting function name into a callable capability . | 196 | 21 |
242,255 | def _resolve_capability ( self , atom ) : code = tigetstr ( self . _sugar . get ( atom , atom ) ) if code : # See the comment in ParametrizingString for why this is latin1. return code . decode ( 'latin1' ) return u'' | Return a terminal code for a capname or a sugary name or an empty Unicode . | 68 | 18 |
242,256 | def _resolve_color ( self , color ) : # TODO: Does curses automatically exchange red and blue and cyan and # yellow when a terminal supports setf/setb rather than setaf/setab? # I'll be blasted if I can find any documentation. The following # assumes it does. color_cap = ( self . _background_color if 'on_' in color else self . _foreground_color ) # curses constants go up to only 7, so add an offset to get at the # bright colors at 8-15: offset = 8 if 'bright_' in color else 0 base_color = color . rsplit ( '_' , 1 ) [ - 1 ] return self . _formatting_string ( color_cap ( getattr ( curses , 'COLOR_' + base_color . upper ( ) ) + offset ) ) | Resolve a color like red or on_bright_green into a callable capability . | 182 | 18 |
242,257 | def send_login_code ( self , code , context , * * kwargs ) : from_number = self . from_number or getattr ( settings , 'DEFAULT_FROM_NUMBER' ) sms_content = render_to_string ( self . template_name , context ) self . twilio_client . messages . create ( to = code . user . phone_number , from_ = from_number , body = sms_content ) | Send a login code via SMS | 101 | 6 |
242,258 | def load ( filename , * * kwargs ) : with open ( filename , 'rb' ) as f : reader = T7Reader ( f , * * kwargs ) return reader . read_obj ( ) | Loads the given t7 file using default settings ; kwargs are forwarded to T7Reader . | 46 | 21 |
242,259 | def check ( self ) : if self . lastrun + self . interval < time . time ( ) : return True else : return False | Returns True if interval seconds have passed since it last ran | 28 | 11 |
242,260 | def make_union ( * transformers , * * kwargs ) : n_jobs = kwargs . pop ( 'n_jobs' , 1 ) concatenate = kwargs . pop ( 'concatenate' , True ) if kwargs : # We do not currently support `transformer_weights` as we may want to # change its type spec in make_union raise TypeError ( 'Unknown keyword arguments: "{}"' . format ( list ( kwargs . keys ( ) ) [ 0 ] ) ) return FeatureUnion ( _name_estimators ( transformers ) , n_jobs = n_jobs , concatenate = concatenate ) | Construct a FeatureUnion from the given transformers . | 145 | 10 |
242,261 | def get_feature_names ( self ) : feature_names = [ ] for name , trans , weight in self . _iter ( ) : if not hasattr ( trans , 'get_feature_names' ) : raise AttributeError ( "Transformer %s (type %s) does not " "provide get_feature_names." % ( str ( name ) , type ( trans ) . __name__ ) ) feature_names . extend ( [ name + "__" + f for f in trans . get_feature_names ( ) ] ) return feature_names | Get feature names from all transformers . | 122 | 8 |
242,262 | def fit ( self , X , y = None ) : self . transformer_list = list ( self . transformer_list ) self . _validate_transformers ( ) with Pool ( self . n_jobs ) as pool : transformers = pool . starmap ( _fit_one_transformer , ( ( trans , X [ trans [ 'col_pick' ] ] if hasattr ( trans , 'col_pick' ) else X , y ) for _ , trans , _ in self . _iter ( ) ) ) self . _update_transformer_list ( transformers ) return self | Fit all transformers using X . | 127 | 7 |
242,263 | def fit_transform ( self , X , y = None , * * fit_params ) : self . _validate_transformers ( ) with Pool ( self . n_jobs ) as pool : result = pool . starmap ( _fit_transform_one , ( ( trans , weight , X [ trans [ 'col_pick' ] ] if hasattr ( trans , 'col_pick' ) else X , y ) for name , trans , weight in self . _iter ( ) ) ) if not result : # All transformers are None return np . zeros ( ( X . shape [ 0 ] , 0 ) ) Xs , transformers = zip ( * result ) self . _update_transformer_list ( transformers ) if self . concatenate : if any ( sparse . issparse ( f ) for f in Xs ) : Xs = sparse . hstack ( Xs ) . tocsr ( ) else : Xs = np . hstack ( Xs ) return Xs | Fit all transformers transform the data and concatenate results . | 214 | 13 |
242,264 | def transform ( self , X ) : with Pool ( self . n_jobs ) as pool : Xs = pool . starmap ( _transform_one , ( ( trans , weight , X [ trans [ 'col_pick' ] ] if hasattr ( trans , 'col_pick' ) else X ) for name , trans , weight in self . _iter ( ) ) ) if not Xs : # All transformers are None return np . zeros ( ( X . shape [ 0 ] , 0 ) ) if self . concatenate : if any ( sparse . issparse ( f ) for f in Xs ) : Xs = sparse . hstack ( Xs ) . tocsr ( ) else : Xs = np . hstack ( Xs ) return Xs | Transform X separately by each transformer concatenate results . | 166 | 11 |
242,265 | def split_batches ( self , data , minibatch_size = None ) : if minibatch_size == None : minibatch_size = self . minibatch_size if isinstance ( data , list ) or isinstance ( data , tuple ) : len_data = len ( data ) else : len_data = data . shape [ 0 ] if isinstance ( data , pd . DataFrame ) : data_split = [ data . iloc [ x * minibatch_size : ( x + 1 ) * minibatch_size ] for x in range ( int ( ceil ( len_data / minibatch_size ) ) ) ] else : data_split = [ data [ x * minibatch_size : min ( len_data , ( x + 1 ) * minibatch_size ) ] for x in range ( int ( ceil ( len_data / minibatch_size ) ) ) ] return data_split | Split data into minibatches with a specified size | 207 | 10 |
242,266 | def merge_batches ( self , data ) : if isinstance ( data [ 0 ] , ssp . csr_matrix ) : return ssp . vstack ( data ) if isinstance ( data [ 0 ] , pd . DataFrame ) or isinstance ( data [ 0 ] , pd . Series ) : return pd . concat ( data ) return [ item for sublist in data for item in sublist ] | Merge a list of data minibatches into one single instance representing the data | 92 | 16 |
242,267 | def shuffle_batch ( self , texts , labels = None , seed = None ) : if seed != None : random . seed ( seed ) index_shuf = list ( range ( len ( texts ) ) ) random . shuffle ( index_shuf ) texts = [ texts [ x ] for x in index_shuf ] if labels == None : return texts labels = [ labels [ x ] for x in index_shuf ] return texts , labels | Shuffle a list of samples as well as the labels if specified | 94 | 13 |
242,268 | def demeshgrid ( arr ) : dim = len ( arr . shape ) for i in range ( dim ) : Slice1 = [ 0 ] * dim Slice2 = [ 1 ] * dim Slice1 [ i ] = slice ( None ) Slice2 [ i ] = slice ( None ) if ( arr [ tuple ( Slice1 ) ] == arr [ tuple ( Slice2 ) ] ) . all ( ) : return arr [ tuple ( Slice1 ) ] | Turns an ndarray created by a meshgrid back into a 1D array | 101 | 17 |
242,269 | def timeline_slider ( self , text = 'Time' , ax = None , valfmt = None , color = None ) : if ax is None : adjust_plot = { 'bottom' : .2 } rect = [ .18 , .05 , .5 , .03 ] plt . subplots_adjust ( * * adjust_plot ) self . slider_ax = plt . axes ( rect ) else : self . slider_ax = ax if valfmt is None : if ( np . issubdtype ( self . timeline . t . dtype , np . datetime64 ) or np . issubdtype ( self . timeline . t . dtype , np . timedelta64 ) ) : valfmt = '%s' else : valfmt = '%1.2f' if self . timeline . log : valfmt = '$10^{%s}$' % valfmt self . slider = Slider ( self . slider_ax , text , 0 , self . timeline . _len - 1 , valinit = 0 , valfmt = ( valfmt + self . timeline . units ) , valstep = 1 , color = color ) self . _has_slider = True def set_time ( t ) : self . timeline . index = int ( self . slider . val ) self . slider . valtext . set_text ( self . slider . valfmt % ( self . timeline [ self . timeline . index ] ) ) if self . _pause : for block in self . blocks : block . _update ( self . timeline . index ) self . fig . canvas . draw ( ) self . slider . on_changed ( set_time ) | Creates a timeline slider . | 363 | 6 |
242,270 | def controls ( self , timeline_slider_args = { } , toggle_args = { } ) : self . timeline_slider ( * * timeline_slider_args ) self . toggle ( * * toggle_args ) | Creates interactive controls for the animation | 49 | 7 |
242,271 | def save_gif ( self , filename ) : self . timeline . index -= 1 # required for proper starting point for save self . animation . save ( filename + '.gif' , writer = PillowWriter ( fps = self . timeline . fps ) ) | Saves the animation to a gif | 52 | 7 |
242,272 | def save ( self , * args , * * kwargs ) : self . timeline . index -= 1 # required for proper starting point for save self . animation . save ( * args , * * kwargs ) | Saves an animation | 45 | 4 |
242,273 | def isin_alone ( elems , line ) : found = False for e in elems : if line . strip ( ) . lower ( ) == e . lower ( ) : found = True break return found | Check if an element from a list is the only element of a string . | 44 | 15 |
242,274 | def isin_start ( elems , line ) : found = False elems = [ elems ] if type ( elems ) is not list else elems for e in elems : if line . lstrip ( ) . lower ( ) . startswith ( e ) : found = True break return found | Check if an element from a list starts a string . | 65 | 11 |
242,275 | def isin ( elems , line ) : found = False for e in elems : if e in line . lower ( ) : found = True break return found | Check if an element from a list is in a string . | 34 | 12 |
242,276 | def get_leading_spaces ( data ) : spaces = '' m = re . match ( r'^(\s*)' , data ) if m : spaces = m . group ( 1 ) return spaces | Get the leading space of a string if it is not empty | 43 | 12 |
242,277 | def get_mandatory_sections ( self ) : return [ s for s in self . opt if s not in self . optional_sections and s not in self . excluded_sections ] | Get mandatory sections | 39 | 3 |
242,278 | def get_raw_not_managed ( self , data ) : keys = [ 'also' , 'ref' , 'note' , 'other' , 'example' , 'method' , 'attr' ] elems = [ self . opt [ k ] for k in self . opt if k in keys ] data = data . splitlines ( ) start = 0 init = 0 raw = '' spaces = None while start != - 1 : start , end = self . get_next_section_lines ( data [ init : ] ) if start != - 1 : init += start if isin_alone ( elems , data [ init ] ) and not isin_alone ( [ self . opt [ e ] for e in self . excluded_sections ] , data [ init ] ) : spaces = get_leading_spaces ( data [ init ] ) if end != - 1 : section = [ d . replace ( spaces , '' , 1 ) . rstrip ( ) for d in data [ init : init + end ] ] else : section = [ d . replace ( spaces , '' , 1 ) . rstrip ( ) for d in data [ init : ] ] raw += '\n' . join ( section ) + '\n' init += 2 return raw | Get elements not managed . They can be used as is . | 265 | 12 |
242,279 | def get_key_section_header ( self , key , spaces ) : header = super ( NumpydocTools , self ) . get_key_section_header ( key , spaces ) header = spaces + header + '\n' + spaces + '-' * len ( header ) + '\n' return header | Get the key of the header section | 68 | 7 |
242,280 | def autodetect_style ( self , data ) : # evaluate styles with keys found_keys = defaultdict ( int ) for style in self . tagstyles : for key in self . opt : found_keys [ style ] += data . count ( self . opt [ key ] [ style ] [ 'name' ] ) fkey = max ( found_keys , key = found_keys . get ) detected_style = fkey if found_keys [ fkey ] else 'unknown' # evaluate styles with groups if detected_style == 'unknown' : found_groups = 0 found_googledoc = 0 found_numpydoc = 0 found_numpydocsep = 0 for line in data . strip ( ) . splitlines ( ) : for key in self . groups : found_groups += 1 if isin_start ( self . groups [ key ] , line ) else 0 for key in self . googledoc : found_googledoc += 1 if isin_start ( self . googledoc [ key ] , line ) else 0 for key in self . numpydoc : found_numpydoc += 1 if isin_start ( self . numpydoc [ key ] , line ) else 0 if line . strip ( ) and isin_alone ( [ '-' * len ( line . strip ( ) ) ] , line ) : found_numpydocsep += 1 elif isin ( self . numpydoc . keywords , line ) : found_numpydoc += 1 # TODO: check if not necessary to have > 1?? if found_numpydoc and found_numpydocsep : detected_style = 'numpydoc' elif found_googledoc >= found_groups : detected_style = 'google' elif found_groups : detected_style = 'groups' self . style [ 'in' ] = detected_style return detected_style | Determine the style of a docstring and sets it as the default input one for the instance . | 420 | 21 |
242,281 | def _get_options ( self , style ) : return [ self . opt [ o ] [ style ] [ 'name' ] for o in self . opt ] | Get the list of keywords for a particular style | 34 | 9 |
242,282 | def get_group_key_line ( self , data , key ) : idx = - 1 for i , line in enumerate ( data . splitlines ( ) ) : if isin_start ( self . groups [ key ] , line ) : idx = i return idx | Get the next group - style key s line number . | 60 | 11 |
242,283 | def get_group_key_index ( self , data , key ) : idx = - 1 li = self . get_group_key_line ( data , key ) if li != - 1 : idx = 0 for line in data . splitlines ( ) [ : li ] : idx += len ( line ) + len ( '\n' ) return idx | Get the next groups style s starting line index for a key | 79 | 12 |
242,284 | def get_group_line ( self , data ) : idx = - 1 for key in self . groups : i = self . get_group_key_line ( data , key ) if ( i < idx and i != - 1 ) or idx == - 1 : idx = i return idx | Get the next group - style key s line . | 66 | 10 |
242,285 | def get_group_index ( self , data ) : idx = - 1 li = self . get_group_line ( data ) if li != - 1 : idx = 0 for line in data . splitlines ( ) [ : li ] : idx += len ( line ) + len ( '\n' ) return idx | Get the next groups style s starting line index | 71 | 9 |
242,286 | def get_key_index ( self , data , key , starting = True ) : key = self . opt [ key ] [ self . style [ 'in' ] ] [ 'name' ] if key . startswith ( ':returns' ) : data = data . replace ( ':return:' , ':returns:' ) # see issue 9 idx = len ( data ) ini = 0 loop = True if key in data : while loop : i = data . find ( key ) if i != - 1 : if starting : if not data [ : i ] . rstrip ( ' \t' ) . endswith ( '\n' ) and len ( data [ : i ] . strip ( ) ) > 0 : ini = i + 1 data = data [ ini : ] else : idx = ini + i loop = False else : idx = ini + i loop = False else : loop = False if idx == len ( data ) : idx = - 1 return idx | Get from a docstring the next option with a given key . | 217 | 13 |
242,287 | def _extract_docs_description ( self ) : # FIXME: the indentation of descriptions is lost data = '\n' . join ( [ d . rstrip ( ) . replace ( self . docs [ 'out' ] [ 'spaces' ] , '' , 1 ) for d in self . docs [ 'in' ] [ 'raw' ] . splitlines ( ) ] ) if self . dst . style [ 'in' ] == 'groups' : idx = self . dst . get_group_index ( data ) elif self . dst . style [ 'in' ] == 'google' : lines = data . splitlines ( ) line_num = self . dst . googledoc . get_next_section_start_line ( lines ) if line_num == - 1 : idx = - 1 else : idx = len ( '\n' . join ( lines [ : line_num ] ) ) elif self . dst . style [ 'in' ] == 'numpydoc' : lines = data . splitlines ( ) line_num = self . dst . numpydoc . get_next_section_start_line ( lines ) if line_num == - 1 : idx = - 1 else : idx = len ( '\n' . join ( lines [ : line_num ] ) ) elif self . dst . style [ 'in' ] == 'unknown' : idx = - 1 else : idx = self . dst . get_elem_index ( data ) if idx == 0 : self . docs [ 'in' ] [ 'desc' ] = '' elif idx == - 1 : self . docs [ 'in' ] [ 'desc' ] = data else : self . docs [ 'in' ] [ 'desc' ] = data [ : idx ] | Extract main description from docstring | 396 | 7 |
242,288 | def _extract_groupstyle_docs_params ( self ) : data = '\n' . join ( [ d . rstrip ( ) . replace ( self . docs [ 'out' ] [ 'spaces' ] , '' , 1 ) for d in self . docs [ 'in' ] [ 'raw' ] . splitlines ( ) ] ) idx = self . dst . get_group_key_line ( data , 'param' ) if idx >= 0 : data = data . splitlines ( ) [ idx + 1 : ] end = self . dst . get_group_line ( '\n' . join ( data ) ) end = end if end != - 1 else len ( data ) for i in range ( end ) : # FIXME: see how retrieve multiline param description and how get type line = data [ i ] param = None desc = '' ptype = '' m = re . match ( r'^\W*(\w+)[\W\s]+(\w[\s\w]+)' , line . strip ( ) ) if m : param = m . group ( 1 ) . strip ( ) desc = m . group ( 2 ) . strip ( ) else : m = re . match ( r'^\W*(\w+)\W*' , line . strip ( ) ) if m : param = m . group ( 1 ) . strip ( ) if param : self . docs [ 'in' ] [ 'params' ] . append ( ( param , desc , ptype ) ) | Extract group style parameters | 330 | 5 |
242,289 | def _extract_docs_return ( self ) : if self . dst . style [ 'in' ] == 'numpydoc' : data = '\n' . join ( [ d . rstrip ( ) . replace ( self . docs [ 'out' ] [ 'spaces' ] , '' , 1 ) for d in self . docs [ 'in' ] [ 'raw' ] . splitlines ( ) ] ) self . docs [ 'in' ] [ 'return' ] = self . dst . numpydoc . get_return_list ( data ) self . docs [ 'in' ] [ 'rtype' ] = None # TODO: fix this elif self . dst . style [ 'in' ] == 'google' : data = '\n' . join ( [ d . rstrip ( ) . replace ( self . docs [ 'out' ] [ 'spaces' ] , '' , 1 ) for d in self . docs [ 'in' ] [ 'raw' ] . splitlines ( ) ] ) self . docs [ 'in' ] [ 'return' ] = self . dst . googledoc . get_return_list ( data ) self . docs [ 'in' ] [ 'rtype' ] = None elif self . dst . style [ 'in' ] == 'groups' : self . _extract_groupstyle_docs_return ( ) elif self . dst . style [ 'in' ] in [ 'javadoc' , 'reST' ] : self . _extract_tagstyle_docs_return ( ) | Extract return description and type | 342 | 6 |
242,290 | def _extract_docs_other ( self ) : if self . dst . style [ 'in' ] == 'numpydoc' : data = '\n' . join ( [ d . rstrip ( ) . replace ( self . docs [ 'out' ] [ 'spaces' ] , '' , 1 ) for d in self . docs [ 'in' ] [ 'raw' ] . splitlines ( ) ] ) lst = self . dst . numpydoc . get_list_key ( data , 'also' ) lst = self . dst . numpydoc . get_list_key ( data , 'ref' ) lst = self . dst . numpydoc . get_list_key ( data , 'note' ) lst = self . dst . numpydoc . get_list_key ( data , 'other' ) lst = self . dst . numpydoc . get_list_key ( data , 'example' ) lst = self . dst . numpydoc . get_list_key ( data , 'attr' ) | Extract other specific sections | 236 | 5 |
242,291 | def _set_desc ( self ) : # TODO: manage different in/out styles if self . docs [ 'in' ] [ 'desc' ] : self . docs [ 'out' ] [ 'desc' ] = self . docs [ 'in' ] [ 'desc' ] else : self . docs [ 'out' ] [ 'desc' ] = '' | Sets the global description if any | 78 | 7 |
242,292 | def _set_params ( self ) : # TODO: manage different in/out styles if self . docs [ 'in' ] [ 'params' ] : # list of parameters is like: (name, description, type) self . docs [ 'out' ] [ 'params' ] = list ( self . docs [ 'in' ] [ 'params' ] ) for e in self . element [ 'params' ] : if type ( e ) is tuple : # tuple is: (name, default) param = e [ 0 ] else : param = e found = False for i , p in enumerate ( self . docs [ 'out' ] [ 'params' ] ) : if param == p [ 0 ] : found = True # add default value if any if type ( e ) is tuple : # param will contain: (name, desc, type, default) self . docs [ 'out' ] [ 'params' ] [ i ] = ( p [ 0 ] , p [ 1 ] , p [ 2 ] , e [ 1 ] ) if not found : if type ( e ) is tuple : p = ( param , '' , None , e [ 1 ] ) else : p = ( param , '' , None , None ) self . docs [ 'out' ] [ 'params' ] . append ( p ) | Sets the parameters with types descriptions and default value if any | 278 | 12 |
242,293 | def _set_raises ( self ) : # TODO: manage different in/out styles # manage setting if not mandatory for numpy but optional if self . docs [ 'in' ] [ 'raises' ] : if self . dst . style [ 'out' ] != 'numpydoc' or self . dst . style [ 'in' ] == 'numpydoc' or ( self . dst . style [ 'out' ] == 'numpydoc' and 'raise' not in self . dst . numpydoc . get_excluded_sections ( ) ) : # list of parameters is like: (name, description) self . docs [ 'out' ] [ 'raises' ] = list ( self . docs [ 'in' ] [ 'raises' ] ) | Sets the raises and descriptions | 171 | 6 |
242,294 | def _set_return ( self ) : # TODO: manage return retrieved from element code (external) # TODO: manage different in/out styles if type ( self . docs [ 'in' ] [ 'return' ] ) is list and self . dst . style [ 'out' ] not in [ 'groups' , 'numpydoc' , 'google' ] : # TODO: manage return names # manage not setting return if not mandatory for numpy lst = self . docs [ 'in' ] [ 'return' ] if lst : if lst [ 0 ] [ 0 ] is not None : self . docs [ 'out' ] [ 'return' ] = "%s-> %s" % ( lst [ 0 ] [ 0 ] , lst [ 0 ] [ 1 ] ) else : self . docs [ 'out' ] [ 'return' ] = lst [ 0 ] [ 1 ] self . docs [ 'out' ] [ 'rtype' ] = lst [ 0 ] [ 2 ] else : self . docs [ 'out' ] [ 'return' ] = self . docs [ 'in' ] [ 'return' ] self . docs [ 'out' ] [ 'rtype' ] = self . docs [ 'in' ] [ 'rtype' ] | Sets the return parameter with description and rtype if any | 277 | 12 |
242,295 | def _set_other ( self ) : # manage not setting if not mandatory for numpy if self . dst . style [ 'in' ] == 'numpydoc' : if self . docs [ 'in' ] [ 'raw' ] is not None : self . docs [ 'out' ] [ 'post' ] = self . dst . numpydoc . get_raw_not_managed ( self . docs [ 'in' ] [ 'raw' ] ) elif 'post' not in self . docs [ 'out' ] or self . docs [ 'out' ] [ 'post' ] is None : self . docs [ 'out' ] [ 'post' ] = '' | Sets other specific sections | 148 | 5 |
242,296 | def _set_raw ( self ) : sep = self . dst . get_sep ( target = 'out' ) sep = sep + ' ' if sep != ' ' else sep with_space = lambda s : '\n' . join ( [ self . docs [ 'out' ] [ 'spaces' ] + l if i > 0 else l for i , l in enumerate ( s . splitlines ( ) ) ] ) # sets the description section raw = self . docs [ 'out' ] [ 'spaces' ] + self . quotes desc = self . docs [ 'out' ] [ 'desc' ] . strip ( ) if not desc or not desc . count ( '\n' ) : if not self . docs [ 'out' ] [ 'params' ] and not self . docs [ 'out' ] [ 'return' ] and not self . docs [ 'out' ] [ 'rtype' ] and not self . docs [ 'out' ] [ 'raises' ] : raw += desc if desc else self . trailing_space raw += self . quotes self . docs [ 'out' ] [ 'raw' ] = raw . rstrip ( ) return if not self . first_line : raw += '\n' + self . docs [ 'out' ] [ 'spaces' ] raw += with_space ( self . docs [ 'out' ] [ 'desc' ] ) . strip ( ) + '\n' # sets the parameters section raw += self . _set_raw_params ( sep ) # sets the return section raw += self . _set_raw_return ( sep ) # sets the raises section raw += self . _set_raw_raise ( sep ) # sets post specific if any if 'post' in self . docs [ 'out' ] : raw += self . docs [ 'out' ] [ 'spaces' ] + with_space ( self . docs [ 'out' ] [ 'post' ] ) . strip ( ) + '\n' # sets the doctests if any if 'doctests' in self . docs [ 'out' ] : raw += self . docs [ 'out' ] [ 'spaces' ] + with_space ( self . docs [ 'out' ] [ 'doctests' ] ) . strip ( ) + '\n' if raw . count ( self . quotes ) == 1 : raw += self . docs [ 'out' ] [ 'spaces' ] + self . quotes self . docs [ 'out' ] [ 'raw' ] = raw . rstrip ( ) | Sets the output raw docstring | 549 | 7 |
242,297 | def generate_docs ( self ) : if self . dst . style [ 'out' ] == 'numpydoc' and self . dst . numpydoc . first_line is not None : self . first_line = self . dst . numpydoc . first_line self . _set_desc ( ) self . _set_params ( ) self . _set_return ( ) self . _set_raises ( ) self . _set_other ( ) self . _set_raw ( ) self . generated_docs = True | Generates the output docstring | 117 | 6 |
242,298 | def get_files_from_dir ( path , recursive = True , depth = 0 , file_ext = '.py' ) : file_list = [ ] if os . path . isfile ( path ) or path == '-' : return [ path ] if path [ - 1 ] != os . sep : path = path + os . sep for f in glob . glob ( path + "*" ) : if os . path . isdir ( f ) : if depth < MAX_DEPTH_RECUR : # avoid infinite recursive loop file_list . extend ( get_files_from_dir ( f , recursive , depth + 1 ) ) else : continue elif f . endswith ( file_ext ) : file_list . append ( f ) return file_list | Retrieve the list of files from a folder . | 164 | 10 |
242,299 | def get_config ( config_file ) : config = { } tobool = lambda s : True if s . lower ( ) == 'true' else False if config_file : try : f = open ( config_file , 'r' ) except : print ( "Unable to open configuration file '{0}'" . format ( config_file ) ) else : for line in f . readlines ( ) : if len ( line . strip ( ) ) : key , value = line . split ( "=" , 1 ) key , value = key . strip ( ) , value . strip ( ) if key in [ 'init2class' , 'first_line' , 'convert_only' ] : value = tobool ( value ) config [ key ] = value return config | Get the configuration from a file . | 165 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.