idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
61,500
def _convert_unsigned ( data , fmt ) : num = len ( data ) return struct . unpack ( "{}{}" . format ( num , fmt . upper ( ) ) . encode ( "utf-8" ) , struct . pack ( "{}{}" . format ( num , fmt ) . encode ( "utf-8" ) , * data ) )
Convert data from signed to unsigned in bulk .
61,501
def convert_column ( data , schemae ) : ctype = schemae . converted_type if ctype == parquet_thrift . ConvertedType . DECIMAL : scale_factor = Decimal ( "10e-{}" . format ( schemae . scale ) ) if schemae . type == parquet_thrift . Type . INT32 or schemae . type == parquet_thrift . Type . INT64 : return [ Decimal ( unscaled ) * scale_factor for unscaled in data ] return [ Decimal ( intbig ( unscaled ) ) * scale_factor for unscaled in data ] elif ctype == parquet_thrift . ConvertedType . DATE : return [ datetime . date . fromordinal ( d ) for d in data ] elif ctype == parquet_thrift . ConvertedType . TIME_MILLIS : return [ datetime . timedelta ( milliseconds = d ) for d in data ] elif ctype == parquet_thrift . ConvertedType . TIMESTAMP_MILLIS : return [ datetime . datetime . utcfromtimestamp ( d / 1000.0 ) for d in data ] elif ctype == parquet_thrift . ConvertedType . UTF8 : return [ codecs . decode ( item , "utf-8" ) for item in data ] elif ctype == parquet_thrift . ConvertedType . UINT_8 : return _convert_unsigned ( data , 'b' ) elif ctype == parquet_thrift . ConvertedType . UINT_16 : return _convert_unsigned ( data , 'h' ) elif ctype == parquet_thrift . ConvertedType . UINT_32 : return _convert_unsigned ( data , 'i' ) elif ctype == parquet_thrift . ConvertedType . UINT_64 : return _convert_unsigned ( data , 'q' ) elif ctype == parquet_thrift . ConvertedType . JSON : return [ json . loads ( s ) for s in codecs . iterdecode ( data , "utf-8" ) ] elif ctype == parquet_thrift . ConvertedType . BSON and bson : return [ bson . BSON ( s ) . decode ( ) for s in data ] else : logger . info ( "Converted type '%s'' not handled" , parquet_thrift . ConvertedType . _VALUES_TO_NAMES [ ctype ] ) return data
Convert known types from primitive to rich .
61,502
def setup_logging ( options = None ) : level = logging . DEBUG if options is not None and options . debug else logging . WARNING console = logging . StreamHandler ( ) console . setLevel ( level ) formatter = logging . Formatter ( '%(name)s: %(levelname)-8s %(message)s' ) console . setFormatter ( formatter ) logging . getLogger ( 'parquet' ) . setLevel ( level ) logging . getLogger ( 'parquet' ) . addHandler ( console )
Configure logging based on options .
61,503
def main ( argv = None ) : argv = argv or sys . argv [ 1 : ] parser = argparse . ArgumentParser ( 'parquet' , description = 'Read parquet files' ) parser . add_argument ( '--metadata' , action = 'store_true' , help = 'show metadata on file' ) parser . add_argument ( '--row-group-metadata' , action = 'store_true' , help = "show per row group metadata" ) parser . add_argument ( '--no-data' , action = 'store_true' , help = "don't dump any data from the file" ) parser . add_argument ( '--limit' , action = 'store' , type = int , default = - 1 , help = 'max records to output' ) parser . add_argument ( '--col' , action = 'append' , type = str , help = 'only include this column (can be ' 'specified multiple times)' ) parser . add_argument ( '--no-headers' , action = 'store_true' , help = 'skip headers in output (only applies if ' 'format=csv)' ) parser . add_argument ( '--format' , action = 'store' , type = str , default = 'csv' , help = 'format for the output data. can be csv or json.' ) parser . add_argument ( '--debug' , action = 'store_true' , help = 'log debug info to stderr' ) parser . add_argument ( 'file' , help = 'path to the file to parse' ) args = parser . parse_args ( argv ) setup_logging ( args ) import parquet if args . metadata : parquet . dump_metadata ( args . file , args . row_group_metadata ) if not args . no_data : parquet . dump ( args . file , args )
Run parquet utility application .
61,504
def is_required ( self , name ) : return self . schema_element ( name ) . repetition_type == parquet_thrift . FieldRepetitionType . REQUIRED
Return true iff the schema element with the given name is required .
61,505
def max_repetition_level ( self , path ) : max_level = 0 for part in path : element = self . schema_element ( part ) if element . repetition_type == parquet_thrift . FieldRepetitionType . REQUIRED : max_level += 1 return max_level
Get the max repetition level for the given schema path .
61,506
def execute ( self , using = None ) : if not using : using = self . getConnection ( ) insertedEntities = { } for klass in self . orders : number = self . quantities [ klass ] if klass not in insertedEntities : insertedEntities [ klass ] = [ ] for i in range ( 0 , number ) : insertedEntities [ klass ] . append ( self . entities [ klass ] . execute ( using , insertedEntities ) ) return insertedEntities
Populate the database using all the Entity classes previously added .
61,507
def getGenerator ( cls , locale = None , providers = None , codename = None ) : codename = codename or cls . getCodename ( locale , providers ) if codename not in cls . generators : from faker import Faker as FakerGenerator cls . generators [ codename ] = FakerGenerator ( locale , providers ) cls . generators [ codename ] . seed ( cls . generators [ codename ] . randomInt ( ) ) return cls . generators [ codename ]
use a codename to cache generators
61,508
def _point_in_bbox ( point , bounds ) : return not ( point [ 'coordinates' ] [ 1 ] < bounds [ 0 ] or point [ 'coordinates' ] [ 1 ] > bounds [ 2 ] or point [ 'coordinates' ] [ 0 ] < bounds [ 1 ] or point [ 'coordinates' ] [ 0 ] > bounds [ 3 ] )
valid whether the point is inside the bounding box
61,509
def point_in_polygon ( point , poly ) : coords = [ poly [ 'coordinates' ] ] if poly [ 'type' ] == 'Polygon' else poly [ 'coordinates' ] return _point_in_polygon ( point , coords )
valid whether the point is located in a polygon
61,510
def draw_circle ( radius_in_meters , center_point , steps = 15 ) : steps = steps if steps > 15 else 15 center = [ center_point [ 'coordinates' ] [ 1 ] , center_point [ 'coordinates' ] [ 0 ] ] dist = ( radius_in_meters / 1000 ) / 6371 rad_center = [ number2radius ( center [ 0 ] ) , number2radius ( center [ 1 ] ) ] poly = [ ] for step in range ( 0 , steps ) : brng = 2 * math . pi * step / steps lat = math . asin ( math . sin ( rad_center [ 0 ] ) * math . cos ( dist ) + math . cos ( rad_center [ 0 ] ) * math . sin ( dist ) * math . cos ( brng ) ) lng = rad_center [ 1 ] + math . atan2 ( math . sin ( brng ) * math . sin ( dist ) * math . cos ( rad_center [ 0 ] ) , math . cos ( dist ) - math . sin ( rad_center [ 0 ] ) * math . sin ( lat ) ) poly . append ( [ number2degree ( lng ) , number2degree ( lat ) ] ) return { "type" : "Polygon" , "coordinates" : [ poly ] }
get a circle shape polygon based on centerPoint and radius
61,511
def rectangle_centroid ( rectangle ) : bbox = rectangle [ 'coordinates' ] [ 0 ] xmin = bbox [ 0 ] [ 0 ] ymin = bbox [ 0 ] [ 1 ] xmax = bbox [ 2 ] [ 0 ] ymax = bbox [ 2 ] [ 1 ] xwidth = xmax - xmin ywidth = ymax - ymin return { 'type' : 'Point' , 'coordinates' : [ xmin + xwidth / 2 , ymin + ywidth / 2 ] }
get the centroid of the rectangle
61,512
def geometry_within_radius ( geometry , center , radius ) : if geometry [ 'type' ] == 'Point' : return point_distance ( geometry , center ) <= radius elif geometry [ 'type' ] == 'LineString' or geometry [ 'type' ] == 'Polygon' : point = { } coordinates = geometry [ 'coordinates' ] [ 0 ] if geometry [ 'type' ] == 'Polygon' else geometry [ 'coordinates' ] for coordinate in coordinates : point [ 'coordinates' ] = coordinate if point_distance ( point , center ) > radius : return False return True
To valid whether point or linestring or polygon is inside a radius around a center
61,513
def area ( poly ) : poly_area = 0 points = poly [ 'coordinates' ] [ 0 ] j = len ( points ) - 1 count = len ( points ) for i in range ( 0 , count ) : p1_x = points [ i ] [ 1 ] p1_y = points [ i ] [ 0 ] p2_x = points [ j ] [ 1 ] p2_y = points [ j ] [ 0 ] poly_area += p1_x * p2_y poly_area -= p1_y * p2_x j = i poly_area /= 2 return poly_area
calculate the area of polygon
61,514
def destination_point ( point , brng , dist ) : dist = float ( dist ) / 6371 brng = number2radius ( brng ) lon1 = number2radius ( point [ 'coordinates' ] [ 0 ] ) lat1 = number2radius ( point [ 'coordinates' ] [ 1 ] ) lat2 = math . asin ( math . sin ( lat1 ) * math . cos ( dist ) + math . cos ( lat1 ) * math . sin ( dist ) * math . cos ( brng ) ) lon2 = lon1 + math . atan2 ( math . sin ( brng ) * math . sin ( dist ) * math . cos ( lat1 ) , math . cos ( dist ) - math . sin ( lat1 ) * math . sin ( lat2 ) ) lon2 = ( lon2 + 3 * math . pi ) % ( 2 * math . pi ) - math . pi return { 'type' : 'Point' , 'coordinates' : [ number2degree ( lon2 ) , number2degree ( lat2 ) ] }
Calculate a destination Point base on a base point and a distance
61,515
def merge_featurecollection ( * jsons ) : features = [ ] for json in jsons : if json [ 'type' ] == 'FeatureCollection' : for feature in json [ 'features' ] : features . append ( feature ) return { "type" : 'FeatureCollection' , "features" : features }
merge features into one featurecollection
61,516
def trace_dispatch ( self , frame , event , arg ) : if hasattr ( self , 'vimpdb' ) : return self . vimpdb . trace_dispatch ( frame , event , arg ) else : return self . _orig_trace_dispatch ( frame , event , arg )
allow to switch to Vimpdb instance
61,517
def hook ( klass ) : if not hasattr ( klass , 'do_vim' ) : setupMethod ( klass , trace_dispatch ) klass . __bases__ += ( SwitcherToVimpdb , )
monkey - patch pdb . Pdb class
61,518
def trace_dispatch ( self , frame , event , arg ) : if hasattr ( self , 'pdb' ) : return self . pdb . trace_dispatch ( frame , event , arg ) else : return Pdb . trace_dispatch ( self , frame , event , arg )
allow to switch to Pdb instance
61,519
def get_context_data ( self , ** kwargs ) : data = { } if self . _contextual_vals . current_level == 1 and self . max_levels > 1 : data [ 'sub_menu_template' ] = self . sub_menu_template . template . name data . update ( kwargs ) return super ( ) . get_context_data ( ** data )
Include the name of the sub menu template in the context . This is purely for backwards compatibility . Any sub menus rendered as part of this menu will call sub_menu_template on the original menu instance to get an actual Template
61,520
def render_from_tag ( cls , context , max_levels = None , use_specific = None , apply_active_classes = True , allow_repeating_parents = True , use_absolute_page_urls = False , add_sub_menus_inline = None , template_name = '' , ** kwargs ) : instance = cls . _get_render_prepared_object ( 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_name , ** kwargs ) if not instance : return '' return instance . render_to_template ( )
A template tag should call this method to render a menu . The Context instance and option values provided are used to get or create a relevant menu instance prepare it then render it and it s menu items to an appropriate template .
61,521
def _create_contextualvals_obj_from_context ( cls , context ) : context_processor_vals = context . get ( 'wagtailmenus_vals' , { } ) return ContextualVals ( context , context [ 'request' ] , get_site_from_request ( context [ 'request' ] ) , context . get ( 'current_level' , 0 ) + 1 , context . get ( 'original_menu_tag' , cls . related_templatetag_name ) , context . get ( 'original_menu_instance' ) , context_processor_vals . get ( 'current_page' ) , context_processor_vals . get ( 'section_root' ) , context_processor_vals . get ( 'current_page_ancestor_ids' , ( ) ) , )
Gathers all of the contextual data needed to render a menu instance and returns it in a structure that can be conveniently referenced throughout the process of preparing the menu and menu items and for rendering .
61,522
def render_to_template ( self ) : context_data = self . get_context_data ( ) template = self . get_template ( ) context_data [ 'current_template' ] = template . template . name return template . render ( context_data )
Render the current menu instance to a template and return a string
61,523
def get_common_hook_kwargs ( self , ** kwargs ) : opt_vals = self . _option_vals hook_kwargs = self . _contextual_vals . _asdict ( ) hook_kwargs . update ( { 'menu_instance' : self , 'menu_tag' : self . related_templatetag_name , 'parent_page' : None , 'max_levels' : self . max_levels , 'use_specific' : self . use_specific , 'apply_active_classes' : opt_vals . apply_active_classes , 'allow_repeating_parents' : opt_vals . allow_repeating_parents , 'use_absolute_page_urls' : opt_vals . use_absolute_page_urls , } ) if hook_kwargs [ 'original_menu_instance' ] is None : hook_kwargs [ 'original_menu_instance' ] = self hook_kwargs . update ( kwargs ) return hook_kwargs
Returns a dictionary of common values to be passed as keyword arguments to methods registered as hooks .
61,524
def get_page_children_dict ( self , page_qs = None ) : children_dict = defaultdict ( list ) for page in page_qs or self . pages_for_display : children_dict [ page . path [ : - page . steplen ] ] . append ( page ) return children_dict
Returns a dictionary of lists where the keys are path values for pages and the value is a list of children pages for that page .
61,525
def get_context_data ( self , ** kwargs ) : ctx_vals = self . _contextual_vals opt_vals = self . _option_vals data = self . create_dict_from_parent_context ( ) data . update ( ctx_vals . _asdict ( ) ) data . update ( { 'apply_active_classes' : opt_vals . apply_active_classes , 'allow_repeating_parents' : opt_vals . allow_repeating_parents , 'use_absolute_page_urls' : opt_vals . use_absolute_page_urls , 'max_levels' : self . max_levels , 'use_specific' : self . use_specific , 'menu_instance' : self , self . menu_instance_context_name : self , 'section_root' : data [ 'current_section_root_page' ] , 'current_ancestor_ids' : data [ 'current_page_ancestor_ids' ] , } ) if not ctx_vals . original_menu_instance and ctx_vals . current_level == 1 : data [ 'original_menu_instance' ] = self if 'menu_items' not in kwargs : data [ 'menu_items' ] = self . get_menu_items_for_rendering ( ) data . update ( kwargs ) return data
Return a dictionary containing all of the values needed to render the menu instance to a template including values that might be used by the sub_menu tag to render any additional levels .
61,526
def get_menu_items_for_rendering ( self ) : items = self . get_raw_menu_items ( ) for hook in hooks . get_hooks ( 'menus_modify_raw_menu_items' ) : items = hook ( items , ** self . common_hook_kwargs ) items = self . modify_menu_items ( self . prime_menu_items ( items ) ) if isinstance ( items , GeneratorType ) : items = list ( items ) hook_methods = hooks . get_hooks ( 'menus_modify_primed_menu_items' ) for hook in hook_methods : items = hook ( items , ** self . common_hook_kwargs ) return items
Return a list of menu items to be included in the context for rendering the current level of the menu .
61,527
def _replace_with_specific_page ( page , menu_item ) : if type ( page ) is Page : page = page . specific if isinstance ( menu_item , MenuItem ) : menu_item . link_page = page else : menu_item = page return page , menu_item
If page is a vanilla Page object replace it with a specific version of itself . Also update menu_item depending on whether it s a MenuItem object or a Page object .
61,528
def prime_menu_items ( self , menu_items ) : for item in menu_items : item = self . _prime_menu_item ( item ) if item is not None : yield item
A generator method that takes a list of MenuItem or Page objects and sets a number of additional attributes on each item that are useful in menu templates .
61,529
def get_children_for_page ( self , page ) : if self . max_levels == 1 : return self . pages_for_display return super ( ) . get_children_for_page ( page )
Return a list of relevant child pages for a given page
61,530
def get_top_level_items ( self ) : menu_items = self . get_base_menuitem_queryset ( ) page_ids = tuple ( obj . link_page_id for obj in menu_items if obj . link_page_id ) page_dict = { } if page_ids : top_level_pages = self . get_base_page_queryset ( ) . filter ( id__in = page_ids ) if self . use_specific >= constants . USE_SPECIFIC_TOP_LEVEL : top_level_pages = top_level_pages . specific ( ) page_dict = { p . id : p for p in top_level_pages } menu_item_list = [ ] for item in menu_items : if not item . link_page_id : menu_item_list . append ( item ) continue if item . link_page_id in page_dict . keys ( ) : item . link_page = page_dict . get ( item . link_page_id ) menu_item_list . append ( item ) return menu_item_list
Return a list of menu items with link_page objects supplemented with specific pages where appropriate .
61,531
def get_for_site ( cls , site ) : instance , created = cls . objects . get_or_create ( site = site ) return instance
Return the main menu instance for the provided site
61,532
def get_form_kwargs ( self ) : kwargs = super ( ) . get_form_kwargs ( ) if self . request . method == 'POST' : data = copy ( self . request . POST ) i = 0 while ( data . get ( '%s-%s-id' % ( settings . FLAT_MENU_ITEMS_RELATED_NAME , i ) ) ) : data [ '%s-%s-id' % ( settings . FLAT_MENU_ITEMS_RELATED_NAME , i ) ] = None i += 1 kwargs . update ( { 'data' : data , 'instance' : self . model ( ) } ) return kwargs
When the form is posted don t pass an instance to the form . It should create a new one out of the posted data . We also need to nullify any IDs posted for inline menu items so that new instances of those are created too .
61,533
def modify_submenu_items ( self , menu_items , current_page , current_ancestor_ids , current_site , allow_repeating_parents , apply_active_classes , original_menu_tag , menu_instance = None , request = None , use_absolute_page_urls = False , ) : if ( allow_repeating_parents and menu_items and self . repeat_in_subnav ) : repeated_item = self . get_repeated_menu_item ( current_page = current_page , current_site = current_site , apply_active_classes = apply_active_classes , original_menu_tag = original_menu_tag , use_absolute_page_urls = use_absolute_page_urls , request = request , ) menu_items . insert ( 0 , repeated_item ) return menu_items
Make any necessary modifications to menu_items and return the list back to the calling menu tag to render in templates . Any additional items added should have a text and href attribute as a minimum .
61,534
def has_submenu_items ( self , current_page , allow_repeating_parents , original_menu_tag , menu_instance = None , request = None ) : return menu_instance . page_has_children ( self )
When rendering pages in a menu template a has_children_in_menu attribute is added to each page letting template developers know whether or not the item has a submenu that must be rendered .
61,535
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 .
61,536
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 ) menuitem . text = self . get_text_for_repeated_menu_item ( request , current_site , original_menu_tag ) if use_absolute_page_urls : url = self . get_full_url ( request = request ) else : url = self . relative_url ( current_site ) menuitem . href = url if apply_active_classes and self == current_page : menuitem . active_class = settings . ACTIVE_CLASS else : menuitem . active_class = '' 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 .
61,537
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 .
61,538
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
61,539
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 .
61,540
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
61,541
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 .
61,542
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 .
61,543
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
61,544
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 .
61,545
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 .
61,546
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 .
61,547
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 .
61,548
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 .
61,549
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 ) thread_ts = None if 'thread_ts' in event : thread_ts = event [ 'thread_ts' ] while response : server . slack . rtm_send_message ( event [ "channel" ] , response [ : 1000 ] , thread_ts ) response = response [ 1000 : ] run_hook ( server . hooks , "loop" , server ) 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
61,550
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 .
61,551
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
61,552
def get_all ( self , api_method , collection_name , ** kwargs ) : objs = [ ] limit = 250 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 : 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 .
61,553
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 ) ) 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
61,554
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
61,555
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" ] 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
61,556
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 ) 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
61,557
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
61,558
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 .
61,559
def fromstring ( text ) : fig = SVGFigure ( ) svg = etree . fromstring ( text . encode ( ) ) fig . root = svg return fig
Create a SVG figure from a string .
61,560
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 ( ) ) w , h = fig . get_size ( ) fig . set_size ( ( w . replace ( 'pt' , '' ) , h . replace ( 'pt' , '' ) ) ) return fig
Create a SVG figure from a matplotlib figure .
61,561
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 .
61,562
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 .
61,563
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
61,564
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 .
61,565
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 .
61,566
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 .
61,567
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
61,568
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 .
61,569
def to_str ( self ) : return etree . tostring ( self . root , xml_declaration = True , standalone = True , pretty_print = True )
Returns a string of the SVG figure .
61,570
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
61,571
def set_size ( self , size ) : w , h = size self . root . set ( 'width' , w ) self . root . set ( 'height' , h )
Set figure size
61,572
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 .
61,573
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 .
61,574
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 .
61,575
def tostr ( self ) : element = _transform . SVGFigure ( self . width , self . height ) element . append ( self ) svgstr = element . to_str ( ) return svgstr
Export SVG as a string
61,576
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 .
61,577
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 .
61,578
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 .
61,579
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 .
61,580
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 .
61,581
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 .
61,582
def get_current_point ( self ) : 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 .
61,583
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 .
61,584
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
61,585
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 .
61,586
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 .
61,587
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 .
61,588
def get_font_face ( self ) : return FontFace . _from_pointer ( cairo . cairo_get_font_face ( self . _pointer ) , incref = True )
Return the current font face .
61,589
def get_scaled_font ( self ) : return ScaledFont . _from_pointer ( cairo . cairo_get_scaled_font ( self . _pointer ) , incref = True )
Return the current scaled font .
61,590
def font_extents ( self ) : extents = ffi . new ( 'cairo_font_extents_t *' ) cairo . cairo_font_extents ( self . _pointer , extents ) self . _check_status ( ) return ( extents . ascent , extents . descent , extents . height , extents . max_x_advance , extents . max_y_advance )
Return the extents of the currently selected font .
61,591
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 ( ) 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 .
61,592
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 .
61,593
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 .
61,594
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 .
61,595
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 : 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 .
61,596
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 .
61,597
def _encode_filename ( filename ) : errors = 'ignore' if os . name == 'nt' else 'replace' if not isinstance ( filename , bytes ) : if os . name == 'nt' and cairo . cairo_version ( ) >= 11510 : filename = filename . encode ( 'utf-8' , errors = errors ) else : try : filename = filename . encode ( sys . getfilesystemencoding ( ) ) except UnicodeEncodeError : filename = filename . encode ( 'ascii' , errors = errors ) return ffi . new ( 'char[]' , filename )
Return a byte string suitable for a filename .
61,598
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 .
61,599
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 .