text
stringlengths
81
112k
Handle a few expected values for rendering the current choice. Extracts the state name from StateWrapper and State object. def render(self, name, value, attrs=None, *args, **kwargs): """Handle a few expected values for rendering the current choice. Extracts the state name from StateWrapper an...
Contribute the state to a Model. Attaches a StateFieldProperty to wrap the attribute. def contribute_to_class(self, cls, name): """Contribute the state to a Model. Attaches a StateFieldProperty to wrap the attribute. """ super(StateField, self).contribute_to_class(cls, name) ...
Converts the DB-stored value into a Python value. def to_python(self, value): """Converts the DB-stored value into a Python value.""" if isinstance(value, base.StateWrapper): res = value else: if isinstance(value, base.State): state = value el...
Convert a value to DB storage. Returns the state name. def get_db_prep_value(self, value, connection, prepared=False): """Convert a value to DB storage. Returns the state name. """ if not prepared: value = self.get_prep_value(value) return value.state.name
Convert a field value to a string. Returns the state name. def value_to_string(self, obj): """Convert a field value to a string. Returns the state name. """ statefield = self.to_python(self.value_from_object(obj)) return statefield.state.name
Validate that a given value is a valid option for a given model instance. Args: value (xworkflows.base.StateWrapper): The base.StateWrapper returned by to_python. model_instance: A WorkflowEnabled instance def validate(self, value, model_instance): """Validate that a given valu...
Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django doesn't like deconstructing metaclass-built classes. def deconstruct(self): """Deconstruction for migrations. Return a simpler object (_Serial...
Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects. def _find_workflows(mcs, attrs): """Find workflow definition(s) in a WorkflowEnabled definition. This method overrides...
Cache for fetching the actual log model object once django is loaded. Otherwise, import conflict occur: WorkflowEnabled imports <log_model> which tries to import all models to retrieve the proper model class. def _get_log_model_class(self): """Cache for fetching the actual log model object onc...
Logs the transition into the database. def db_log(self, transition, from_state, instance, *args, **kwargs): """Logs the transition into the database.""" if self.log_model: model_class = self._get_log_model_class() extras = {} for db_field, transition_arg, default in...
Generic transition logging. def log_transition(self, transition, from_state, instance, *args, **kwargs): """Generic transition logging.""" save = kwargs.pop('save', True) log = kwargs.pop('log', True) super(Workflow, self).log_transition( transition, from_state, instance, *a...
Cleanup README.rst for proper PyPI formatting. def clean_readme(fname): """Cleanup README.rst for proper PyPI formatting.""" with codecs.open(fname, 'r', 'utf-8') as f: return ''.join( re.sub(r':\w+:`([^`]+?)( <[^<>]+>)?`', r'``\1``', line) for line in f if not (line...
Return a gallery image/album depending on what the json represent. def _get_album_or_image(json, imgur): """Return a gallery image/album depending on what the json represent.""" if json['is_album']: return Gallery_album(json, imgur, has_fetched=False) return Gallery_image(json, imgur)
Refresh this objects attributes to the newest values. Attributes that weren't added to the object before, due to lazy loading, will be added by calling refresh. def refresh(self): """ Refresh this objects attributes to the newest values. Attributes that weren't added to the ob...
Add images to the album. :param images: A list of the images we want to add to the album. Can be Image objects, ids or a combination of the two. Images that you cannot add (non-existing or not owned by you) will not cause exceptions, but fail silently. def add_images(self,...
Remove images from the album. :param images: A list of the images we want to remove from the album. Can be Image objects, ids or a combination of the two. Images that you cannot remove (non-existing, not owned by you or not part of album) will not cause exceptions, but fail ...
Set the images in this album. :param images: A list of the images we want the album to contain. Can be Image objects, ids or a combination of the two. Images that images that you cannot set (non-existing or not owned by you) will not cause exceptions, but fail silently. def...
Add this to the gallery. Require that the authenticated user has accepted gallery terms and verified their email. :param title: The title of the new gallery item. :param bypass_terms: If the user has not accepted Imgur's terms yet, this method will return an error. Set this...
Update the album's information. Arguments with the value None will retain their old values. :param title: The title of the album. :param description: A description of the album. :param images: A list of the images we want the album to contain. Can be Image objects, ids or a...
Get the replies to this comment. def get_replies(self): """Get the replies to this comment.""" url = self._imgur._base_url + "/3/comment/{0}/replies".format(self.id) json = self._imgur._send_request(url) child_comments = json['children'] return [Comment(com, self._imgur) for com...
Make a top-level comment to this. :param text: The comment text. def comment(self, text): """ Make a top-level comment to this. :param text: The comment text. """ url = self._imgur._base_url + "/3/comment" payload = {'image_id': self.id, 'comment': text} ...
Dislike this. A downvote will replace a neutral vote or an upvote. Downvoting something the authenticated user has already downvoted will set the vote to neutral. def downvote(self): """ Dislike this. A downvote will replace a neutral vote or an upvote. Downvoting ...
Get a list of the top-level comments. def get_comments(self): """Get a list of the top-level comments.""" url = self._imgur._base_url + "/3/gallery/{0}/comments".format(self.id) resp = self._imgur._send_request(url) return [Comment(com, self._imgur) for com in resp]
Remove this image from the gallery. def remove_from_gallery(self): """Remove this image from the gallery.""" url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) self._imgur._send_request(url, needs_auth=True, method='DELETE') if isinstance(self, Image): item = sel...
Download the image. :param path: The image will be downloaded to the folder specified at path, if path is None (default) then the current working directory will be used. :param name: The name the image will be stored as (not including file extension). If name is None...
Update the image with a new title and/or description. def update(self, title=None, description=None): """Update the image with a new title and/or description.""" url = (self._imgur._base_url + "/3/image/" "{0}".format(self._delete_or_id_hash)) is_updated = self._imgur._send_reque...
Handles top level functionality for sending requests to Imgur. This mean - Raising client-side error if insufficient authentication. - Adding authentication information to the request. - Split the request into multiple request for pagination. - Retry calls for ce...
Return the authorization url that's needed to authorize as a user. :param response: Can be either code or pin. If it's code the user will be redirected to your redirect url with the code as a get parameter after authorizing your application. If it's pin then after authorizin...
Change the current authentication. def change_authentication(self, client_id=None, client_secret=None, access_token=None, refresh_token=None): """Change the current authentication.""" # TODO: Add error checking so you cannot change client_id and retain # access_tok...
Create a new Album. :param title: The title of the album. :param description: The albums description. :param images: A list of the images that will be added to the album after it's created. Can be Image objects, ids or a combination of the two. Images that you cannot a...
Exchange one-use code for an access_token and request_token. def exchange_code(self, code): """Exchange one-use code for an access_token and request_token.""" params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'authorization_cod...
Exchange one-use pin for an access_token and request_token. def exchange_pin(self, pin): """Exchange one-use pin for an access_token and request_token.""" params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'pin', ...
Return information about this album. def get_album(self, id): """Return information about this album.""" url = self._base_url + "/3/album/{0}".format(id) json = self._send_request(url) return Album(json, self)
Return a object representing the content at url. Returns None if no object could be matched with the id. Works for Album, Comment, Gallery_album, Gallery_image, Image and User. NOTE: Imgur's documentation does not cover what urls are available. Some urls, such as imgur.com/<ID> can be...
Return information about this comment. def get_comment(self, id): """Return information about this comment.""" url = self._base_url + "/3/comment/{0}".format(id) json = self._send_request(url) return Comment(json, self)
Return a list of gallery albums and gallery images. :param section: hot | top | user - defaults to hot. :param sort: viral | time - defaults to viral. :param window: Change the date range of the request if the section is "top", day | week | month | year | all, defaults to day. ...
Return the gallery album matching the id. Note that an album's id is different from it's id as a gallery album. This makes it possible to remove an album from the gallery and setting it's privacy setting as secret, without compromising it's secrecy. def get_gallery_album(self, id): """...
Return the gallery image matching the id. Note that an image's id is different from it's id as a gallery image. This makes it possible to remove an image from the gallery and setting it's privacy setting as secret, without compromising it's secrecy. def get_gallery_image(self, id): """...
Return a Image object representing the image with the given id. def get_image(self, id): """Return a Image object representing the image with the given id.""" url = self._base_url + "/3/image/{0}".format(id) resp = self._send_request(url) return Image(resp, self)
Return a Message object for given id. :param id: The id of the message object to return. def get_message(self, id): """ Return a Message object for given id. :param id: The id of the message object to return. """ url = self._base_url + "/3/message/{0}".format(id) ...
Return a Notification object. :param id: The id of the notification object to return. def get_notification(self, id): """ Return a Notification object. :param id: The id of the notification object to return. """ url = self._base_url + "/3/notification/{0}".format(id) ...
Return a list of gallery albums/images submitted to the memes gallery The url for the memes gallery is: http://imgur.com/g/memes :param sort: viral | time | top - defaults to viral :param window: Change the date range of the request if the section is "top", day | week | month | yea...
Return a list of gallery albums/images submitted to a subreddit. A subreddit is a subsection of the website www.reddit.com, where users can, among other things, post images. :param subreddit: A valid subreddit name. :param sort: time | top - defaults to top. :param window: Chan...
Return the Gallery_image with the id submitted to subreddit gallery :param subreddit: The subreddit the image has been submitted to. :param id: The id of the image we want. def get_subreddit_image(self, subreddit, id): """ Return the Gallery_image with the id submitted to subreddit gal...
Return a User object for this username. :param username: The name of the user we want more information about. def get_user(self, username): """ Return a User object for this username. :param username: The name of the user we want more information about. """ url = self....
Refresh the access_token. The self.access_token attribute will be updated with the value of the new access_token which will also be returned. def refresh_access_token(self): """ Refresh the access_token. The self.access_token attribute will be updated with the value of the ...
Search the gallery with the given query string. def search_gallery(self, q): """Search the gallery with the given query string.""" url = self._base_url + "/3/gallery/search?q={0}".format(q) resp = self._send_request(url) return [_get_album_or_image(thing, self) for thing in resp]
Upload the image at either path or url. :param path: The path to the image you want to upload. :param url: The url to the image you want to upload. :param title: The title the image will have when uploaded. :param description: The description the image will have when uploaded. :...
Delete the message. def delete(self): """Delete the message.""" url = self._imgur._base_url + "/3/message/{0}".format(self.id) return self._imgur._send_request(url, method='DELETE')
Return the message thread this Message is in. def get_thread(self): """Return the message thread this Message is in.""" url = (self._imgur._base_url + "/3/message/{0}/thread".format( self.first_message.id)) resp = self._imgur._send_request(url) return [Message(msg, self._...
Reply to this message. This is a convenience method calling User.send_message. See it for more information on usage. Note that both recipient and reply_to are given by using this convenience method. :param body: The body of the message. def reply(self, body): """ Reply...
Update the settings for the user. :param bio: A basic description filled out by the user, is displayed in the gallery profile page. :param public_images: Set the default privacy setting of the users images. If True images are public, if False private. :param messaging_en...
Return a list of the user's albums. Secret and hidden albums are only returned if this is the logged-in user. def get_albums(self, limit=None): """ Return a list of the user's albums. Secret and hidden albums are only returned if this is the logged-in user. "...
Return the users favorited images. def get_favorites(self): """Return the users favorited images.""" url = self._imgur._base_url + "/3/account/{0}/favorites".format(self.name) resp = self._imgur._send_request(url, needs_auth=True) return [_get_album_or_image(thing, self._imgur) for thin...
Get a list of the images in the gallery this user has favorited. def get_gallery_favorites(self): """Get a list of the images in the gallery this user has favorited.""" url = (self._imgur._base_url + "/3/account/{0}/gallery_favorites".format( self.name)) resp = self._imgur._send_...
Return the users gallery profile. def get_gallery_profile(self): """Return the users gallery profile.""" url = (self._imgur._base_url + "/3/account/{0}/" "gallery_profile".format(self.name)) return self._imgur._send_request(url)
Has the user verified that the email he has given is legit? Verified e-mail is required to the gallery. Confirmation happens by sending an email to the user and the owner of the email user verifying that he is the same as the Imgur user. def has_verified_email(self): """ Has th...
Return all of the images associated with the user. def get_images(self, limit=None): """Return all of the images associated with the user.""" url = (self._imgur._base_url + "/3/account/{0}/" "images/{1}".format(self.name, '{}')) resp = self._imgur._send_request(url, limit=limit) ...
Return all messages sent to this user, formatted as a notification. :param new: False for all notifications, True for only non-viewed notifications. def get_messages(self, new=True): """ Return all messages sent to this user, formatted as a notification. :param new: False ...
Return all the notifications for this user. def get_notifications(self, new=True): """Return all the notifications for this user.""" url = (self._imgur._base_url + "/3/account/{0}/" "notifications".format(self.name)) resp = self._imgur._send_request(url, params=locals(), needs_au...
Return all reply notifications for this user. :param new: False for all notifications, True for only non-viewed notifications. def get_replies(self, new=True): """ Return all reply notifications for this user. :param new: False for all notifications, True for only non-view...
Returns current settings. Only accessible if authenticated as the user. def get_settings(self): """ Returns current settings. Only accessible if authenticated as the user. """ url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name) return self...
Return a list of the images a user has submitted to the gallery. def get_submissions(self, limit=None): """Return a list of the images a user has submitted to the gallery.""" url = (self._imgur._base_url + "/3/account/{0}/submissions/" "{1}".format(self.name, '{}')) resp = self._...
Send a message to this user from the logged in user. :param body: The body of the message. :param subject: The subject of the message. Note that if the this message is a reply, then the subject of the first message will be used instead. :param reply_to: Messages can eith...
Send verification email to this users email address. Remember that the verification email may end up in the users spam folder. def send_verification_email(self): """ Send verification email to this users email address. Remember that the verification email may end up in the use...
Hook the current excepthook to the backtrace. If `align` is True, all parts (line numbers, file names, etc..) will be aligned to the left according to the longest entry. If `strip_path` is True, only the file name will be shown, not its full path. If `enable_on_envvar_only` is True, only if the e...
Receive a list of strings representing the input from stdin and return the restructured backtrace. This iterates over the output and once it identifies a hopefully genuine identifier, it will start parsing output. In the case the input includes a reraise (a Python 3 case), the primary traceback isn...
Return the (potentially) aligned, rebuit traceback Yes, we iterate over the entries thrice. We sacrifice performance for code readability. I mean.. come on, how long can your traceback be that it matters? def generate_backtrace(self, styles): """Return the (potentially) aligned, rebuit...
Look at a list of sources and split them according to their class. Parameters ---------- catalog : iterable A list or iterable object of {SimpleSource, IslandSource, OutputSource} objects, possibly mixed. Any other objects will be silently ignored. Returns ------- components : ...
Iterate over a catalog of sources, and return an island worth of sources at a time. Yields a list of components, one island at a time Parameters ---------- catalog : iterable A list or iterable of :class:`AegeanTools.models.OutputSource` objects. Yields ------ group : list ...
Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly. def _sanitise(self): """ Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly. """ for k in self.__dict__: if isinstance(self.__dict__[k], np.f...
Return an *ordered* list of the source attributes def as_list(self): """ Return an *ordered* list of the source attributes """ self._sanitise() l = [] for name in self.names: l.append(getattr(self, name)) return l
Add one or more circles to this region Parameters ---------- ra_cen, dec_cen, radius : float or list The center and radius of the circle or circles to add to this region. depth : int The depth at which the given circles will be inserted. def add_circles(self, r...
Add a single polygon to this region. Parameters ---------- positions : [[ra, dec], ...] Positions for the vertices of the polygon. The polygon needs to be convex and non-intersecting. depth : int The deepth at which the polygon will be inserted. def add_poly(se...
Add one or more HEALPix pixels to this region. Parameters ---------- pix : int or iterable The pixels to be added depth : int The depth at which the pixels are added. def add_pixels(self, pix, depth): """ Add one or more HEALPix pixels to this r...
Calculate the total area represented by this region. Parameters ---------- degrees : bool If True then return the area in square degrees, otherwise use steradians. Default = True. Returns ------- area : float The area of the region. ...
Convert the multi-depth pixeldict into a single set of pixels at the deepest layer. The result is cached, and reset when any changes are made to this region. def _demote_all(self): """ Convert the multi-depth pixeldict into a single set of pixels at the deepest layer. The result is ca...
Remake the pixel dictionary, merging groups of pixels at level N into a single pixel at level N-1 def _renorm(self): """ Remake the pixel dictionary, merging groups of pixels at level N into a single pixel at level N-1 """ self.demoted = set() # convert all to lo...
Test whether a sky position is within this region Parameters ---------- ra, dec : float Sky position. degin : bool If True the ra/dec is interpreted as degrees, otherwise as radians. Default = False. Returns ------- within : ...
Add another Region by performing union on their pixlists. Parameters ---------- other : :class:`AegeanTools.regions.Region` The region to be combined. renorm : bool Perform renormalisation after the operation? Default = True. def union(self, other, ...
Subtract another Region by performing a difference operation on their pixlists. Requires both regions to have the same maxdepth. Parameters ---------- other : :class:`AegeanTools.regions.Region` The region to be combined. def without(self, other): """ Subtr...
Combine with another Region by performing intersection on their pixlists. Requires both regions to have the same maxdepth. Parameters ---------- other : :class:`AegeanTools.regions.Region` The region to be combined. def intersect(self, other): """ Combine w...
Combine with another Region by performing the symmetric difference of their pixlists. Requires both regions to have the same maxdepth. Parameters ---------- other : :class:`AegeanTools.regions.Region` The region to be combined. def symmetric_difference(self, other): ...
Write a ds9 region file that represents this region as a set of diamonds. Parameters ---------- filename : str File to write def write_reg(self, filename): """ Write a ds9 region file that represents this region as a set of diamonds. Parameters ----...
Write a fits file representing the MOC of this region. Parameters ---------- filename : str File to write moctool : str String to be written to fits header with key "MOCTOOL". Default = '' def write_fits(self, filename, moctool=''): """ ...
Create a list of all the pixels that cover this region. This list contains overlapping pixels of different orders. Returns ------- pix : list A list of HEALPix pixel numbers. def _uniq(self): """ Create a list of all the pixels that cover this region. ...
Convert [ra], [dec] to [(ra[0], dec[0]),....] and also ra,dec to [(ra,dec)] if ra/dec are not iterable Parameters ---------- ra, dec : float or iterable Sky coordinates Returns ------- sky : numpy.array array of (ra,dec) coordinates. de...
Convert ra,dec coordinates to theta,phi coordinates ra -> phi dec -> theta Parameters ---------- sky : numpy.array Array of (ra,dec) coordinates. See :func:`AegeanTools.regions.Region.radec2sky` Returns ------- theta_phi : numpy.a...
Convert sky positions in to 3d-vectors on the unit sphere. Parameters ---------- sky : numpy.array Sky coordinates as an array of (ra,dec) Returns ------- vec : numpy.array Unit vectors as an array of (x,y,z) See Also -------- ...
Convert [x,y,z] vectors into sky coordinates ra,dec Parameters ---------- vec : numpy.array Unit vectors as an array of (x,y,z) degrees Returns ------- sky : numpy.array Sky coordinates as an array of (ra,dec) See Also -...
Create a new WCSHelper class from the given header. Parameters ---------- header : `astropy.fits.HDUHeader` or string The header to be used to create the WCS helper beam : :class:`AegeanTools.fits_image.Beam` or None The synthesized beam. If the supplied beam is...
Create a new WCSHelper class from a given fits file. Parameters ---------- filename : string The file to be read beam : :class:`AegeanTools.fits_image.Beam` or None The synthesized beam. If the supplied beam is None then one is constructed form the header. ...
Convert pixel coordinates into sky coordinates. Parameters ---------- pixel : (float, float) The (x,y) pixel coordinates Returns ------- sky : (float, float) The (ra,dec) sky coordinates in degrees def pix2sky(self, pixel): """ C...
Convert sky coordinates into pixel coordinates. Parameters ---------- pos : (float, float) The (ra, dec) sky coordinates (degrees) Returns ------- pixel : (float, float) The (x,y) pixel coordinates def sky2pix(self, pos): """ Con...
Convert a vector from sky to pixel coords. The vector has a magnitude, angle, and an origin on the sky. Parameters ---------- pos : (float, float) The (ra, dec) of the origin of the vector (degrees). r : float The magnitude or length of the vector (degre...
Given and input position and vector in pixel coordinates, calculate the equivalent position and vector in sky coordinates. Parameters ---------- pixel : (int,int) origin of vector in pixel coordinates r : float magnitude of vector in pixels theta ...
Convert an ellipse from sky to pixel coordinates. Parameters ---------- pos : (float, float) The (ra, dec) of the ellipse center (degrees). a, b, pa: float The semi-major axis, semi-minor axis and position angle of the ellipse (degrees). Returns ...
Convert an ellipse from pixel to sky coordinates. Parameters ---------- pixel : (float, float) The (x, y) coordinates of the center of the ellipse. sx, sy : float The major and minor axes (FHWM) of the ellipse, in pixels. theta : float The rot...
Determine the beam in pixels at the given location in pixel coordinates. Parameters ---------- x , y : float The pixel coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` A beam object, with a/...
Determine the beam at the given sky location. Parameters ---------- ra, dec : float The sky coordinates at which the beam is determined. Returns ------- beam : :class:`AegeanTools.fits_image.Beam` A beam object, with a/b/pa in sky coordinates de...