idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
12,400 | def _cleanup ( self , status , expires_multiplier = 1 ) : # self.expires is inherited, and defaults to 1 day (or setting CELERY_TASK_RESULT_EXPIRES) expires = self . expires if isinstance ( self . expires , timedelta ) else timedelta ( seconds = self . expires ) expires = expires * expires_multiplier chords_to_delete = ChordData . objects . filter ( callback_result__date_done__lte = datetime . now ( ) - expires , callback_result__status = status ) . iterator ( ) for _chord in chords_to_delete : subtask_ids = [ subtask . task_id for subtask in _chord . completed_results . all ( ) ] _chord . completed_results . clear ( ) TaskMeta . objects . filter ( task_id__in = subtask_ids ) . delete ( ) _chord . callback_result . delete ( ) _chord . delete ( ) | u Clean up expired records . | 218 | 6 |
12,401 | def on_chord_part_return ( self , task , state , result , propagate = False ) : # pylint: disable=redefined-outer-name with transaction . atomic ( ) : chord_data = ChordData . objects . select_for_update ( ) . get ( # select_for_update will prevent race conditions callback_result__task_id = task . request . chord [ u'options' ] [ u'task_id' ] ) _ = TaskMeta . objects . update_or_create ( task_id = task . request . id , defaults = { u'status' : state , u'result' : result } ) if chord_data . is_ready ( ) : # we don't use celery beat, so this is as good a place as any to fire off periodic cleanup tasks self . get_suitable_app ( current_app ) . tasks [ u'celery.backend_cleanup' ] . apply_async ( ) chord_data . execute_callback ( ) | u Update the linking ChordData object and execute callback if needed . | 223 | 14 |
12,402 | def apply_chord ( self , header , partial_args , group_id , body , * * options ) : callback_entry = TaskMeta . objects . create ( task_id = body . id ) chord_data = ChordData . objects . create ( callback_result = callback_entry ) for subtask in header : subtask_entry = TaskMeta . objects . create ( task_id = subtask . id ) chord_data . completed_results . add ( subtask_entry ) if body . options . get ( u'use_iterator' , None ) is None : body . options [ u'use_iterator' ] = True chord_data . serialized_callback = json . dumps ( body ) chord_data . save ( ) return header ( * partial_args , task_id = group_id ) | u Instantiate a linking ChordData object before executing subtasks . | 176 | 14 |
12,403 | def get_suitable_app ( cls , given_app ) : if not isinstance ( getattr ( given_app , 'backend' , None ) , ChordableDjangoBackend ) : return_app = deepcopy ( given_app ) return_app . backend = ChordableDjangoBackend ( return_app ) return return_app else : return given_app | u Return a clone of given_app with ChordableDjangoBackend if needed . | 84 | 19 |
12,404 | def linked_model_for_class ( self , cls , make_constants_variable = False , * * kwargs ) : constructor_args = inspect . getfullargspec ( cls ) . args attribute_tuples = self . attribute_tuples new_model = PriorModel ( cls ) for attribute_tuple in attribute_tuples : name = attribute_tuple . name if name in constructor_args or ( is_tuple_like_attribute_name ( name ) and tuple_name ( name ) in constructor_args ) : attribute = kwargs [ name ] if name in kwargs else attribute_tuple . value if make_constants_variable and isinstance ( attribute , Constant ) : new_attribute = getattr ( new_model , name ) if isinstance ( new_attribute , Prior ) : new_attribute . mean = attribute . value continue setattr ( new_model , name , attribute ) return new_model | Create a PriorModel wrapping the specified class with attributes from this instance . Priors can be overridden using keyword arguments . Any constructor arguments of the new class for which there is no attribute associated with this class and no keyword argument are created from config . | 206 | 50 |
12,405 | def instance_for_arguments ( self , arguments : { Prior : float } ) : for prior , value in arguments . items ( ) : prior . assert_within_limits ( value ) model_arguments = { t . name : arguments [ t . prior ] for t in self . direct_prior_tuples } constant_arguments = { t . name : t . constant . value for t in self . direct_constant_tuples } for tuple_prior in self . tuple_prior_tuples : model_arguments [ tuple_prior . name ] = tuple_prior . prior . value_for_arguments ( arguments ) for prior_model_tuple in self . direct_prior_model_tuples : model_arguments [ prior_model_tuple . name ] = prior_model_tuple . prior_model . instance_for_arguments ( arguments ) return self . cls ( * * { * * model_arguments , * * constant_arguments } ) | Create an instance of the associated class for a set of arguments | 221 | 12 |
12,406 | def gaussian_prior_model_for_arguments ( self , arguments ) : new_model = copy . deepcopy ( self ) model_arguments = { t . name : arguments [ t . prior ] for t in self . direct_prior_tuples } for tuple_prior_tuple in self . tuple_prior_tuples : setattr ( new_model , tuple_prior_tuple . name , tuple_prior_tuple . prior . gaussian_tuple_prior_for_arguments ( arguments ) ) for prior_tuple in self . direct_prior_tuples : setattr ( new_model , prior_tuple . name , model_arguments [ prior_tuple . name ] ) for constant_tuple in self . constant_tuples : setattr ( new_model , constant_tuple . name , constant_tuple . constant ) for name , prior_model in self . direct_prior_model_tuples : setattr ( new_model , name , prior_model . gaussian_prior_model_for_arguments ( arguments ) ) return new_model | Create a new instance of model mapper with a set of Gaussian priors based on tuples provided by a previous \ nonlinear search . | 251 | 29 |
12,407 | def load_post ( self , wp_post_id ) : path = "sites/{}/posts/{}" . format ( self . site_id , wp_post_id ) response = self . get ( path ) if response . ok and response . text : api_post = response . json ( ) self . get_ref_data_map ( bulk_mode = False ) self . load_wp_post ( api_post , bulk_mode = False ) # the post should exist in the db now, so return it so that callers can work with it try : post = Post . objects . get ( site_id = self . site_id , wp_id = wp_post_id ) except Exception as ex : logger . exception ( "Unable to load post with wp_post_id={}:\n{}" . format ( wp_post_id , ex . message ) ) else : return post else : logger . warning ( "Unable to load post with wp_post_id={}:\n{}" . format ( wp_post_id , response . text ) ) | Refresh local content for a single post from the the WordPress REST API . This can be called from a webhook on the WordPress side when a post is updated . | 243 | 33 |
12,408 | def load_categories ( self , max_pages = 30 ) : logger . info ( "loading categories" ) # clear them all out so we don't get dupes if requested if self . purge_first : Category . objects . filter ( site_id = self . site_id ) . delete ( ) path = "sites/{}/categories" . format ( self . site_id ) params = { "number" : 100 } page = 1 response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) while response . ok and response . text and page < max_pages : logger . info ( " - page: %d" , page ) api_categories = response . json ( ) . get ( "categories" ) if not api_categories : # we're done here break categories = [ ] for api_category in api_categories : # if it exists locally, update local version if anything has changed existing_category = Category . objects . filter ( site_id = self . site_id , wp_id = api_category [ "ID" ] ) . first ( ) if existing_category : self . update_existing_category ( existing_category , api_category ) else : categories . append ( self . get_new_category ( api_category ) ) if categories : Category . objects . bulk_create ( categories ) elif not self . full : # we're done here break # get next page page += 1 params [ "page" ] = page response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) return | Load all WordPress categories from the given site . | 398 | 9 |
12,409 | def get_new_category ( self , api_category ) : return Category ( site_id = self . site_id , wp_id = api_category [ "ID" ] , * * self . api_object_data ( "category" , api_category ) ) | Instantiate a new Category from api data . | 60 | 9 |
12,410 | def load_tags ( self , max_pages = 30 ) : logger . info ( "loading tags" ) # clear them all out so we don't get dupes if requested if self . purge_first : Tag . objects . filter ( site_id = self . site_id ) . delete ( ) path = "sites/{}/tags" . format ( self . site_id ) params = { "number" : 1000 } page = 1 response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) while response . ok and response . text and page < max_pages : logger . info ( " - page: %d" , page ) api_tags = response . json ( ) . get ( "tags" ) if not api_tags : # we're done here break tags = [ ] for api_tag in api_tags : # if it exists locally, update local version if anything has changed existing_tag = Tag . objects . filter ( site_id = self . site_id , wp_id = api_tag [ "ID" ] ) . first ( ) if existing_tag : self . update_existing_tag ( existing_tag , api_tag ) else : tags . append ( self . get_new_tag ( api_tag ) ) if tags : Tag . objects . bulk_create ( tags ) elif not self . full : # we're done here break # get next page page += 1 params [ "page" ] = page response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) return | Load all WordPress tags from the given site . | 392 | 9 |
12,411 | def get_new_tag ( self , api_tag ) : return Tag ( site_id = self . site_id , wp_id = api_tag [ "ID" ] , * * self . api_object_data ( "tag" , api_tag ) ) | Instantiate a new Tag from api data . | 60 | 9 |
12,412 | def load_authors ( self , max_pages = 10 ) : logger . info ( "loading authors" ) # clear them all out so we don't get dupes if requested if self . purge_first : Author . objects . filter ( site_id = self . site_id ) . delete ( ) path = "sites/{}/users" . format ( self . site_id ) params = { "number" : 100 } page = 1 response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) while response . ok and response . text and page < max_pages : logger . info ( " - page: %d" , page ) api_users = response . json ( ) . get ( "users" ) if not api_users : # we're done here break authors = [ ] for api_author in api_users : # if it exists locally, update local version if anything has changed existing_author = Author . objects . filter ( site_id = self . site_id , wp_id = api_author [ "ID" ] ) . first ( ) if existing_author : self . update_existing_author ( existing_author , api_author ) else : authors . append ( self . get_new_author ( api_author ) ) if authors : Author . objects . bulk_create ( authors ) elif not self . full : # we're done here break # get next page # this endpoint doesn't have a page param, so use offset params [ "offset" ] = page * 100 page += 1 response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) return | Load all WordPress authors from the given site . | 407 | 9 |
12,413 | def get_new_author ( self , api_author ) : return Author ( site_id = self . site_id , wp_id = api_author [ "ID" ] , * * self . api_object_data ( "author" , api_author ) ) | Instantiate a new Author from api data . | 60 | 9 |
12,414 | def load_media ( self , max_pages = 150 ) : logger . info ( "loading media" ) # clear them all out so we don't get dupes if self . purge_first : logger . warning ( "purging ALL media from site %s" , self . site_id ) Media . objects . filter ( site_id = self . site_id ) . delete ( ) path = "sites/{}/media" . format ( self . site_id ) params = { "number" : 100 } self . set_media_params_after ( params ) page = 1 response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) while response . ok and response . text and page < max_pages : logger . info ( " - page: %d" , page ) api_medias = response . json ( ) . get ( "media" ) if not api_medias : # we're done here break medias = [ ] for api_media in api_medias : # exclude media items that are not attached to posts (for now) if api_media [ "post_ID" ] != 0 : # if it exists locally, update local version if anything has changed existing_media = Media . objects . filter ( site_id = self . site_id , wp_id = api_media [ "ID" ] ) . first ( ) if existing_media : self . update_existing_media ( existing_media , api_media ) else : medias . append ( self . get_new_media ( api_media ) ) if medias : Media . objects . bulk_create ( medias ) # get next page page += 1 params [ "page" ] = page response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) return | Load all WordPress media from the given site . | 445 | 9 |
12,415 | def get_new_media ( self , api_media ) : return Media ( site_id = self . site_id , wp_id = api_media [ "ID" ] , * * self . api_object_data ( "media" , api_media ) ) | Instantiate a new Media from api data . | 60 | 9 |
12,416 | def get_ref_data_map ( self , bulk_mode = True ) : if bulk_mode : self . ref_data_map = { "authors" : { a . wp_id : a for a in Author . objects . filter ( site_id = self . site_id ) } , "categories" : { c . wp_id : c for c in Category . objects . filter ( site_id = self . site_id ) } , "tags" : { t . wp_id : t for t in Tag . objects . filter ( site_id = self . site_id ) } , "media" : { m . wp_id : m for m in Media . objects . filter ( site_id = self . site_id ) } } else : # in single post mode, WP ref data is handled dynamically for the post self . ref_data_map = { "authors" : { } , "categories" : { } , "tags" : { } , "media" : { } } | Get referential data from the local db into the self . ref_data_map dictionary . This allows for fast FK lookups when looping through posts . | 224 | 34 |
12,417 | def load_posts ( self , post_type = None , max_pages = 200 , status = None ) : logger . info ( "loading posts with post_type=%s" , post_type ) # clear them all out so we don't get dupes if self . purge_first : Post . objects . filter ( site_id = self . site_id , post_type = post_type ) . delete ( ) path = "sites/{}/posts" . format ( self . site_id ) # type allows us to pull information about pages, attachments, guest-authors, etc. # you know, posts that aren't posts... thank you WordPress! if not post_type : post_type = "post" if not status : status = "publish" params = { "number" : self . batch_size , "type" : post_type , "status" : status } self . set_posts_param_modified_after ( params , post_type , status ) # get first page response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) # process all posts in the response self . process_posts_response ( response , path , params , max_pages ) | Load all WordPress posts of a given post_type from a site . | 288 | 14 |
12,418 | def set_posts_param_modified_after ( self , params , post_type , status ) : if not self . purge_first and not self . full and not self . modified_after : if status == "any" : latest = Post . objects . filter ( post_type = post_type ) . order_by ( "-modified" ) . first ( ) else : latest = Post . objects . filter ( post_type = post_type , status = status ) . order_by ( "-modified" ) . first ( ) if latest : self . modified_after = latest . modified if self . modified_after : params [ "modified_after" ] = self . modified_after . isoformat ( ) logger . info ( "getting posts after: %s" , params [ "modified_after" ] ) | Set modified_after date to continue where we left off if appropriate | 173 | 13 |
12,419 | def load_wp_post ( self , api_post , bulk_mode = True , post_categories = None , post_tags = None , post_media_attachments = None , posts = None ) : # initialize reference vars if none supplied if post_categories is None : post_categories = { } if post_tags is None : post_tags = { } if post_media_attachments is None : post_media_attachments = { } if posts is None : posts = [ ] # process objects related to this post author = None if api_post [ "author" ] . get ( "ID" ) : author = self . process_post_author ( bulk_mode , api_post [ "author" ] ) # process many-to-many fields self . process_post_categories ( bulk_mode , api_post , post_categories ) self . process_post_tags ( bulk_mode , api_post , post_tags ) self . process_post_media_attachments ( bulk_mode , api_post , post_media_attachments ) # if this post exists, update it; else create it existing_post = Post . objects . filter ( site_id = self . site_id , wp_id = api_post [ "ID" ] ) . first ( ) if existing_post : self . process_existing_post ( existing_post , api_post , author , post_categories , post_tags , post_media_attachments ) else : self . process_new_post ( bulk_mode , api_post , posts , author , post_categories , post_tags , post_media_attachments ) # if this is a real post (not an attachment, page, etc.), sync child attachments that haven been deleted # these are generally other posts with post_type=attachment representing media that has been "uploaded to the post" # they can be deleted on the WP side, creating an orphan here without this step. if api_post [ "type" ] == "post" : self . sync_deleted_attachments ( api_post ) | Load a single post from API data . | 457 | 8 |
12,420 | def process_post_author ( self , bulk_mode , api_author ) : # get from the ref data map if in bulk mode, else look it up from the db if bulk_mode : author = self . ref_data_map [ "authors" ] . get ( api_author [ "ID" ] ) if author : self . update_existing_author ( author , api_author ) else : # if the author wasn't found (likely because it's a Byline or guest author, not a user), # go ahead and create the author now author = Author . objects . create ( site_id = self . site_id , wp_id = api_author [ "ID" ] , * * self . api_object_data ( "author" , api_author ) ) else : # do a direct db lookup if we're not in bulk mode author , created = self . get_or_create_author ( api_author ) if author and not created : self . update_existing_author ( author , api_author ) # add to the ref data map so we don't try to create it again if author : self . ref_data_map [ "authors" ] [ api_author [ "ID" ] ] = author return author | Create or update an Author related to a post . | 267 | 10 |
12,421 | def get_or_create_author ( self , api_author ) : return Author . objects . get_or_create ( site_id = self . site_id , wp_id = api_author [ "ID" ] , defaults = self . api_object_data ( "author" , api_author ) ) | Find or create an Author object given API data . | 70 | 10 |
12,422 | def process_post_categories ( self , bulk_mode , api_post , post_categories ) : post_categories [ api_post [ "ID" ] ] = [ ] for api_category in six . itervalues ( api_post [ "categories" ] ) : category = self . process_post_category ( bulk_mode , api_category ) if category : post_categories [ api_post [ "ID" ] ] . append ( category ) | Create or update Categories related to a post . | 104 | 9 |
12,423 | def process_post_category ( self , bulk_mode , api_category ) : category = None # try to get from the ref data map if in bulk mode if bulk_mode : category = self . ref_data_map [ "categories" ] . get ( api_category [ "ID" ] ) # double check the db before giving up, we may have sync'd it in a previous run if not category : category , created = Category . objects . get_or_create ( site_id = self . site_id , wp_id = api_category [ "ID" ] , defaults = self . api_object_data ( "category" , api_category ) ) if category and not created : self . update_existing_category ( category , api_category ) # add to ref data map so later lookups work if category : self . ref_data_map [ "categories" ] [ api_category [ "ID" ] ] = category return category | Create or update a Category related to a post . | 207 | 10 |
12,424 | def process_post_tags ( self , bulk_mode , api_post , post_tags ) : post_tags [ api_post [ "ID" ] ] = [ ] for api_tag in six . itervalues ( api_post [ "tags" ] ) : tag = self . process_post_tag ( bulk_mode , api_tag ) if tag : post_tags [ api_post [ "ID" ] ] . append ( tag ) | Create or update Tags related to a post . | 99 | 9 |
12,425 | def process_post_tag ( self , bulk_mode , api_tag ) : tag = None # try to get from the ref data map if in bulk mode if bulk_mode : tag = self . ref_data_map [ "tags" ] . get ( api_tag [ "ID" ] ) # double check the db before giving up, we may have sync'd it in a previous run if not tag : tag , created = Tag . objects . get_or_create ( site_id = self . site_id , wp_id = api_tag [ "ID" ] , defaults = self . api_object_data ( "tag" , api_tag ) ) if tag and not created : self . update_existing_tag ( tag , api_tag ) # add to ref data map so later lookups work if tag : self . ref_data_map [ "tags" ] [ api_tag [ "ID" ] ] = tag return tag | Create or update a Tag related to a post . | 205 | 10 |
12,426 | def process_post_media_attachments ( self , bulk_mode , api_post , post_media_attachments ) : post_media_attachments [ api_post [ "ID" ] ] = [ ] for api_attachment in six . itervalues ( api_post [ "attachments" ] ) : attachment = self . process_post_media_attachment ( bulk_mode , api_attachment ) if attachment : post_media_attachments [ api_post [ "ID" ] ] . append ( attachment ) | Create or update Media objects related to a post . | 117 | 10 |
12,427 | def process_post_media_attachment ( self , bulk_mode , api_media_attachment ) : attachment = None # try to get from the ref data map if in bulk mode if bulk_mode : attachment = self . ref_data_map [ "media" ] . get ( api_media_attachment [ "ID" ] ) # double check the db before giving up, we may have sync'd it in a previous run if not attachment : # do a direct db lookup if we're not in bulk mode attachment , created = self . get_or_create_media ( api_media_attachment ) if attachment and not created : self . update_existing_media ( attachment , api_media_attachment ) # add to ref data map so later lookups work if attachment : self . ref_data_map [ "media" ] [ api_media_attachment [ "ID" ] ] = attachment return attachment | Create or update a Media attached to a post . | 197 | 10 |
12,428 | def get_or_create_media ( self , api_media ) : return Media . objects . get_or_create ( site_id = self . site_id , wp_id = api_media [ "ID" ] , defaults = self . api_object_data ( "media" , api_media ) ) | Find or create a Media object given API data . | 70 | 10 |
12,429 | def process_existing_post ( existing_post , api_post , author , post_categories , post_tags , post_media_attachments ) : # don't bother checking what's different, just update all fields existing_post . author = author existing_post . post_date = api_post [ "date" ] existing_post . modified = api_post [ "modified" ] existing_post . title = api_post [ "title" ] existing_post . url = api_post [ "URL" ] existing_post . short_url = api_post [ "short_URL" ] existing_post . content = api_post [ "content" ] existing_post . excerpt = api_post [ "excerpt" ] existing_post . slug = api_post [ "slug" ] existing_post . guid = api_post [ "guid" ] existing_post . status = api_post [ "status" ] existing_post . sticky = api_post [ "sticky" ] existing_post . password = api_post [ "password" ] existing_post . parent = api_post [ "parent" ] existing_post . post_type = api_post [ "type" ] existing_post . likes_enabled = api_post [ "likes_enabled" ] existing_post . sharing_enabled = api_post [ "sharing_enabled" ] existing_post . like_count = api_post [ "like_count" ] existing_post . global_ID = api_post [ "global_ID" ] existing_post . featured_image = api_post [ "featured_image" ] existing_post . format = api_post [ "format" ] existing_post . menu_order = api_post [ "menu_order" ] existing_post . metadata = api_post [ "metadata" ] existing_post . post_thumbnail = api_post [ "post_thumbnail" ] WPAPILoader . process_post_many_to_many_field ( existing_post , "categories" , post_categories ) WPAPILoader . process_post_many_to_many_field ( existing_post , "tags" , post_tags ) WPAPILoader . process_post_many_to_many_field ( existing_post , "attachments" , post_media_attachments ) existing_post . save ( ) | Sync attributes for a single post from WP API data . | 523 | 11 |
12,430 | def process_post_many_to_many_field ( existing_post , field , related_objects ) : to_add = set ( related_objects . get ( existing_post . wp_id , set ( ) ) ) - set ( getattr ( existing_post , field ) . all ( ) ) to_remove = set ( getattr ( existing_post , field ) . all ( ) ) - set ( related_objects . get ( existing_post . wp_id , set ( ) ) ) if to_add : getattr ( existing_post , field ) . add ( * to_add ) if to_remove : getattr ( existing_post , field ) . remove ( * to_remove ) | Sync data for a many - to - many field related to a post using set differences . | 154 | 18 |
12,431 | def bulk_create_posts ( self , posts , post_categories , post_tags , post_media_attachments ) : Post . objects . bulk_create ( posts ) # attach many-to-ones for post_wp_id , categories in six . iteritems ( post_categories ) : Post . objects . get ( site_id = self . site_id , wp_id = post_wp_id ) . categories . add ( * categories ) for post_id , tags in six . iteritems ( post_tags ) : Post . objects . get ( site_id = self . site_id , wp_id = post_id ) . tags . add ( * tags ) for post_id , attachments in six . iteritems ( post_media_attachments ) : Post . objects . get ( site_id = self . site_id , wp_id = post_id ) . attachments . add ( * attachments ) | Actually do a db bulk creation of posts and link up the many - to - many fields | 203 | 18 |
12,432 | def sync_deleted_attachments ( self , api_post ) : existing_IDs = set ( Post . objects . filter ( site_id = self . site_id , post_type = "attachment" , parent__icontains = '"ID":{}' . format ( api_post [ "ID" ] ) ) . values_list ( "wp_id" , flat = True ) ) # can't delete what we don't have if existing_IDs : api_IDs = set ( ) # call the API again to the get the full list of attachment posts whose parent is this post's wp_id path = "sites/{}/posts/" . format ( self . site_id ) params = { "type" : "attachment" , "parent_id" : api_post [ "ID" ] , "fields" : "ID" , "number" : 100 } page = 1 response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) # loop around since there may be more than 100 attachments (example: really large slideshows) while response . ok and response . text and page < 10 : api_json = response . json ( ) api_attachments = api_json . get ( "posts" , [ ] ) # iteratively extend the set to include this page's IDs api_IDs |= set ( a [ "ID" ] for a in api_attachments ) # get next page page += 1 next_page_handle = api_json . get ( "meta" , { } ) . get ( "next_page" ) if next_page_handle : params [ "page_handle" ] = next_page_handle else : # no more pages left break response = self . get ( path , params ) if not response . ok : logger . warning ( "Response NOT OK! status_code=%s\n%s" , response . status_code , response . text ) return # perform set difference to_remove = existing_IDs - api_IDs # purge the extras if to_remove : Post . objects . filter ( site_id = self . site_id , post_type = "attachment" , parent__icontains = '"ID":{}' . format ( api_post [ "ID" ] ) , wp_id__in = list ( to_remove ) ) . delete ( ) | Remove Posts with post_type = attachment that have been removed from the given Post on the WordPress side . | 542 | 21 |
12,433 | def nextparent ( self , parent , depth ) : if depth > 1 : # can't jump to parent of root node! pdir = os . path . dirname ( self . name ) line = 0 for c , d in parent . traverse ( ) : if line > parent . curline and c . name . startswith ( pdir ) : parent . curline += 1 line += 1 else : # otherwise just skip to next directory line = - 1 # skip hidden parent node for c , d in parent . traverse ( ) : if line > parent . curline : parent . curline += 1 if os . path . isdir ( c . name ) and c . name in parent . children [ 0 : ] : break line += 1 | Add lines to current line by traversing the grandparent object again and once we reach our current line counting every line that is prefixed with the parent directory . | 155 | 32 |
12,434 | def prevparent ( self , parent , depth ) : pdir = os . path . dirname ( self . name ) if depth > 1 : # can't jump to parent of root node! for c , d in parent . traverse ( ) : if c . name == self . name : break if c . name . startswith ( pdir ) : parent . curline -= 1 else : # otherwise jus skip to previous directory pdir = self . name # - 1 otherwise hidden parent node throws count off & our # self.curline doesn't change! line = - 1 for c , d in parent . traverse ( ) : if c . name == self . name : break if os . path . isdir ( c . name ) and c . name in parent . children [ 0 : ] : parent . curline = line line += 1 return pdir | Subtract lines from our curline if the name of a node is prefixed with the parent directory when traversing the grandparent object . | 179 | 29 |
12,435 | def token ( config , token ) : if not token : info_out ( "To generate a personal API token, go to:\n\n\t" "https://github.com/settings/tokens\n\n" "To read more about it, go to:\n\n\t" "https://help.github.com/articles/creating-an-access" "-token-for-command-line-use/\n\n" 'Remember to enable "repo" in the scopes.' ) token = getpass . getpass ( "GitHub API Token: " ) . strip ( ) url = urllib . parse . urljoin ( config . github_url , "/user" ) assert url . startswith ( "https://" ) , url response = requests . get ( url , headers = { "Authorization" : "token {}" . format ( token ) } ) if response . status_code == 200 : update ( config . configfile , { "GITHUB" : { "github_url" : config . github_url , "token" : token , "login" : response . json ( ) [ "login" ] , } } , ) name = response . json ( ) [ "name" ] or response . json ( ) [ "login" ] success_out ( "Hi! {}" . format ( name ) ) else : error_out ( "Failed - {} ({})" . format ( response . status_code , response . content ) ) | Store and fetch a GitHub access token | 324 | 7 |
12,436 | def log_response ( handler ) : content_type = handler . _headers . get ( 'Content-Type' , None ) headers_str = handler . _generate_headers ( ) block = 'Response Infomations:\n' + headers_str . strip ( ) if content_type and ( 'text' in content_type or 'json' in content_type ) : limit = 0 if 'LOG_RESPONSE_LINE_LIMIT' in settings : limit = settings [ 'LOG_RESPONSE_LINE_LIMIT' ] def cut ( s ) : if limit and len ( s ) > limit : return [ s [ : limit ] ] + cut ( s [ limit : ] ) else : return [ s ] body = '' . join ( handler . _write_buffer ) lines = [ ] for i in body . split ( '\n' ) : lines += [ '| ' + j for j in cut ( i ) ] block += '\nBody:\n' + '\n' . join ( lines ) app_log . info ( block ) | Acturally logging response is not a server s responsibility you should use http tools like Chrome Developer Tools to analyse the response . | 233 | 24 |
12,437 | def log_request ( handler ) : block = 'Request Infomations:\n' + _format_headers_log ( handler . request . headers ) if handler . request . arguments : block += '+----Arguments----+\n' for k , v in handler . request . arguments . items ( ) : block += '| {0:<15} | {1:<15} \n' . format ( repr ( k ) , repr ( v ) ) app_log . info ( block ) | Logging request is opposite to response sometime its necessary feel free to enable it . | 107 | 16 |
12,438 | def _exception_default_handler ( self , e ) : if isinstance ( e , HTTPError ) : if e . log_message : format = "%d %s: " + e . log_message args = [ e . status_code , self . _request_summary ( ) ] + list ( e . args ) app_log . warning ( format , * args ) if e . status_code not in httplib . responses : app_log . error ( "Bad HTTP status code: %d" , e . status_code ) self . send_error ( 500 , exc_info = sys . exc_info ( ) ) else : self . send_error ( e . status_code , exc_info = sys . exc_info ( ) ) else : app_log . error ( "Uncaught exception %s\n%r" , self . _request_summary ( ) , self . request , exc_info = True ) self . send_error ( 500 , exc_info = sys . exc_info ( ) ) | This method is a copy of tornado . web . RequestHandler . _handle_request_exception | 223 | 20 |
12,439 | def _handle_request_exception ( self , e ) : handle_func = self . _exception_default_handler if self . EXCEPTION_HANDLERS : for excs , func_name in self . EXCEPTION_HANDLERS . items ( ) : if isinstance ( e , excs ) : handle_func = getattr ( self , func_name ) break handle_func ( e ) if not self . _finished : self . finish ( ) | This method handle HTTPError exceptions the same as how tornado does leave other exceptions to be handled by user defined handler function maped in class attribute EXCEPTION_HANDLERS | 104 | 36 |
12,440 | def flush ( self , * args , * * kwgs ) : if settings [ 'LOG_RESPONSE' ] and not self . _status_code == 500 : log_response ( self ) super ( BaseHandler , self ) . flush ( * args , * * kwgs ) | Before RequestHandler . flush was called we got the final _write_buffer . | 63 | 16 |
12,441 | def write_json ( self , chunk , code = None , headers = None ) : assert chunk is not None , 'None cound not be written in write_json' self . set_header ( "Content-Type" , "application/json; charset=UTF-8" ) if isinstance ( chunk , dict ) or isinstance ( chunk , list ) : chunk = self . json_encode ( chunk ) # convert chunk to utf8 before `RequestHandler.write()` # so that if any error occurs, we can catch and log it try : chunk = utf8 ( chunk ) except Exception : app_log . error ( 'chunk encoding error, repr: %s' % repr ( chunk ) ) raise_exc_info ( sys . exc_info ( ) ) self . write ( chunk ) if code : self . set_status ( code ) if headers : for k , v in headers . items ( ) : self . set_header ( k , v ) | A convenient method that binds chunk code headers together | 209 | 9 |
12,442 | def write_file ( self , file_path , mime_type = None ) : if not os . path . exists ( file_path ) : raise HTTPError ( 404 ) if not os . path . isfile ( file_path ) : raise HTTPError ( 403 , "%s is not a file" , file_path ) stat_result = os . stat ( file_path ) modified = datetime . datetime . fromtimestamp ( stat_result [ stat . ST_MTIME ] ) self . set_header ( "Last-Modified" , modified ) if not mime_type : mime_type , _encoding = mimetypes . guess_type ( file_path ) if mime_type : self . set_header ( "Content-Type" , mime_type ) # Check the If-Modified-Since, and don't send the result if the # content has not been modified ims_value = self . request . headers . get ( "If-Modified-Since" ) if ims_value is not None : date_tuple = email . utils . parsedate ( ims_value ) if_since = datetime . datetime . fromtimestamp ( time . mktime ( date_tuple ) ) if if_since >= modified : self . set_status ( 304 ) return with open ( file_path , "rb" ) as file : data = file . read ( ) hasher = hashlib . sha1 ( ) hasher . update ( data ) self . set_header ( "Etag" , '"%s"' % hasher . hexdigest ( ) ) self . write ( data ) | Copy from tornado . web . StaticFileHandler | 357 | 9 |
12,443 | def prepare ( self ) : if settings [ 'LOG_REQUEST' ] : log_request ( self ) for i in self . PREPARES : getattr ( self , 'prepare_' + i ) ( ) if self . _finished : return | Behaves like a middleware between raw request and handling process | 54 | 12 |
12,444 | def csv_to_dicts ( file , header = None ) : with open ( file ) as csvfile : return [ row for row in csv . DictReader ( csvfile , fieldnames = header ) ] | Reads a csv and returns a List of Dicts with keys given by header row . | 49 | 19 |
12,445 | def cli ( config , configfile , verbose ) : config . verbose = verbose config . configfile = configfile if not os . path . isfile ( configfile ) : state . write ( configfile , { } ) | A glorious command line tool to make your life with git GitHub and Bugzilla much easier . | 50 | 18 |
12,446 | def parse_uri ( self , uri = None ) : # no uri provided, assume root if not uri : return rdflib . term . URIRef ( self . root ) # string uri provided elif type ( uri ) == str : # assume "short" uri, expand with repo root if type ( uri ) == str and not uri . startswith ( 'http' ) : return rdflib . term . URIRef ( "%s%s" % ( self . root , uri ) ) # else, assume full uri else : return rdflib . term . URIRef ( uri ) # already rdflib.term.URIRef elif type ( uri ) == rdflib . term . URIRef : return uri # unknown input else : raise TypeError ( 'invalid URI input' ) | parses and cleans up possible uri inputs return instance of rdflib . term . URIRef | 192 | 23 |
12,447 | def create_resource ( self , resource_type = None , uri = None ) : if resource_type in [ NonRDFSource , Binary , BasicContainer , DirectContainer , IndirectContainer ] : return resource_type ( self , uri ) else : raise TypeError ( "expecting Resource type, such as BasicContainer or NonRDFSource" ) | Convenience method for creating a new resource | 76 | 9 |
12,448 | def start_txn ( self , txn_name = None ) : # if no name provided, create one if not txn_name : txn_name = uuid . uuid4 ( ) . hex # request new transaction txn_response = self . api . http_request ( 'POST' , '%s/fcr:tx' % self . root , data = None , headers = None ) # if 201, transaction was created if txn_response . status_code == 201 : txn_uri = txn_response . headers [ 'Location' ] logger . debug ( "spawning transaction: %s" % txn_uri ) # init new Transaction, and pass Expires header txn = Transaction ( self , # pass the repository txn_name , txn_uri , expires = txn_response . headers [ 'Expires' ] ) # append to self self . txns [ txn_name ] = txn # return return txn | Request new transaction from repository init new Transaction store in self . txns | 210 | 14 |
12,449 | def get_txn ( self , txn_name , txn_uri ) : # parse uri txn_uri = self . parse_uri ( txn_uri ) # request new transaction txn_response = self . api . http_request ( 'GET' , txn_uri , data = None , headers = None ) # if 200, transaction exists if txn_response . status_code == 200 : logger . debug ( "transactoin found: %s" % txn_uri ) # init new Transaction, and pass Expires header txn = Transaction ( self , # pass the repository txn_name , txn_uri , expires = None ) # append to self self . txns [ txn_name ] = txn # return return txn # if 404, transaction does not exist elif txn_response . status_code in [ 404 , 410 ] : logger . debug ( "transaction does not exist: %s" % txn_uri ) return False else : raise Exception ( 'HTTP %s, could not retrieve transaction' % txn_response . status_code ) | Retrieves known transaction and adds to self . txns . | 239 | 13 |
12,450 | def keep_alive ( self ) : # keep transaction alive txn_response = self . api . http_request ( 'POST' , '%sfcr:tx' % self . root , data = None , headers = None ) # if 204, transaction kept alive if txn_response . status_code == 204 : logger . debug ( "continuing transaction: %s" % self . root ) # update status and timer self . active = True self . expires = txn_response . headers [ 'Expires' ] return True # if 410, transaction does not exist elif txn_response . status_code == 410 : logger . debug ( "transaction does not exist: %s" % self . root ) self . active = False return False else : raise Exception ( 'HTTP %s, could not continue transaction' % txn_response . status_code ) | Keep current transaction alive updates self . expires | 186 | 8 |
12,451 | def _close ( self , close_type ) : # commit transaction txn_response = self . api . http_request ( 'POST' , '%sfcr:tx/fcr:%s' % ( self . root , close_type ) , data = None , headers = None ) # if 204, transaction was closed if txn_response . status_code == 204 : logger . debug ( "%s for transaction: %s, successful" % ( close_type , self . root ) ) # update self.active self . active = False # return return True # if 410 or 404, transaction does not exist elif txn_response . status_code in [ 404 , 410 ] : logger . debug ( "transaction does not exist: %s" % self . root ) # update self.active self . active = False return False else : raise Exception ( 'HTTP %s, could not commit transaction' % txn_response . status_code ) | Ends transaction by committing or rolling back all changes during transaction . | 204 | 13 |
12,452 | def http_request ( self , verb , uri , data = None , headers = None , files = None , response_format = None , is_rdf = True , stream = False ) : # set content negotiated response format for RDFSources if is_rdf : ''' Acceptable content negotiated response formats include: application/ld+json (discouraged, if not prohibited, as it drops prefixes used in repository) application/n-triples application/rdf+xml text/n3 (or text/rdf+n3) text/plain text/turtle (or application/x-turtle) ''' # set for GET requests only if verb == 'GET' : # if no response_format has been requested to this point, use repository instance default if not response_format : response_format = self . repo . default_serialization # if headers present, append if headers and 'Accept' not in headers . keys ( ) : headers [ 'Accept' ] = response_format # if headers are blank, init dictionary else : headers = { 'Accept' : response_format } # prepare uri for HTTP request if type ( uri ) == rdflib . term . URIRef : uri = uri . toPython ( ) logger . debug ( "%s request for %s, format %s, headers %s" % ( verb , uri , response_format , headers ) ) # manually prepare request session = requests . Session ( ) request = requests . Request ( verb , uri , auth = ( self . repo . username , self . repo . password ) , data = data , headers = headers , files = files ) prepped_request = session . prepare_request ( request ) response = session . send ( prepped_request , stream = stream , ) return response | Primary route for all HTTP requests to repository . Ability to set most parameters for requests library with some additional convenience parameters as well . | 383 | 25 |
12,453 | def parse_rdf_payload ( self , data , headers ) : # handle edge case for content-types not recognized by rdflib parser if headers [ 'Content-Type' ] . startswith ( 'text/plain' ) : logger . debug ( 'text/plain Content-Type detected, using application/n-triples for parser' ) parse_format = 'application/n-triples' else : parse_format = headers [ 'Content-Type' ] # clean parse format for rdf parser (see: https://www.w3.org/2008/01/rdf-media-types) if ';charset' in parse_format : parse_format = parse_format . split ( ';' ) [ 0 ] # parse graph graph = rdflib . Graph ( ) . parse ( data = data . decode ( 'utf-8' ) , format = parse_format ) # return graph return graph | small function to parse RDF payloads from various repository endpoints | 203 | 13 |
12,454 | def _derive_namespaces ( self ) : # iterate through graphs and get unique namespace uris for graph in [ self . diffs . overlap , self . diffs . removed , self . diffs . added ] : for s , p , o in graph : try : ns_prefix , ns_uri , predicate = graph . compute_qname ( p ) # predicates self . update_namespaces . add ( ns_uri ) except : logger . debug ( 'could not parse Object URI: %s' % ns_uri ) try : ns_prefix , ns_uri , predicate = graph . compute_qname ( o ) # objects self . update_namespaces . add ( ns_uri ) except : logger . debug ( 'could not parse Object URI: %s' % ns_uri ) logger . debug ( self . update_namespaces ) # build unique prefixes dictionary # NOTE: can improve by using self.rdf.uris (reverse lookup of self.rdf.prefixes) for ns_uri in self . update_namespaces : for k in self . prefixes . __dict__ : if str ( ns_uri ) == str ( self . prefixes . __dict__ [ k ] ) : logger . debug ( 'adding prefix %s for uri %s to unique_prefixes' % ( k , str ( ns_uri ) ) ) self . update_prefixes [ k ] = self . prefixes . __dict__ [ k ] | Small method to loop through three graphs in self . diffs identify unique namespace URIs . Then loop through provided dictionary of prefixes and pin one to another . | 315 | 32 |
12,455 | def check_exists ( self ) : response = self . repo . api . http_request ( 'HEAD' , self . uri ) self . status_code = response . status_code # resource exists if self . status_code == 200 : self . exists = True # resource no longer here elif self . status_code == 410 : self . exists = False # resource not found elif self . status_code == 404 : self . exists = False return self . exists | Check if resource exists update self . exists returns | 101 | 9 |
12,456 | def create ( self , specify_uri = False , ignore_tombstone = False , serialization_format = None , stream = False , auto_refresh = None ) : # if resource claims existence, raise exception if self . exists : raise Exception ( 'resource exists attribute True, aborting' ) # else, continue else : # determine verb based on specify_uri parameter if specify_uri : verb = 'PUT' else : verb = 'POST' logger . debug ( 'creating resource %s with verb %s' % ( self . uri , verb ) ) # check if NonRDFSource, or extension thereof #if so, run self.binary._prep_binary() if issubclass ( type ( self ) , NonRDFSource ) : self . binary . _prep_binary ( ) data = self . binary . data # otherwise, prep for RDF else : # determine serialization if not serialization_format : serialization_format = self . repo . default_serialization data = self . rdf . graph . serialize ( format = serialization_format ) logger . debug ( 'Serialized graph used for resource creation:' ) logger . debug ( data . decode ( 'utf-8' ) ) self . headers [ 'Content-Type' ] = serialization_format # fire creation request response = self . repo . api . http_request ( verb , self . uri , data = data , headers = self . headers , stream = stream ) return self . _handle_create ( response , ignore_tombstone , auto_refresh ) | Primary method to create resources . | 332 | 6 |
12,457 | def options ( self ) : # http request response = self . repo . api . http_request ( 'OPTIONS' , self . uri ) return response . headers | Small method to return headers of an OPTIONS request to self . uri | 36 | 15 |
12,458 | def copy ( self , destination ) : # set move headers destination_uri = self . repo . parse_uri ( destination ) # http request response = self . repo . api . http_request ( 'COPY' , self . uri , data = None , headers = { 'Destination' : destination_uri . toPython ( ) } ) # handle response if response . status_code == 201 : return destination_uri else : raise Exception ( 'HTTP %s, could not move resource %s to %s' % ( response . status_code , self . uri , destination_uri ) ) | Method to copy resource to another location | 128 | 7 |
12,459 | def delete ( self , remove_tombstone = True ) : response = self . repo . api . http_request ( 'DELETE' , self . uri ) # update exists if response . status_code == 204 : # removal successful, updating self self . _empty_resource_attributes ( ) if remove_tombstone : self . repo . api . http_request ( 'DELETE' , '%s/fcr:tombstone' % self . uri ) return True | Method to delete resources . | 108 | 5 |
12,460 | def refresh ( self , refresh_binary = True ) : updated_self = self . repo . get_resource ( self . uri ) # if resource type of updated_self != self, raise exception if not isinstance ( self , type ( updated_self ) ) : raise Exception ( 'Instantiated %s, but repository reports this resource is %s' % ( type ( updated_self ) , type ( self ) ) ) if updated_self : # update attributes self . status_code = updated_self . status_code self . rdf . data = updated_self . rdf . data self . headers = updated_self . headers self . exists = updated_self . exists # update graph if RDFSource if type ( self ) != NonRDFSource : self . _parse_graph ( ) # empty versions self . versions = SimpleNamespace ( ) # if NonRDF, set binary attributes if type ( updated_self ) == NonRDFSource and refresh_binary : self . binary . refresh ( updated_self ) # fire resource._post_create hook if exists if hasattr ( self , '_post_refresh' ) : self . _post_refresh ( ) # cleanup del ( updated_self ) else : logger . debug ( 'resource %s not found, dumping values' ) self . _empty_resource_attributes ( ) | Performs GET request and refreshes RDF information for resource . | 288 | 13 |
12,461 | def _build_rdf ( self , data = None ) : # recreate rdf data self . rdf = SimpleNamespace ( ) self . rdf . data = data self . rdf . prefixes = SimpleNamespace ( ) self . rdf . uris = SimpleNamespace ( ) # populate prefixes for prefix , uri in self . repo . context . items ( ) : setattr ( self . rdf . prefixes , prefix , rdflib . Namespace ( uri ) ) # graph self . _parse_graph ( ) | Parse incoming rdf as self . rdf . orig_graph create copy at self . rdf . graph | 118 | 23 |
12,462 | def _parse_graph ( self ) : # if resource exists, parse self.rdf.data if self . exists : self . rdf . graph = self . repo . api . parse_rdf_payload ( self . rdf . data , self . headers ) # else, create empty graph else : self . rdf . graph = rdflib . Graph ( ) # bind any additional namespaces from repo instance, but do not override self . rdf . namespace_manager = rdflib . namespace . NamespaceManager ( self . rdf . graph ) for ns_prefix , ns_uri in self . rdf . prefixes . __dict__ . items ( ) : self . rdf . namespace_manager . bind ( ns_prefix , ns_uri , override = False ) # conversely, add namespaces from parsed graph to self.rdf.prefixes for ns_prefix , ns_uri in self . rdf . graph . namespaces ( ) : setattr ( self . rdf . prefixes , ns_prefix , rdflib . Namespace ( ns_uri ) ) setattr ( self . rdf . uris , rdflib . Namespace ( ns_uri ) , ns_prefix ) # pin old graph to resource, create copy graph for modifications self . rdf . _orig_graph = copy . deepcopy ( self . rdf . graph ) # parse triples for object-like access self . parse_object_like_triples ( ) | use Content - Type from headers to determine parsing method | 320 | 10 |
12,463 | def parse_object_like_triples ( self ) : # parse triples as object-like attributes in self.rdf.triples self . rdf . triples = SimpleNamespace ( ) # prepare triples for s , p , o in self . rdf . graph : # get ns info ns_prefix , ns_uri , predicate = self . rdf . graph . compute_qname ( p ) # if prefix as list not yet added, add if not hasattr ( self . rdf . triples , ns_prefix ) : setattr ( self . rdf . triples , ns_prefix , SimpleNamespace ( ) ) # same for predicate if not hasattr ( getattr ( self . rdf . triples , ns_prefix ) , predicate ) : setattr ( getattr ( self . rdf . triples , ns_prefix ) , predicate , [ ] ) # append object for this prefix getattr ( getattr ( self . rdf . triples , ns_prefix ) , predicate ) . append ( o ) | method to parse triples from self . rdf . graph for object - like access | 222 | 17 |
12,464 | def _empty_resource_attributes ( self ) : self . status_code = 404 self . headers = { } self . exists = False # build RDF self . rdf = self . _build_rdf ( ) # if NonRDF, empty binary data if type ( self ) == NonRDFSource : self . binary . empty ( ) | small method to empty values if resource is removed or absent | 75 | 11 |
12,465 | def add_triple ( self , p , o , auto_refresh = True ) : self . rdf . graph . add ( ( self . uri , p , self . _handle_object ( o ) ) ) # determine if triples refreshed self . _handle_triple_refresh ( auto_refresh ) | add triple by providing p o assumes s = subject | 70 | 10 |
12,466 | def set_triple ( self , p , o , auto_refresh = True ) : self . rdf . graph . set ( ( self . uri , p , self . _handle_object ( o ) ) ) # determine if triples refreshed self . _handle_triple_refresh ( auto_refresh ) | Assuming the predicate or object matches a single triple sets the other for that triple . | 70 | 16 |
12,467 | def remove_triple ( self , p , o , auto_refresh = True ) : self . rdf . graph . remove ( ( self . uri , p , self . _handle_object ( o ) ) ) # determine if triples refreshed self . _handle_triple_refresh ( auto_refresh ) | remove triple by supplying p o | 70 | 6 |
12,468 | def _handle_triple_refresh ( self , auto_refresh ) : # if auto_refresh set, and True, refresh if auto_refresh : self . parse_object_like_triples ( ) # else, if auto_refresh is not set (None), check repository instance default elif auto_refresh == None : if self . repo . default_auto_refresh : self . parse_object_like_triples ( ) | method to refresh self . rdf . triples if auto_refresh or defaults set to True | 99 | 20 |
12,469 | def update ( self , sparql_query_only = False , auto_refresh = None , update_binary = True ) : # run diff on graphs, send as PATCH request self . _diff_graph ( ) sq = SparqlUpdate ( self . rdf . prefixes , self . rdf . diffs ) if sparql_query_only : return sq . build_query ( ) response = self . repo . api . http_request ( 'PATCH' , '%s/fcr:metadata' % self . uri , # send RDF updates to URI/fcr:metadata data = sq . build_query ( ) , headers = { 'Content-Type' : 'application/sparql-update' } ) # if RDF update not 204, raise Exception if response . status_code != 204 : logger . debug ( response . content ) raise Exception ( 'HTTP %s, expecting 204' % response . status_code ) # if NonRDFSource, and self.binary.data is not a Response object, update binary as well if type ( self ) == NonRDFSource and update_binary and type ( self . binary . data ) != requests . models . Response : self . binary . _prep_binary ( ) binary_data = self . binary . data binary_response = self . repo . api . http_request ( 'PUT' , self . uri , data = binary_data , headers = { 'Content-Type' : self . binary . mimetype } ) # if not refreshing RDF, still update binary here if not auto_refresh and not self . repo . default_auto_refresh : logger . debug ( "not refreshing resource RDF, but updated binary, so must refresh binary data" ) updated_self = self . repo . get_resource ( self . uri ) self . binary . refresh ( updated_self ) # fire optional post-update hook if hasattr ( self , '_post_update' ) : self . _post_update ( ) # determine refreshing ''' If not updating binary, pass that bool to refresh as refresh_binary flag to avoid touching binary data ''' if auto_refresh : self . refresh ( refresh_binary = update_binary ) elif auto_refresh == None : if self . repo . default_auto_refresh : self . refresh ( refresh_binary = update_binary ) return True | Method to update resources in repository . Firing this method computes the difference in the local modified graph and the original one creates an instance of SparqlUpdate and builds a sparql query that represents these differences and sends this as a PATCH request . | 512 | 51 |
12,470 | def children ( self , as_resources = False ) : children = [ o for s , p , o in self . rdf . graph . triples ( ( None , self . rdf . prefixes . ldp . contains , None ) ) ] # if as_resources, issue GET requests for children and return if as_resources : logger . debug ( 'retrieving children as resources' ) children = [ self . repo . get_resource ( child ) for child in children ] return children | method to return hierarchical children of this resource | 103 | 8 |
12,471 | def parents ( self , as_resources = False ) : parents = [ o for s , p , o in self . rdf . graph . triples ( ( None , self . rdf . prefixes . fedora . hasParent , None ) ) ] # if as_resources, issue GET requests for children and return if as_resources : logger . debug ( 'retrieving parent as resource' ) parents = [ self . repo . get_resource ( parent ) for parent in parents ] return parents | method to return hierarchical parents of this resource | 104 | 8 |
12,472 | def siblings ( self , as_resources = False ) : siblings = set ( ) # loop through parents and get children for parent in self . parents ( as_resources = True ) : for sibling in parent . children ( as_resources = as_resources ) : siblings . add ( sibling ) # remove self if as_resources : siblings . remove ( self ) if not as_resources : siblings . remove ( self . uri ) return list ( siblings ) | method to return hierarchical siblings of this resource . | 94 | 9 |
12,473 | def create_version ( self , version_label ) : # create version version_response = self . repo . api . http_request ( 'POST' , '%s/fcr:versions' % self . uri , data = None , headers = { 'Slug' : version_label } ) # if 201, assume success if version_response . status_code == 201 : logger . debug ( 'version created: %s' % version_response . headers [ 'Location' ] ) # affix version self . _affix_version ( version_response . headers [ 'Location' ] , version_label ) | method to create a new version of the resource as it currently stands | 132 | 13 |
12,474 | def get_versions ( self ) : # get all versions versions_response = self . repo . api . http_request ( 'GET' , '%s/fcr:versions' % self . uri ) # parse response versions_graph = self . repo . api . parse_rdf_payload ( versions_response . content , versions_response . headers ) # loop through fedora.hasVersion for version_uri in versions_graph . objects ( self . uri , self . rdf . prefixes . fedora . hasVersion ) : # get label version_label = versions_graph . value ( version_uri , self . rdf . prefixes . fedora . hasVersionLabel , None ) . toPython ( ) # affix version self . _affix_version ( version_uri , version_label ) | retrieves all versions of an object and stores them at self . versions | 176 | 15 |
12,475 | def dump ( self , format = 'ttl' ) : return self . rdf . graph . serialize ( format = format ) . decode ( 'utf-8' ) | Convenience method to return RDF data for resource optionally selecting serialization format . Inspired by . dump from Samvera . | 37 | 26 |
12,476 | def revert_to ( self ) : # send patch response = self . resource . repo . api . http_request ( 'PATCH' , self . uri ) # if response 204 if response . status_code == 204 : logger . debug ( 'reverting to previous version of resource, %s' % self . uri ) # refresh current resource handle self . _current_resource . refresh ( ) else : raise Exception ( 'HTTP %s, could not revert to resource version, %s' % ( response . status_code , self . uri ) ) | method to revert resource to this version by issuing PATCH | 119 | 11 |
12,477 | def delete ( self ) : # send patch response = self . resource . repo . api . http_request ( 'DELETE' , self . uri ) # if response 204 if response . status_code == 204 : logger . debug ( 'deleting previous version of resource, %s' % self . uri ) # remove from resource versions delattr ( self . _current_resource . versions , self . label ) # if 400, likely most recent version and cannot remove elif response . status_code == 400 : raise Exception ( 'HTTP 400, likely most recent resource version which cannot be removed' ) else : raise Exception ( 'HTTP %s, could not delete resource version: %s' % ( response . status_code , self . uri ) ) | method to remove version from resource s history | 162 | 8 |
12,478 | def empty ( self ) : self . resource = None self . delivery = None self . data = None self . stream = False self . mimetype = None self . location = None | Method to empty attributes particularly for use when object is deleted but remains as variable | 38 | 15 |
12,479 | def refresh ( self , updated_self ) : logger . debug ( 'refreshing binary attributes' ) self . mimetype = updated_self . binary . mimetype self . data = updated_self . binary . data | method to refresh binary attributes and data | 48 | 7 |
12,480 | def parse_binary ( self ) : # derive mimetype self . mimetype = self . resource . rdf . graph . value ( self . resource . uri , self . resource . rdf . prefixes . ebucore . hasMimeType ) . toPython ( ) # get binary content as stremable response self . data = self . resource . repo . api . http_request ( 'GET' , self . resource . uri , data = None , headers = { 'Content-Type' : self . resource . mimetype } , is_rdf = False , stream = True ) | when retrieving a NonRDF resource parse binary data and make available via generators | 129 | 15 |
12,481 | def _prep_binary_content ( self ) : # nothing present if not self . data and not self . location and 'Content-Location' not in self . resource . headers . keys ( ) : raise Exception ( 'creating/updating NonRDFSource requires content from self.binary.data, self.binary.location, or the Content-Location header' ) elif 'Content-Location' in self . resource . headers . keys ( ) : logger . debug ( 'Content-Location header found, using' ) self . delivery = 'header' # if Content-Location is not set, look for self.data_location then self.data elif 'Content-Location' not in self . resource . headers . keys ( ) : # data_location set, trumps Content self.data if self . location : # set appropriate header self . resource . headers [ 'Content-Location' ] = self . location self . delivery = 'header' # data attribute is plain text, binary, or file-like object elif self . data : # if file-like object, set flag for api.http_request if isinstance ( self . data , io . BufferedIOBase ) : logger . debug ( 'detected file-like object' ) self . delivery = 'payload' # else, just bytes else : logger . debug ( 'detected bytes' ) self . delivery = 'payload' | Sets delivery method of either payload or header Favors Content - Location header if set | 297 | 17 |
12,482 | def fixity ( self , response_format = None ) : # if no response_format, use default if not response_format : response_format = self . repo . default_serialization # issue GET request for fixity check response = self . repo . api . http_request ( 'GET' , '%s/fcr:fixity' % self . uri ) # parse fixity_graph = self . repo . api . parse_rdf_payload ( response . content , response . headers ) # determine verdict for outcome in fixity_graph . objects ( None , self . rdf . prefixes . premis . hasEventOutcome ) : if outcome . toPython ( ) == 'SUCCESS' : verdict = True else : verdict = False return { 'verdict' : verdict , 'premis_graph' : fixity_graph } | Issues fixity check return parsed graph | 184 | 8 |
12,483 | def get_value ( self , consumer = None ) : if consumer : self . consumers [ consumer ] = True return self . value | If consumer is specified the channel will record that consumer as having consumed the value . | 27 | 16 |
12,484 | def set_input_data ( self , key , value ) : if not key in self . input_channels . keys ( ) : self . set_input_channel ( key , Channel ( ) ) self . input_channels [ key ] . set_value ( Data ( self . time , value ) ) | set_input_data will automatically create an input channel if necessary . Automatic channel creation is intended for the case where users are trying to set initial values on a block whose input channels aren t subscribed to anything in the graph . | 66 | 45 |
12,485 | def get_output_channel ( self , output_channel_name ) : if not output_channel_name in self . output_channels . keys ( ) : self . output_channels [ output_channel_name ] = Channel ( ) self . output_channels [ output_channel_name ] . add_producer ( self ) return self . output_channels [ output_channel_name ] | get_output_channel will create a new channel object if necessary . | 87 | 14 |
12,486 | def by_bounding_box ( self , tl_lat , tl_long , br_lat , br_long , term = None , num_biz_requested = None , category = None ) : header , content = self . _http_request ( self . BASE_URL , tl_lat = tl_lat , tl_long = tl_long , br_lat = br_lat , br_long = br_long , term = term , category = category , num_biz_requested = num_biz_requested ) return json . loads ( content ) | Perform a Yelp Review Search based on a map bounding box . | 128 | 14 |
12,487 | def by_geopoint ( self , lat , long , radius , term = None , num_biz_requested = None , category = None ) : header , content = self . _http_request ( self . BASE_URL , lat = lat , long = long , radius = radius , term = None , num_biz_requested = None ) return json . loads ( content ) | Perform a Yelp Review Search based on a geopoint and radius tuple . | 82 | 15 |
12,488 | def by_location ( self , location , cc = None , radius = None , term = None , num_biz_requested = None , category = None ) : header , content = self . _http_request ( self . BASE_URL , location = location , cc = cc , radius = radius , term = term , num_biz_requested = num_biz_requested ) return json . loads ( content ) | Perform a Yelp Review Search based on a location specifier . | 89 | 13 |
12,489 | def by_phone ( self , phone , cc = None ) : header , content = self . _http_request ( self . BASE_URL , phone = phone , cc = cc ) return json . loads ( content ) | Perform a Yelp Phone API Search based on phone number given . | 46 | 13 |
12,490 | def by_geopoint ( self , lat , long ) : header , content = self . _http_request ( self . BASE_URL , lat = lat , long = long ) return json . loads ( content ) | Perform a Yelp Neighborhood API Search based on a geopoint . | 46 | 13 |
12,491 | def by_location ( self , location , cc = None ) : header , content = self . _http_request ( self . BASE_URL , location = location , cc = cc ) return json . loads ( content ) | Perform a Yelp Neighborhood API Search based on a location specifier . | 46 | 14 |
12,492 | def check_transport_host ( self ) : sock = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) result = sock . connect_ex ( ( 'events-server' , 8080 ) ) if result == 0 : logging . info ( 'port 8080 on zmq is open!' ) return True return False | Check if zeromq socket is available on transport host | 76 | 12 |
12,493 | def sample ( config , samples ) : url = get_api_path ( 'sample.json' ) multiple_files = [ ] images = [ s [ 'image' ] for s in samples ] labels = [ s [ 'label' ] for s in samples ] for image in images : multiple_files . append ( ( 'images' , ( image , open ( image , 'rb' ) , 'image/png' ) ) ) headers = get_headers ( no_content_type = True ) headers [ "config" ] = json . dumps ( config , cls = HCEncoder ) headers [ "labels" ] = json . dumps ( labels ) print ( "With headers" , headers ) try : r = requests . post ( url , files = multiple_files , headers = headers , timeout = 30 ) return r . text except requests . exceptions . RequestException : e = sys . exc_info ( ) [ 0 ] print ( "Error while calling hyperchamber - " , e ) return None | Upload a series of samples . Each sample has keys image and label . Images are ignored if the rate limit is hit . | 213 | 24 |
12,494 | def measure ( config , result , max_retries = 10 ) : url = get_api_path ( 'measurement.json' ) data = { 'config' : config , 'result' : result } retries = 0 while ( retries < max_retries ) : try : r = requests . post ( url , data = json . dumps ( data , cls = HCEncoder ) , headers = get_headers ( ) , timeout = 30 ) return r . text except requests . exceptions . RequestException : e = sys . exc_info ( ) [ 0 ] print ( "Error while calling hyperchamber - retrying " , e ) retries += 1 | Records results on hyperchamber . io . Used when you are done testing a config . | 143 | 19 |
12,495 | def move_selection ( reverse = False ) : global selected_pid if selected_pid not in gunicorns : selected_pid = None found = False pids = sorted ( gunicorns . keys ( ) , reverse = reverse ) # Iterate items twice to enable wrapping. for pid in pids + pids : if selected_pid is None or found : selected_pid = pid return found = pid == selected_pid | Goes through the list of gunicorns setting the selected as the one after the currently selected . | 89 | 20 |
12,496 | def update_gunicorns ( ) : global tick tick += 1 if ( tick * screen_delay ) % ps_delay != 0 : return tick = 0 for pid in gunicorns : gunicorns [ pid ] . update ( { "workers" : 0 , "mem" : 0 } ) ps = Popen ( PS_ARGS , stdout = PIPE ) . communicate ( ) [ 0 ] . split ( "\n" ) headings = ps . pop ( 0 ) . split ( ) name_col = headings . index ( cmd_heading ) num_cols = len ( headings ) - 1 for row in ps : cols = row . split ( None , num_cols ) if cols and "gunicorn: " in cols [ name_col ] : if "gunicorn: worker" in cols [ name_col ] : is_worker = True else : is_worker = False if is_worker : pid = cols [ headings . index ( "PPID" ) ] else : pid = cols [ headings . index ( "PID" ) ] if pid not in gunicorns : gunicorns [ pid ] = { "workers" : 0 , "mem" : 0 , "port" : None , "name" : cols [ name_col ] . strip ( ) . split ( "[" , 1 ) [ 1 ] . split ( "]" , 1 ) [ : - 1 ] } gunicorns [ pid ] [ "mem" ] += int ( cols [ headings . index ( "RSS" ) ] ) if is_worker : gunicorns [ pid ] [ "workers" ] += 1 # Remove gunicorns that were not found in the process list. for pid in gunicorns . keys ( ) [ : ] : if gunicorns [ pid ] [ "workers" ] == 0 : del gunicorns [ pid ] # Determine ports if any are missing. if not [ g for g in gunicorns . values ( ) if g [ "port" ] is None ] : return for ( pid , port ) in ports_for_pids ( gunicorns . keys ( ) ) : if pid in gunicorns : gunicorns [ pid ] [ "port" ] = port | Updates the dict of gunicorn processes . Run the ps command and parse its output for processes named after gunicorn building up a dict of gunicorn processes . When new gunicorns are discovered run the netstat command to determine the ports they re serving on . | 487 | 56 |
12,497 | def handle_keypress ( screen ) : global selected_pid try : key = screen . getkey ( ) . upper ( ) except : return if key in ( "KEY_DOWN" , "J" ) : move_selection ( ) elif key in ( "KEY_UP" , "K" ) : move_selection ( reverse = True ) elif key in ( "A" , "+" ) : send_signal ( "TTIN" ) if selected_pid in gunicorns : gunicorns [ selected_pid ] [ "workers" ] = 0 elif key in ( "W" , "-" ) : if selected_pid in gunicorns : if gunicorns [ selected_pid ] [ "workers" ] != 1 : send_signal ( "TTOU" ) gunicorns [ selected_pid ] [ "workers" ] = 0 elif key in ( "R" , ) : if selected_pid in gunicorns : send_signal ( "HUP" ) del gunicorns [ selected_pid ] selected_pid = None elif key in ( "T" , ) : for pid in gunicorns . copy ( ) . iterkeys ( ) : selected_pid = pid send_signal ( "HUP" ) del gunicorns [ selected_pid ] selected_pid = None elif key in ( "M" , "-" ) : if selected_pid in gunicorns : send_signal ( "QUIT" ) del gunicorns [ selected_pid ] selected_pid = None elif key in ( "Q" , ) : raise KeyboardInterrupt | Check for a key being pressed and handle it if applicable . | 346 | 12 |
12,498 | def format_row ( pid = "" , port = "" , name = "" , mem = "" , workers = "" , prefix_char = " " ) : row = "%s%-5s %-6s %-25s %8s %7s " % ( prefix_char , pid , port , name , mem , workers ) global screen_width if screen_width is None : screen_width = len ( row ) return row | Applies consistant padding to each of the columns in a row and serves as the source of the overall screen width . | 92 | 24 |
12,499 | def display_output ( screen ) : format_row ( ) # Sets up the screen width. screen_height = len ( gunicorns ) + len ( instructions . split ( "\n" ) ) + 9 if not gunicorns : screen_height += 2 # A couple of blank lines are added when empty. screen . erase ( ) win = curses . newwin ( screen_height , screen_width + 6 , 1 , 3 ) win . bkgd ( " " , curses . color_pair ( 1 ) ) win . border ( ) x = 3 blank_line = y = count ( 2 ) . next win . addstr ( y ( ) , x , title . center ( screen_width ) , curses . A_NORMAL ) blank_line ( ) win . addstr ( y ( ) , x , format_row ( " PID" , "PORT" , "NAME" , "MEM (MB)" , "WORKERS" ) , curses . A_STANDOUT ) if not gunicorns : blank_line ( ) win . addstr ( y ( ) , x , no_gunicorns . center ( screen_width ) , curses . A_NORMAL ) blank_line ( ) else : win . hline ( y ( ) , x , curses . ACS_HLINE , screen_width ) for ( i , pid ) in enumerate ( sorted ( gunicorns . keys ( ) ) ) : port = gunicorns [ pid ] [ "port" ] name = gunicorns [ pid ] [ "name" ] mem = "%#.3f" % ( gunicorns [ pid ] [ "mem" ] / 1000. ) workers = gunicorns [ pid ] [ "workers" ] # When a signal is sent to update the number of workers, the number # of workers is set to zero as a marker to signify an update has # occurred. We then piggyback this variable and use it as a counter # to animate the display until the gunicorn is next updated. if workers < 1 : gunicorns [ pid ] [ "workers" ] -= 1 chars = "|/-\\" workers *= - 1 if workers == len ( chars ) : gunicorns [ pid ] [ "workers" ] = workers = 0 workers = chars [ workers ] if pid == selected_pid : attr = curses . A_STANDOUT prefix_char = '> ' else : attr = curses . A_NORMAL prefix_char = ' ' win . addstr ( y ( ) , x , format_row ( pid , port , name , mem , workers , prefix_char ) , attr ) win . hline ( y ( ) , x , curses . ACS_HLINE , screen_width ) blank_line ( ) for line in instructions . split ( "\n" ) : win . addstr ( y ( ) , x , line . center ( screen_width ) , curses . A_NORMAL ) win . refresh ( ) | Display the menu list of gunicorns . | 631 | 9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.