idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
249,400 | def get_text_for_repeated_menu_item ( self , request = None , current_site = None , original_menu_tag = '' , * * kwargs ) : source_field_name = settings . PAGE_FIELD_FOR_MENU_ITEM_TEXT return self . repeated_item_text or getattr ( self , source_field_name , self . title ) | Return the a string to use as text for this page when it is being included as a repeated menu item in a menu . You might want to override this method if you re creating a multilingual site and you have different translations of repeated_item_text that you wish to surface . | 86 | 57 |
249,401 | def get_repeated_menu_item ( self , current_page , current_site , apply_active_classes , original_menu_tag , request = None , use_absolute_page_urls = False , ) : menuitem = copy ( self ) # Set/reset 'text' menuitem . text = self . get_text_for_repeated_menu_item ( request , current_site , original_menu_tag ) # Set/reset 'href' if use_absolute_page_urls : url = self . get_full_url ( request = request ) else : url = self . relative_url ( current_site ) menuitem . href = url # Set/reset 'active_class' if apply_active_classes and self == current_page : menuitem . active_class = settings . ACTIVE_CLASS else : menuitem . active_class = '' # Set/reset 'has_children_in_menu' and 'sub_menu' menuitem . has_children_in_menu = False menuitem . sub_menu = None return menuitem | Return something that can be used to display a repeated menu item for this specific page . | 241 | 17 |
249,402 | def menu_text ( self , request = None ) : source_field_name = settings . PAGE_FIELD_FOR_MENU_ITEM_TEXT if ( source_field_name != 'menu_text' and hasattr ( self , source_field_name ) ) : return getattr ( self , source_field_name ) return self . title | Return a string to use as link text when this page appears in menus . | 76 | 15 |
249,403 | def link_page_is_suitable_for_display ( self , request = None , current_site = None , menu_instance = None , original_menu_tag = '' ) : if self . link_page : if ( not self . link_page . show_in_menus or not self . link_page . live or self . link_page . expired ) : return False return True | Like menu items link pages linking to pages should only be included in menus when the target page is live and is itself configured to appear in menus . Returns a boolean indicating as much | 86 | 35 |
249,404 | def show_in_menus_custom ( self , request = None , current_site = None , menu_instance = None , original_menu_tag = '' ) : if not self . show_in_menus : return False if self . link_page : return self . link_page_is_suitable_for_display ( ) return True | Return a boolean indicating whether this page should be included in menus being rendered . | 76 | 15 |
249,405 | def accepts_kwarg ( func , kwarg ) : signature = inspect . signature ( func ) try : signature . bind_partial ( * * { kwarg : None } ) return True except TypeError : return False | Determine whether the callable func has a signature that accepts the keyword argument kwarg | 47 | 19 |
249,406 | def section_menu ( context , show_section_root = True , show_multiple_levels = True , apply_active_classes = True , allow_repeating_parents = True , max_levels = settings . DEFAULT_SECTION_MENU_MAX_LEVELS , template = '' , sub_menu_template = '' , sub_menu_templates = None , use_specific = settings . DEFAULT_SECTION_MENU_USE_SPECIFIC , use_absolute_page_urls = False , add_sub_menus_inline = None , * * kwargs ) : validate_supplied_values ( 'section_menu' , max_levels = max_levels , use_specific = use_specific ) if not show_multiple_levels : max_levels = 1 menu_class = settings . objects . SECTION_MENU_CLASS return menu_class . render_from_tag ( context = context , max_levels = max_levels , use_specific = use_specific , apply_active_classes = apply_active_classes , allow_repeating_parents = allow_repeating_parents , use_absolute_page_urls = use_absolute_page_urls , add_sub_menus_inline = add_sub_menus_inline , template_name = template , sub_menu_template_name = sub_menu_template , sub_menu_template_names = split_if_string ( sub_menu_templates ) , show_section_root = show_section_root , * * kwargs ) | Render a section menu for the current section . | 340 | 9 |
249,407 | def sub_menu ( context , menuitem_or_page , use_specific = None , allow_repeating_parents = None , apply_active_classes = None , template = '' , use_absolute_page_urls = None , add_sub_menus_inline = None , * * kwargs ) : validate_supplied_values ( 'sub_menu' , use_specific = use_specific , menuitem_or_page = menuitem_or_page ) max_levels = context . get ( 'max_levels' , settings . DEFAULT_CHILDREN_MENU_MAX_LEVELS ) if use_specific is None : use_specific = context . get ( 'use_specific' , constants . USE_SPECIFIC_AUTO ) if apply_active_classes is None : apply_active_classes = context . get ( 'apply_active_classes' , True ) if allow_repeating_parents is None : allow_repeating_parents = context . get ( 'allow_repeating_parents' , True ) if use_absolute_page_urls is None : use_absolute_page_urls = context . get ( 'use_absolute_page_urls' , False ) if add_sub_menus_inline is None : add_sub_menus_inline = context . get ( 'add_sub_menus_inline' , False ) if isinstance ( menuitem_or_page , Page ) : parent_page = menuitem_or_page else : parent_page = menuitem_or_page . link_page original_menu = context . get ( 'original_menu_instance' ) if original_menu is None : raise SubMenuUsageError ( ) menu_class = original_menu . get_sub_menu_class ( ) return menu_class . render_from_tag ( context = context , parent_page = parent_page , max_levels = max_levels , use_specific = use_specific , apply_active_classes = apply_active_classes , allow_repeating_parents = allow_repeating_parents , use_absolute_page_urls = use_absolute_page_urls , add_sub_menus_inline = add_sub_menus_inline , template_name = template , * * kwargs ) | Retrieve the children pages for the menuitem_or_page provided turn them into menu items and render them to a template . | 512 | 27 |
249,408 | def trace ( self , * attributes ) : def decorator ( f ) : def wrapper ( * args , * * kwargs ) : if self . _trace_all_requests : return f ( * args , * * kwargs ) self . _before_request_fn ( list ( attributes ) ) try : r = f ( * args , * * kwargs ) self . _after_request_fn ( ) except Exception as e : self . _after_request_fn ( error = e ) raise self . _after_request_fn ( ) return r wrapper . __name__ = f . __name__ return wrapper return decorator | Function decorator that traces functions | 138 | 6 |
249,409 | def get_span ( self , request = None ) : if request is None and stack . top : request = stack . top . request scope = self . _current_scopes . get ( request , None ) return None if scope is None else scope . span | Returns the span tracing request or the current request if request == None . | 54 | 14 |
249,410 | def initial_value ( self , field_name : str = None ) : if self . _meta . get_field ( field_name ) . get_internal_type ( ) == 'ForeignKey' : if not field_name . endswith ( '_id' ) : field_name = field_name + '_id' attribute = self . _diff_with_initial . get ( field_name , None ) if not attribute : return None return attribute [ 0 ] | Get initial value of field when model was instantiated . | 102 | 11 |
249,411 | def has_changed ( self , field_name : str = None ) -> bool : changed = self . _diff_with_initial . keys ( ) if self . _meta . get_field ( field_name ) . get_internal_type ( ) == 'ForeignKey' : if not field_name . endswith ( '_id' ) : field_name = field_name + '_id' if field_name in changed : return True return False | Check if a field has changed since the model was instantiated . | 99 | 13 |
249,412 | def _descriptor_names ( self ) : descriptor_names = [ ] for name in dir ( self ) : try : attr = getattr ( type ( self ) , name ) if isinstance ( attr , DJANGO_RELATED_FIELD_DESCRIPTOR_CLASSES ) : descriptor_names . append ( name ) except AttributeError : pass return descriptor_names | Attributes which are Django descriptors . These represent a field which is a one - to - many or many - to - many relationship that is potentially defined in another model and doesn t otherwise appear as a field on this model . | 81 | 45 |
249,413 | def _run_hooked_methods ( self , hook : str ) : for method in self . _potentially_hooked_methods : for callback_specs in method . _hooked : if callback_specs [ 'hook' ] != hook : continue when = callback_specs . get ( 'when' ) if when : if self . _check_callback_conditions ( callback_specs ) : method ( ) else : method ( ) | Iterate through decorated methods to find those that should be triggered by the current hook . If conditions exist check them before running otherwise go ahead and run . | 99 | 30 |
249,414 | def loop ( server , test_loop = None ) : try : loops_without_activity = 0 while test_loop is None or test_loop > 0 : start = time . time ( ) loops_without_activity += 1 events = server . slack . rtm_read ( ) for event in events : loops_without_activity = 0 logger . debug ( "got {0}" . format ( event ) ) response = handle_event ( event , server ) # The docs (https://api.slack.com/docs/message-threading) # suggest looking for messages where `thread_ts` != `ts`, # but I can't see anywhere that it would make a practical # difference. If a message is part of a thread, respond to # that thread. thread_ts = None if 'thread_ts' in event : thread_ts = event [ 'thread_ts' ] while response : # The Slack API documentation says: # # Clients should limit messages sent to channels to 4000 # characters, which will always be under 16k bytes even # with a message comprised solely of non-BMP Unicode # characters at 4 bytes each. # # but empirical testing shows that I'm getting disconnected # at 4000 characters and even quite a bit lower. Use 1000 # to be safe server . slack . rtm_send_message ( event [ "channel" ] , response [ : 1000 ] , thread_ts ) response = response [ 1000 : ] # Run the loop hook. This doesn't send messages it receives, # because it doesn't know where to send them. Use # server.slack.post_message to send messages from a loop hook run_hook ( server . hooks , "loop" , server ) # The Slack RTM API docs say: # # > When there is no other activity clients should send a ping # > every few seconds # # So, if we've gone >5 seconds without any activity, send a ping. # If the connection has broken, this will reveal it so slack can # quit if loops_without_activity > 5 : server . slack . ping ( ) loops_without_activity = 0 end = time . time ( ) runtime = start - end time . sleep ( max ( 1 - runtime , 0 ) ) if test_loop : test_loop -= 1 except KeyboardInterrupt : if os . environ . get ( "LIMBO_DEBUG" ) : import ipdb ipdb . set_trace ( ) raise | Run the main loop | 516 | 4 |
249,415 | def post_message ( self , channel_id , message , * * kwargs ) : params = { "post_data" : { "text" : message , "channel" : channel_id , } } params [ "post_data" ] . update ( kwargs ) return self . api_call ( "chat.postMessage" , * * params ) | Send a message using the slack Event API . | 79 | 9 |
249,416 | def post_reaction ( self , channel_id , timestamp , reaction_name , * * kwargs ) : params = { "post_data" : { "name" : reaction_name , "channel" : channel_id , "timestamp" : timestamp , } } params [ "post_data" ] . update ( kwargs ) return self . api_call ( "reactions.add" , * * params ) | Send a reaction to a message using slack Event API | 93 | 10 |
249,417 | def get_all ( self , api_method , collection_name , * * kwargs ) : objs = [ ] limit = 250 # if you don't provide a limit, the slack API won't return a cursor to you page = json . loads ( self . api_call ( api_method , limit = limit , * * kwargs ) ) while 1 : try : for obj in page [ collection_name ] : objs . append ( obj ) except KeyError : LOG . error ( "Unable to find key %s in page object: \n" "%s" , collection_name , page ) return objs cursor = dig ( page , "response_metadata" , "next_cursor" ) if cursor : # In general we allow applications that integrate with Slack to send # no more than one message per second # https://api.slack.com/docs/rate-limits time . sleep ( 1 ) page = json . loads ( self . api_call ( api_method , cursor = cursor , limit = limit , * * kwargs ) ) else : break return objs | Return all objects in an api_method handle pagination and pass kwargs on to the method being called . | 234 | 23 |
249,418 | def poll ( poll , msg , server ) : poll = remove_smart_quotes ( poll . replace ( u"\u2014" , u"--" ) ) try : args = ARGPARSE . parse_args ( shlex . split ( poll ) ) . poll except ValueError : return ERROR_INVALID_FORMAT if not 2 < len ( args ) < len ( POLL_EMOJIS ) + 1 : return ERROR_WRONG_NUMBER_OF_ARGUMENTS result = [ "Poll: {}\n" . format ( args [ 0 ] ) ] for emoji , answer in zip ( POLL_EMOJIS , args [ 1 : ] ) : result . append ( ":{}: {}\n" . format ( emoji , answer ) ) # for this we are going to need to post the message to Slack via Web API in order to # get the TS and add reactions msg_posted = server . slack . post_message ( msg [ 'channel' ] , "" . join ( result ) , as_user = server . slack . username ) ts = json . loads ( msg_posted ) [ "ts" ] for i in range ( len ( args ) - 1 ) : server . slack . post_reaction ( msg [ 'channel' ] , ts , POLL_EMOJIS [ i ] ) | Given a question and answers present a poll | 289 | 8 |
249,419 | def emoji_list ( server , n = 1 ) : global EMOJI if EMOJI is None : EMOJI = EmojiCache ( server ) return EMOJI . get ( n ) | return a list of n random emoji | 46 | 7 |
249,420 | def wiki ( searchterm ) : searchterm = quote ( searchterm ) url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json" url = url . format ( searchterm ) result = requests . get ( url ) . json ( ) pages = result [ "query" ] [ "search" ] # try to reject disambiguation pages pages = [ p for p in pages if 'may refer to' not in p [ "snippet" ] ] if not pages : return "" page = quote ( pages [ 0 ] [ "title" ] . encode ( "utf8" ) ) link = "http://en.wikipedia.org/wiki/{0}" . format ( page ) r = requests . get ( "http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}" . format ( page ) ) . json ( ) soup = BeautifulSoup ( r [ "parse" ] [ "text" ] [ "*" ] , "html5lib" ) p = soup . find ( 'p' ) . get_text ( ) p = p [ : 8000 ] return u"{0}\n{1}" . format ( p , link ) | return the top wiki search result for the term | 279 | 9 |
249,421 | def gif ( search , unsafe = False ) : searchb = quote ( search . encode ( "utf8" ) ) safe = "&safe=" if unsafe else "&safe=active" searchurl = "https://www.google.com/search?tbs=itp:animated&tbm=isch&q={0}{1}" . format ( searchb , safe ) # this is an old iphone user agent. Seems to make google return good results. useragent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us)" " AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7" result = requests . get ( searchurl , headers = { "User-agent" : useragent } ) . text gifs = list ( map ( unescape , re . findall ( r"var u='(.*?)'" , result ) ) ) shuffle ( gifs ) if gifs : return gifs [ 0 ] return "" | given a search string return a gif URL via google search | 240 | 11 |
249,422 | def on_message ( msg , server ) : text = msg . get ( "text" , "" ) match = re . findall ( r"!gif (.*)" , text ) if not match : return res = gif ( match [ 0 ] ) if not res : return attachment = { "fallback" : match [ 0 ] , "title" : match [ 0 ] , "title_link" : res , "image_url" : res } server . slack . post_message ( msg [ 'channel' ] , '' , as_user = server . slack . username , attachments = json . dumps ( [ attachment ] ) ) | handle a message and return an gif | 133 | 7 |
249,423 | def fromfile ( fname ) : fig = SVGFigure ( ) with open ( fname ) as fid : svg_file = etree . parse ( fid ) fig . root = svg_file . getroot ( ) return fig | Open SVG figure from file . | 50 | 6 |
249,424 | def fromstring ( text ) : fig = SVGFigure ( ) svg = etree . fromstring ( text . encode ( ) ) fig . root = svg return fig | Create a SVG figure from a string . | 36 | 8 |
249,425 | def from_mpl ( fig , savefig_kw = None ) : fid = StringIO ( ) if savefig_kw is None : savefig_kw = { } try : fig . savefig ( fid , format = 'svg' , * * savefig_kw ) except ValueError : raise ( ValueError , "No matplotlib SVG backend" ) fid . seek ( 0 ) fig = fromstring ( fid . read ( ) ) # workaround mpl units bug w , h = fig . get_size ( ) fig . set_size ( ( w . replace ( 'pt' , '' ) , h . replace ( 'pt' , '' ) ) ) return fig | Create a SVG figure from a matplotlib figure . | 144 | 11 |
249,426 | def moveto ( self , x , y , scale = 1 ) : self . root . set ( "transform" , "translate(%s, %s) scale(%s) %s" % ( x , y , scale , self . root . get ( "transform" ) or '' ) ) | Move and scale element . | 65 | 5 |
249,427 | def rotate ( self , angle , x = 0 , y = 0 ) : self . root . set ( "transform" , "%s rotate(%f %f %f)" % ( self . root . get ( "transform" ) or '' , angle , x , y ) ) | Rotate element by given angle around given pivot . | 59 | 10 |
249,428 | def skew ( self , x = 0 , y = 0 ) : if x is not 0 : self . skew_x ( x ) if y is not 0 : self . skew_y ( y ) return self | Skew the element by x and y degrees Convenience function which calls skew_x and skew_y | 44 | 23 |
249,429 | def skew_x ( self , x ) : self . root . set ( "transform" , "%s skewX(%f)" % ( self . root . get ( "transform" ) or '' , x ) ) return self | Skew element along the x - axis by the given angle . | 48 | 14 |
249,430 | def skew_y ( self , y ) : self . root . set ( "transform" , "%s skewY(%f)" % ( self . root . get ( "transform" ) or '' , y ) ) return self | Skew element along the y - axis by the given angle . | 48 | 14 |
249,431 | def find_id ( self , element_id ) : find = etree . XPath ( "//*[@id=$id]" ) return FigureElement ( find ( self . root , id = element_id ) [ 0 ] ) | Find element by its id . | 50 | 6 |
249,432 | def append ( self , element ) : try : self . root . append ( element . root ) except AttributeError : self . root . append ( GroupElement ( element ) . root ) | Append new element to the SVG figure | 39 | 8 |
249,433 | def getroot ( self ) : if 'class' in self . root . attrib : attrib = { 'class' : self . root . attrib [ 'class' ] } else : attrib = None return GroupElement ( self . root . getchildren ( ) , attrib = attrib ) | Return the root element of the figure . | 64 | 8 |
249,434 | def to_str ( self ) : return etree . tostring ( self . root , xml_declaration = True , standalone = True , pretty_print = True ) | Returns a string of the SVG figure . | 36 | 8 |
249,435 | def save ( self , fname ) : out = etree . tostring ( self . root , xml_declaration = True , standalone = True , pretty_print = True ) with open ( fname , 'wb' ) as fid : fid . write ( out ) | Save figure to a file | 57 | 5 |
249,436 | def set_size ( self , size ) : w , h = size self . root . set ( 'width' , w ) self . root . set ( 'height' , h ) | Set figure size | 39 | 3 |
249,437 | def find_id ( self , element_id ) : element = _transform . FigureElement . find_id ( self , element_id ) return Element ( element . root ) | Find a single element with the given ID . | 37 | 9 |
249,438 | def find_ids ( self , element_ids ) : elements = [ _transform . FigureElement . find_id ( self , eid ) for eid in element_ids ] return Panel ( * elements ) | Find elements with given IDs . | 44 | 6 |
249,439 | def save ( self , fname ) : element = _transform . SVGFigure ( self . width , self . height ) element . append ( self ) element . save ( os . path . join ( CONFIG [ 'figure.save_path' ] , fname ) ) | Save figure to SVG file . | 56 | 6 |
249,440 | def tostr ( self ) : element = _transform . SVGFigure ( self . width , self . height ) element . append ( self ) svgstr = element . to_str ( ) return svgstr | Export SVG as a string | 44 | 5 |
249,441 | def tile ( self , ncols , nrows ) : dx = ( self . width / ncols ) . to ( 'px' ) . value dy = ( self . height / nrows ) . to ( 'px' ) . value ix , iy = 0 , 0 for el in self : el . move ( dx * ix , dy * iy ) ix += 1 if ix >= ncols : ix = 0 iy += 1 if iy > nrows : break return self | Automatically tile the panels of the figure . | 110 | 9 |
249,442 | def to ( self , unit ) : u = Unit ( "0cm" ) u . value = self . value / self . per_inch [ self . unit ] * self . per_inch [ unit ] u . unit = unit return u | Convert to a given unit . | 51 | 7 |
249,443 | def dlopen ( ffi , * names ) : for name in names : for lib_name in ( name , 'lib' + name ) : try : path = ctypes . util . find_library ( lib_name ) lib = ffi . dlopen ( path or lib_name ) if lib : return lib except OSError : pass raise OSError ( "dlopen() failed to load a library: %s" % ' / ' . join ( names ) ) | Try various names for the same library for different platforms . | 105 | 11 |
249,444 | def set_source_rgba ( self , red , green , blue , alpha = 1 ) : cairo . cairo_set_source_rgba ( self . _pointer , red , green , blue , alpha ) self . _check_status ( ) | Sets the source pattern within this context to a solid color . This color will then be used for any subsequent drawing operation until a new source pattern is set . | 55 | 32 |
249,445 | def get_dash ( self ) : dashes = ffi . new ( 'double[]' , cairo . cairo_get_dash_count ( self . _pointer ) ) offset = ffi . new ( 'double *' ) cairo . cairo_get_dash ( self . _pointer , dashes , offset ) self . _check_status ( ) return list ( dashes ) , offset [ 0 ] | Return the current dash pattern . | 90 | 6 |
249,446 | def set_miter_limit ( self , limit ) : cairo . cairo_set_miter_limit ( self . _pointer , limit ) self . _check_status ( ) | Sets the current miter limit within the cairo context . | 41 | 13 |
249,447 | def get_current_point ( self ) : # I’d prefer returning None if self.has_current_point() is False # But keep (0, 0) for compat with pycairo. xy = ffi . new ( 'double[2]' ) cairo . cairo_get_current_point ( self . _pointer , xy + 0 , xy + 1 ) self . _check_status ( ) return tuple ( xy ) | Return the current point of the current path which is conceptually the final point reached by the path so far . | 99 | 22 |
249,448 | def copy_path ( self ) : path = cairo . cairo_copy_path ( self . _pointer ) result = list ( _iter_path ( path ) ) cairo . cairo_path_destroy ( path ) return result | Return a copy of the current path . | 51 | 8 |
249,449 | def copy_path_flat ( self ) : path = cairo . cairo_copy_path_flat ( self . _pointer ) result = list ( _iter_path ( path ) ) cairo . cairo_path_destroy ( path ) return result | Return a flattened copy of the current path | 55 | 8 |
249,450 | def clip_extents ( self ) : extents = ffi . new ( 'double[4]' ) cairo . cairo_clip_extents ( self . _pointer , extents + 0 , extents + 1 , extents + 2 , extents + 3 ) self . _check_status ( ) return tuple ( extents ) | Computes a bounding box in user coordinates covering the area inside the current clip . | 73 | 17 |
249,451 | def copy_clip_rectangle_list ( self ) : rectangle_list = cairo . cairo_copy_clip_rectangle_list ( self . _pointer ) _check_status ( rectangle_list . status ) rectangles = rectangle_list . rectangles result = [ ] for i in range ( rectangle_list . num_rectangles ) : rect = rectangles [ i ] result . append ( ( rect . x , rect . y , rect . width , rect . height ) ) cairo . cairo_rectangle_list_destroy ( rectangle_list ) return result | Return the current clip region as a list of rectangles in user coordinates . | 124 | 15 |
249,452 | def select_font_face ( self , family = '' , slant = constants . FONT_SLANT_NORMAL , weight = constants . FONT_WEIGHT_NORMAL ) : cairo . cairo_select_font_face ( self . _pointer , _encode_string ( family ) , slant , weight ) self . _check_status ( ) | Selects a family and style of font from a simplified description as a family name slant and weight . | 80 | 21 |
249,453 | def get_font_face ( self ) : return FontFace . _from_pointer ( cairo . cairo_get_font_face ( self . _pointer ) , incref = True ) | Return the current font face . | 42 | 6 |
249,454 | def get_scaled_font ( self ) : return ScaledFont . _from_pointer ( cairo . cairo_get_scaled_font ( self . _pointer ) , incref = True ) | Return the current scaled font . | 45 | 6 |
249,455 | def font_extents ( self ) : extents = ffi . new ( 'cairo_font_extents_t *' ) cairo . cairo_font_extents ( self . _pointer , extents ) self . _check_status ( ) # returning extents as is would be a nice API, # but return a tuple for compat with pycairo. return ( extents . ascent , extents . descent , extents . height , extents . max_x_advance , extents . max_y_advance ) | Return the extents of the currently selected font . | 118 | 10 |
249,456 | def text_extents ( self , text ) : extents = ffi . new ( 'cairo_text_extents_t *' ) cairo . cairo_text_extents ( self . _pointer , _encode_string ( text ) , extents ) self . _check_status ( ) # returning extents as is would be a nice API, # but return a tuple for compat with pycairo. return ( extents . x_bearing , extents . y_bearing , extents . width , extents . height , extents . x_advance , extents . y_advance ) | Returns the extents for a string of text . | 134 | 10 |
249,457 | def glyph_extents ( self , glyphs ) : glyphs = ffi . new ( 'cairo_glyph_t[]' , glyphs ) extents = ffi . new ( 'cairo_text_extents_t *' ) cairo . cairo_glyph_extents ( self . _pointer , glyphs , len ( glyphs ) , extents ) self . _check_status ( ) return ( extents . x_bearing , extents . y_bearing , extents . width , extents . height , extents . x_advance , extents . y_advance ) | Returns the extents for a list of glyphs . | 134 | 11 |
249,458 | def tag_begin ( self , tag_name , attributes = None ) : if attributes is None : attributes = '' cairo . cairo_tag_begin ( self . _pointer , _encode_string ( tag_name ) , _encode_string ( attributes ) ) self . _check_status ( ) | Marks the beginning of the tag_name structure . | 67 | 11 |
249,459 | def tag_end ( self , tag_name ) : cairo . cairo_tag_end ( self . _pointer , _encode_string ( tag_name ) ) self . _check_status ( ) | Marks the end of the tag_name structure . | 46 | 11 |
249,460 | def _make_read_func ( file_obj ) : @ ffi . callback ( "cairo_read_func_t" , error = constants . STATUS_READ_ERROR ) def read_func ( _closure , data , length ) : string = file_obj . read ( length ) if len ( string ) < length : # EOF too early return constants . STATUS_READ_ERROR ffi . buffer ( data , length ) [ : len ( string ) ] = string return constants . STATUS_SUCCESS return read_func | Return a CFFI callback that reads from a file - like object . | 117 | 15 |
249,461 | def _make_write_func ( file_obj ) : if file_obj is None : return ffi . NULL @ ffi . callback ( "cairo_write_func_t" , error = constants . STATUS_WRITE_ERROR ) def write_func ( _closure , data , length ) : file_obj . write ( ffi . buffer ( data , length ) ) return constants . STATUS_SUCCESS return write_func | Return a CFFI callback that writes to a file - like object . | 96 | 15 |
249,462 | def _encode_filename ( filename ) : # pragma: no cover # Don't replace unknown characters as '?' is forbidden in Windows filenames errors = 'ignore' if os . name == 'nt' else 'replace' if not isinstance ( filename , bytes ) : if os . name == 'nt' and cairo . cairo_version ( ) >= 11510 : # Since 1.15.10, cairo uses utf-8 filenames on Windows filename = filename . encode ( 'utf-8' , errors = errors ) else : try : filename = filename . encode ( sys . getfilesystemencoding ( ) ) except UnicodeEncodeError : # Use plain ASCII filenames as fallback filename = filename . encode ( 'ascii' , errors = errors ) # TODO: avoid characters forbidden in filenames? return ffi . new ( 'char[]' , filename ) | Return a byte string suitable for a filename . | 194 | 9 |
249,463 | def create_similar_image ( self , content , width , height ) : return Surface . _from_pointer ( cairo . cairo_surface_create_similar_image ( self . _pointer , content , width , height ) , incref = False ) | Create a new image surface that is as compatible as possible for uploading to and the use in conjunction with this surface . However this surface can still be used like any normal image surface . | 55 | 36 |
249,464 | def create_for_rectangle ( self , x , y , width , height ) : return Surface . _from_pointer ( cairo . cairo_surface_create_for_rectangle ( self . _pointer , x , y , width , height ) , incref = False ) | Create a new surface that is a rectangle within this surface . All operations drawn to this surface are then clipped and translated onto the target surface . Nothing drawn via this sub - surface outside of its bounds is drawn onto the target surface making this a useful method for passing constrained child surfaces to library routines that draw directly onto the parent surface i . e . with no further backend allocations double buffering or copies . | 61 | 80 |
249,465 | def set_fallback_resolution ( self , x_pixels_per_inch , y_pixels_per_inch ) : cairo . cairo_surface_set_fallback_resolution ( self . _pointer , x_pixels_per_inch , y_pixels_per_inch ) self . _check_status ( ) | Set the horizontal and vertical resolution for image fallbacks . | 75 | 11 |
249,466 | def get_font_options ( self ) : font_options = FontOptions ( ) cairo . cairo_surface_get_font_options ( self . _pointer , font_options . _pointer ) return font_options | Retrieves the default font rendering options for the surface . | 48 | 12 |
249,467 | def set_device_scale ( self , x_scale , y_scale ) : cairo . cairo_surface_set_device_scale ( self . _pointer , x_scale , y_scale ) self . _check_status ( ) | Sets a scale that is multiplied to the device coordinates determined by the CTM when drawing to surface . | 53 | 21 |
249,468 | def get_mime_data ( self , mime_type ) : buffer_address = ffi . new ( 'unsigned char **' ) buffer_length = ffi . new ( 'unsigned long *' ) mime_type = ffi . new ( 'char[]' , mime_type . encode ( 'utf8' ) ) cairo . cairo_surface_get_mime_data ( self . _pointer , mime_type , buffer_address , buffer_length ) return ( ffi . buffer ( buffer_address [ 0 ] , buffer_length [ 0 ] ) if buffer_address [ 0 ] != ffi . NULL else None ) | Return mime data previously attached to surface using the specified mime type . | 143 | 15 |
249,469 | def write_to_png ( self , target = None ) : return_bytes = target is None if return_bytes : target = io . BytesIO ( ) if hasattr ( target , 'write' ) : write_func = _make_write_func ( target ) _check_status ( cairo . cairo_surface_write_to_png_stream ( self . _pointer , write_func , ffi . NULL ) ) else : _check_status ( cairo . cairo_surface_write_to_png ( self . _pointer , _encode_filename ( target ) ) ) if return_bytes : return target . getvalue ( ) | Writes the contents of surface as a PNG image . | 143 | 11 |
249,470 | def create_from_png ( cls , source ) : if hasattr ( source , 'read' ) : read_func = _make_read_func ( source ) pointer = cairo . cairo_image_surface_create_from_png_stream ( read_func , ffi . NULL ) else : pointer = cairo . cairo_image_surface_create_from_png ( _encode_filename ( source ) ) self = object . __new__ ( cls ) Surface . __init__ ( self , pointer ) # Skip ImageSurface.__init__ return self | Decode a PNG file into a new image surface . | 127 | 11 |
249,471 | def add_outline ( self , parent_id , utf8 , link_attribs , flags = None ) : if flags is None : flags = 0 value = cairo . cairo_pdf_surface_add_outline ( self . _pointer , parent_id , _encode_string ( utf8 ) , _encode_string ( link_attribs ) , flags ) self . _check_status ( ) return value | Add an item to the document outline hierarchy . | 97 | 9 |
249,472 | def set_metadata ( self , metadata , utf8 ) : cairo . cairo_pdf_surface_set_metadata ( self . _pointer , metadata , _encode_string ( utf8 ) ) self . _check_status ( ) | Sets document metadata . | 54 | 5 |
249,473 | def set_thumbnail_size ( self , width , height ) : cairo . cairo_pdf_surface_set_thumbnail_size ( self . _pointer , width , height ) | Set thumbnail image size for the current and all subsequent pages . | 41 | 12 |
249,474 | def dsc_comment ( self , comment ) : cairo . cairo_ps_surface_dsc_comment ( self . _pointer , _encode_string ( comment ) ) self . _check_status ( ) | Emit a comment into the PostScript output for the given surface . | 48 | 14 |
249,475 | def set_document_unit ( self , unit ) : cairo . cairo_svg_surface_set_document_unit ( self . _pointer , unit ) self . _check_status ( ) | Use specified unit for width and height of generated SVG file . | 44 | 12 |
249,476 | def get_document_unit ( self ) : unit = cairo . cairo_svg_surface_get_document_unit ( self . _pointer ) self . _check_status ( ) return unit | Get the unit of the SVG surface . | 44 | 8 |
249,477 | def get_extents ( self ) : extents = ffi . new ( 'cairo_rectangle_t *' ) if cairo . cairo_recording_surface_get_extents ( self . _pointer , extents ) : return ( extents . x , extents . y , extents . width , extents . height ) | Return the extents of the recording - surface . | 76 | 10 |
249,478 | def add_color_stop_rgba ( self , offset , red , green , blue , alpha = 1 ) : cairo . cairo_pattern_add_color_stop_rgba ( self . _pointer , offset , red , green , blue , alpha ) self . _check_status ( ) | Adds a translucent color stop to a gradient pattern . | 65 | 10 |
249,479 | def _encode_string ( string ) : if not isinstance ( string , bytes ) : string = string . encode ( 'utf8' ) return ffi . new ( 'char[]' , string ) | Return a byte string encoding Unicode with UTF - 8 . | 44 | 11 |
249,480 | def text_to_glyphs ( self , x , y , text , with_clusters ) : glyphs = ffi . new ( 'cairo_glyph_t **' , ffi . NULL ) num_glyphs = ffi . new ( 'int *' ) if with_clusters : clusters = ffi . new ( 'cairo_text_cluster_t **' , ffi . NULL ) num_clusters = ffi . new ( 'int *' ) cluster_flags = ffi . new ( 'cairo_text_cluster_flags_t *' ) else : clusters = ffi . NULL num_clusters = ffi . NULL cluster_flags = ffi . NULL # TODO: Pass len_utf8 explicitly to support NULL bytes? status = cairo . cairo_scaled_font_text_to_glyphs ( self . _pointer , x , y , _encode_string ( text ) , - 1 , glyphs , num_glyphs , clusters , num_clusters , cluster_flags ) glyphs = ffi . gc ( glyphs [ 0 ] , _keepref ( cairo , cairo . cairo_glyph_free ) ) if with_clusters : clusters = ffi . gc ( clusters [ 0 ] , _keepref ( cairo , cairo . cairo_text_cluster_free ) ) _check_status ( status ) glyphs = [ ( glyph . index , glyph . x , glyph . y ) for i in range ( num_glyphs [ 0 ] ) for glyph in [ glyphs [ i ] ] ] if with_clusters : clusters = [ ( cluster . num_bytes , cluster . num_glyphs ) for i in range ( num_clusters [ 0 ] ) for cluster in [ clusters [ i ] ] ] return glyphs , clusters , cluster_flags [ 0 ] else : return glyphs | Converts a string of text to a list of glyphs optionally with cluster mapping that can be used to render later using this scaled font . | 422 | 28 |
249,481 | def set_variations ( self , variations ) : if variations is None : variations = ffi . NULL else : variations = _encode_string ( variations ) cairo . cairo_font_options_set_variations ( self . _pointer , variations ) self . _check_status ( ) | Sets the OpenType font variations for the font options object . | 64 | 13 |
249,482 | def get_variations ( self ) : variations = cairo . cairo_font_options_get_variations ( self . _pointer ) if variations != ffi . NULL : return ffi . string ( variations ) . decode ( 'utf8' , 'replace' ) | Gets the OpenType font variations for the font options object . | 59 | 13 |
249,483 | def decode_to_pixbuf ( image_data , width = None , height = None ) : loader = ffi . gc ( gdk_pixbuf . gdk_pixbuf_loader_new ( ) , gobject . g_object_unref ) error = ffi . new ( 'GError **' ) if width and height : gdk_pixbuf . gdk_pixbuf_loader_set_size ( loader , width , height ) handle_g_error ( error , gdk_pixbuf . gdk_pixbuf_loader_write ( loader , ffi . new ( 'guchar[]' , image_data ) , len ( image_data ) , error ) ) handle_g_error ( error , gdk_pixbuf . gdk_pixbuf_loader_close ( loader , error ) ) format_ = gdk_pixbuf . gdk_pixbuf_loader_get_format ( loader ) format_name = ( ffi . string ( gdk_pixbuf . gdk_pixbuf_format_get_name ( format_ ) ) . decode ( 'ascii' ) if format_ != ffi . NULL else None ) pixbuf = gdk_pixbuf . gdk_pixbuf_loader_get_pixbuf ( loader ) if pixbuf == ffi . NULL : # pragma: no cover raise ImageLoadingError ( 'Not enough image data (got a NULL pixbuf.)' ) return Pixbuf ( pixbuf ) , format_name | Decode an image from memory with GDK - PixBuf . The file format is detected automatically . | 346 | 21 |
249,484 | def decode_to_image_surface ( image_data , width = None , height = None ) : pixbuf , format_name = decode_to_pixbuf ( image_data , width , height ) surface = ( pixbuf_to_cairo_gdk ( pixbuf ) if gdk is not None else pixbuf_to_cairo_slices ( pixbuf ) if not pixbuf . get_has_alpha ( ) else pixbuf_to_cairo_png ( pixbuf ) ) return surface , format_name | Decode an image from memory into a cairo surface . The file format is detected automatically . | 125 | 19 |
249,485 | def pixbuf_to_cairo_gdk ( pixbuf ) : dummy_context = Context ( ImageSurface ( constants . FORMAT_ARGB32 , 1 , 1 ) ) gdk . gdk_cairo_set_source_pixbuf ( dummy_context . _pointer , pixbuf . _pointer , 0 , 0 ) return dummy_context . get_source ( ) . get_surface ( ) | Convert from PixBuf to ImageSurface using GDK . | 93 | 14 |
249,486 | def pixbuf_to_cairo_slices ( pixbuf ) : assert pixbuf . get_colorspace ( ) == gdk_pixbuf . GDK_COLORSPACE_RGB assert pixbuf . get_n_channels ( ) == 3 assert pixbuf . get_bits_per_sample ( ) == 8 width = pixbuf . get_width ( ) height = pixbuf . get_height ( ) rowstride = pixbuf . get_rowstride ( ) pixels = ffi . buffer ( pixbuf . get_pixels ( ) , pixbuf . get_byte_length ( ) ) # TODO: remove this when cffi buffers support slicing with a stride. pixels = pixels [ : ] # Convert GdkPixbuf’s big-endian RGBA to cairo’s native-endian ARGB cairo_stride = ImageSurface . format_stride_for_width ( constants . FORMAT_RGB24 , width ) data = bytearray ( cairo_stride * height ) big_endian = sys . byteorder == 'big' pixbuf_row_length = width * 3 # stride == row_length + padding cairo_row_length = width * 4 # stride == row_length + padding alpha = b'\xff' * width # opaque for y in range ( height ) : offset = rowstride * y end = offset + pixbuf_row_length red = pixels [ offset : end : 3 ] green = pixels [ offset + 1 : end : 3 ] blue = pixels [ offset + 2 : end : 3 ] offset = cairo_stride * y end = offset + cairo_row_length if big_endian : # pragma: no cover data [ offset : end : 4 ] = alpha data [ offset + 1 : end : 4 ] = red data [ offset + 2 : end : 4 ] = green data [ offset + 3 : end : 4 ] = blue else : data [ offset + 3 : end : 4 ] = alpha data [ offset + 2 : end : 4 ] = red data [ offset + 1 : end : 4 ] = green data [ offset : end : 4 ] = blue data = array ( 'B' , data ) return ImageSurface ( constants . FORMAT_RGB24 , width , height , data , cairo_stride ) | Convert from PixBuf to ImageSurface using slice - based byte swapping . | 521 | 17 |
249,487 | def pixbuf_to_cairo_png ( pixbuf ) : buffer_pointer = ffi . new ( 'gchar **' ) buffer_size = ffi . new ( 'gsize *' ) error = ffi . new ( 'GError **' ) handle_g_error ( error , pixbuf . save_to_buffer ( buffer_pointer , buffer_size , ffi . new ( 'char[]' , b'png' ) , error , ffi . new ( 'char[]' , b'compression' ) , ffi . new ( 'char[]' , b'0' ) , ffi . NULL ) ) png_bytes = ffi . buffer ( buffer_pointer [ 0 ] , buffer_size [ 0 ] ) return ImageSurface . create_from_png ( BytesIO ( png_bytes ) ) | Convert from PixBuf to ImageSurface by going through the PNG format . | 189 | 17 |
249,488 | def probePlayer ( requested_player = '' ) : ret_player = None if logger . isEnabledFor ( logging . INFO ) : logger . info ( "Probing available multimedia players..." ) implementedPlayers = Player . __subclasses__ ( ) if logger . isEnabledFor ( logging . INFO ) : logger . info ( "Implemented players: " + ", " . join ( [ player . PLAYER_CMD for player in implementedPlayers ] ) ) if requested_player : req = requested_player . split ( ',' ) for r_player in req : if r_player == 'vlc' : r_player = 'cvlc' for player in implementedPlayers : if player . PLAYER_CMD == r_player : ret_player = check_player ( player ) if ret_player is not None : return ret_player if ret_player is None : if logger . isEnabledFor ( logging . INFO ) : logger . info ( 'Requested player "{}" not supported' . format ( r_player ) ) else : for player in implementedPlayers : ret_player = check_player ( player ) if ret_player is not None : break return ret_player | Probes the multimedia players which are available on the host system . | 247 | 13 |
249,489 | def play ( self , name , streamUrl , encoding = '' ) : self . close ( ) self . name = name self . oldUserInput = { 'Input' : '' , 'Volume' : '' , 'Title' : '' } self . muted = False self . show_volume = True self . title_prefix = '' self . playback_is_on = False self . outputStream . write ( 'Station: "{}"' . format ( name ) , self . status_update_lock ) if logger . isEnabledFor ( logging . INFO ) : logger . info ( 'Selected Station: "{}"' . format ( name ) ) if encoding : self . _station_encoding = encoding else : self . _station_encoding = 'utf-8' opts = [ ] isPlayList = streamUrl . split ( "?" ) [ 0 ] [ - 3 : ] in [ 'm3u' , 'pls' ] opts = self . _buildStartOpts ( streamUrl , isPlayList ) self . process = subprocess . Popen ( opts , shell = False , stdout = subprocess . PIPE , stdin = subprocess . PIPE , stderr = subprocess . STDOUT ) t = threading . Thread ( target = self . updateStatus , args = ( self . status_update_lock , ) ) t . start ( ) # start playback check timer thread try : self . connection_timeout_thread = threading . Timer ( self . playback_timeout , self . playback_timeout_handler ) self . connection_timeout_thread . start ( ) except : self . connection_timeout_thread = None if ( logger . isEnabledFor ( logging . ERROR ) ) : logger . error ( "playback detection thread start failed" ) if logger . isEnabledFor ( logging . INFO ) : logger . info ( "Player started" ) | use a multimedia player to play a stream | 400 | 8 |
249,490 | def _sendCommand ( self , command ) : if ( self . process is not None ) : try : if logger . isEnabledFor ( logging . DEBUG ) : logger . debug ( "Command: {}" . format ( command ) . strip ( ) ) self . process . stdin . write ( command . encode ( 'utf-8' , 'replace' ) ) self . process . stdin . flush ( ) except : msg = "Error when sending: {}" if logger . isEnabledFor ( logging . ERROR ) : logger . error ( msg . format ( command ) . strip ( ) , exc_info = True ) | send keystroke command to player | 129 | 6 |
249,491 | def _format_title_string ( self , title_string ) : return self . _title_string_format_text_tag ( title_string . replace ( self . icy_tokkens [ 0 ] , self . icy_title_prefix ) ) | format mpv s title | 55 | 5 |
249,492 | def _format_title_string ( self , title_string ) : if "StreamTitle='" in title_string : tmp = title_string [ title_string . find ( "StreamTitle='" ) : ] . replace ( "StreamTitle='" , self . icy_title_prefix ) ret_string = tmp [ : tmp . find ( "';" ) ] else : ret_string = title_string if '"artist":"' in ret_string : """ work on format: ICY Info: START_SONG='{"artist":"Clelia Cafiero","title":"M. Mussorgsky-Quadri di un'esposizione"}'; Fund on "ClassicaViva Web Radio: Classical" """ ret_string = self . icy_title_prefix + ret_string [ ret_string . find ( '"artist":' ) + 10 : ] . replace ( '","title":"' , ' - ' ) . replace ( '"}\';' , '' ) return self . _title_string_format_text_tag ( ret_string ) | format mplayer s title | 229 | 5 |
249,493 | def _format_volume_string ( self , volume_string ) : return '[' + volume_string [ volume_string . find ( self . volume_string ) : ] . replace ( ' %' , '%' ) . replace ( 'ume' , '' ) + '] ' | format mplayer s volume | 61 | 5 |
249,494 | def _format_volume_string ( self , volume_string ) : self . actual_volume = int ( volume_string . split ( self . volume_string ) [ 1 ] . split ( ',' ) [ 0 ] . split ( ) [ 0 ] ) return '[Vol: {}%] ' . format ( int ( 100 * self . actual_volume / self . max_volume ) ) | format vlc s volume | 82 | 5 |
249,495 | def _format_title_string ( self , title_string ) : sp = title_string . split ( self . icy_tokkens [ 0 ] ) if sp [ 0 ] == title_string : ret_string = title_string else : ret_string = self . icy_title_prefix + sp [ 1 ] return self . _title_string_format_text_tag ( ret_string ) | format vlc s title | 87 | 5 |
249,496 | def _is_accepted_input ( self , input_string ) : ret = False accept_filter = ( self . volume_string , "http stream debug: " ) reject_filter = ( ) for n in accept_filter : if n in input_string : ret = True break if ret : for n in reject_filter : if n in input_string : ret = False break return ret | vlc input filtering | 84 | 4 |
249,497 | def _no_mute_on_stop_playback ( self ) : if self . ctrl_c_pressed : return if self . isPlaying ( ) : if self . actual_volume == - 1 : self . _get_volume ( ) while self . actual_volume == - 1 : pass if self . actual_volume == 0 : self . actual_volume = int ( self . max_volume * 0.25 ) self . _sendCommand ( 'volume {}\n' . format ( self . actual_volume ) ) if logger . isEnabledFor ( logging . DEBUG ) : logger . debug ( 'Unmuting VLC on exit: {} (25%)' . format ( self . actual_volume ) ) elif self . muted : if self . actual_volume > 0 : self . _sendCommand ( 'volume {}\n' . format ( self . actual_volume ) ) if logger . isEnabledFor ( logging . DEBUG ) : logger . debug ( 'VLC volume restored on exit: {0} ({1}%)' . format ( self . actual_volume , int ( 100 * self . actual_volume / self . max_volume ) ) ) self . show_volume = True | make sure vlc does not stop muted | 255 | 8 |
249,498 | def _check_stations_csv ( self , usr , root ) : if path . exists ( path . join ( usr , 'stations.csv' ) ) : return else : copyfile ( root , path . join ( usr , 'stations.csv' ) ) | Reclocate a stations . csv copy in user home for easy manage . E . g . not need sudo when you add new station etc | 61 | 29 |
249,499 | def _is_playlist_in_config_dir ( self ) : if path . dirname ( self . stations_file ) == self . stations_dir : self . foreign_file = False self . foreign_filename_only_no_extension = '' else : self . foreign_file = True self . foreign_filename_only_no_extension = self . stations_filename_only_no_extension self . foreign_copy_asked = False | Check if a csv file is in the config dir | 100 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.