repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
rbarrois/django_xworkflows
django_xworkflows/models.py
StateSelect.render
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 and State object. """ if isinstance(value, base.StateWrapper): state_name = value.state.name elif isinstance(value, base.State): state_name = value.name else: state_name = str(value) return super(StateSelect, self).render(name, state_name, attrs, *args, **kwargs)
python
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 and State object. """ if isinstance(value, base.StateWrapper): state_name = value.state.name elif isinstance(value, base.State): state_name = value.name else: state_name = str(value) return super(StateSelect, self).render(name, state_name, attrs, *args, **kwargs)
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "value", ",", "base", ".", "StateWrapper", ")", ":", "state_name", "=", "value", ".", ...
Handle a few expected values for rendering the current choice. Extracts the state name from StateWrapper and State object.
[ "Handle", "a", "few", "expected", "values", "for", "rendering", "the", "current", "choice", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L38-L49
train
rbarrois/django_xworkflows
django_xworkflows/models.py
StateField.contribute_to_class
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) parent_property = getattr(cls, self.name, None) setattr(cls, self.name, StateFieldProperty(self, parent_property))
python
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) parent_property = getattr(cls, self.name, None) setattr(cls, self.name, StateFieldProperty(self, parent_property))
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ")", ":", "super", "(", "StateField", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ")", "parent_property", "=", "getattr", "(", "cls", ",", "self", ".", "name",...
Contribute the state to a Model. Attaches a StateFieldProperty to wrap the attribute.
[ "Contribute", "the", "state", "to", "a", "Model", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L115-L123
train
rbarrois/django_xworkflows
django_xworkflows/models.py
StateField.to_python
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 elif value is None: state = self.workflow.initial_state else: try: state = self.workflow.states[value] except KeyError: raise exceptions.ValidationError(self.error_messages['invalid']) res = base.StateWrapper(state, self.workflow) if res.state not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid']) return res
python
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 elif value is None: state = self.workflow.initial_state else: try: state = self.workflow.states[value] except KeyError: raise exceptions.ValidationError(self.error_messages['invalid']) res = base.StateWrapper(state, self.workflow) if res.state not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid']) return res
[ "def", "to_python", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "base", ".", "StateWrapper", ")", ":", "res", "=", "value", "else", ":", "if", "isinstance", "(", "value", ",", "base", ".", "State", ")", ":", "state", ...
Converts the DB-stored value into a Python value.
[ "Converts", "the", "DB", "-", "stored", "value", "into", "a", "Python", "value", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L125-L144
train
rbarrois/django_xworkflows
django_xworkflows/models.py
StateField.get_db_prep_value
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
python
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
[ "def", "get_db_prep_value", "(", "self", ",", "value", ",", "connection", ",", "prepared", "=", "False", ")", ":", "if", "not", "prepared", ":", "value", "=", "self", ".", "get_prep_value", "(", "value", ")", "return", "value", ".", "state", ".", "name" ...
Convert a value to DB storage. Returns the state name.
[ "Convert", "a", "value", "to", "DB", "storage", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L153-L160
train
rbarrois/django_xworkflows
django_xworkflows/models.py
StateField.value_to_string
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
python
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
[ "def", "value_to_string", "(", "self", ",", "obj", ")", ":", "statefield", "=", "self", ".", "to_python", "(", "self", ".", "value_from_object", "(", "obj", ")", ")", "return", "statefield", ".", "state", ".", "name" ]
Convert a field value to a string. Returns the state name.
[ "Convert", "a", "field", "value", "to", "a", "string", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L162-L168
train
rbarrois/django_xworkflows
django_xworkflows/models.py
StateField.validate
def validate(self, value, model_instance): """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 """ if not isinstance(value, base.StateWrapper): raise exceptions.ValidationError(self.error_messages['wrong_type'] % value) elif not value.workflow == self.workflow: raise exceptions.ValidationError(self.error_messages['wrong_workflow'] % value.workflow) elif value.state not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid_state'] % value.state)
python
def validate(self, value, model_instance): """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 """ if not isinstance(value, base.StateWrapper): raise exceptions.ValidationError(self.error_messages['wrong_type'] % value) elif not value.workflow == self.workflow: raise exceptions.ValidationError(self.error_messages['wrong_workflow'] % value.workflow) elif value.state not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid_state'] % value.state)
[ "def", "validate", "(", "self", ",", "value", ",", "model_instance", ")", ":", "if", "not", "isinstance", "(", "value", ",", "base", ".", "StateWrapper", ")", ":", "raise", "exceptions", ".", "ValidationError", "(", "self", ".", "error_messages", "[", "'wr...
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
[ "Validate", "that", "a", "given", "value", "is", "a", "valid", "option", "for", "a", "given", "model", "instance", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L170-L182
train
rbarrois/django_xworkflows
django_xworkflows/models.py
StateField.deconstruct
def deconstruct(self): """Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django doesn't like deconstructing metaclass-built classes. """ name, path, args, kwargs = super(StateField, self).deconstruct() # We want to display the proper class name, which isn't available # at the same point for _SerializedWorkflow and Workflow. if isinstance(self.workflow, _SerializedWorkflow): workflow_class_name = self.workflow._name else: workflow_class_name = self.workflow.__class__.__name__ kwargs['workflow'] = _SerializedWorkflow( name=workflow_class_name, initial_state=str(self.workflow.initial_state.name), states=[str(st.name) for st in self.workflow.states], ) del kwargs['choices'] del kwargs['default'] return name, path, args, kwargs
python
def deconstruct(self): """Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django doesn't like deconstructing metaclass-built classes. """ name, path, args, kwargs = super(StateField, self).deconstruct() # We want to display the proper class name, which isn't available # at the same point for _SerializedWorkflow and Workflow. if isinstance(self.workflow, _SerializedWorkflow): workflow_class_name = self.workflow._name else: workflow_class_name = self.workflow.__class__.__name__ kwargs['workflow'] = _SerializedWorkflow( name=workflow_class_name, initial_state=str(self.workflow.initial_state.name), states=[str(st.name) for st in self.workflow.states], ) del kwargs['choices'] del kwargs['default'] return name, path, args, kwargs
[ "def", "deconstruct", "(", "self", ")", ":", "name", ",", "path", ",", "args", ",", "kwargs", "=", "super", "(", "StateField", ",", "self", ")", ".", "deconstruct", "(", ")", "# We want to display the proper class name, which isn't available", "# at the same point f...
Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django doesn't like deconstructing metaclass-built classes.
[ "Deconstruction", "for", "migrations", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L187-L210
train
rbarrois/django_xworkflows
django_xworkflows/models.py
WorkflowEnabledMeta._find_workflows
def _find_workflows(mcs, attrs): """Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects. """ workflows = {} for k, v in attrs.items(): if isinstance(v, StateField): workflows[k] = v return workflows
python
def _find_workflows(mcs, attrs): """Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects. """ workflows = {} for k, v in attrs.items(): if isinstance(v, StateField): workflows[k] = v return workflows
[ "def", "_find_workflows", "(", "mcs", ",", "attrs", ")", ":", "workflows", "=", "{", "}", "for", "k", ",", "v", "in", "attrs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "StateField", ")", ":", "workflows", "[", "k", "]", "="...
Find workflow definition(s) in a WorkflowEnabled definition. This method overrides the default behavior from xworkflows in order to use our custom StateField objects.
[ "Find", "workflow", "definition", "(", "s", ")", "in", "a", "WorkflowEnabled", "definition", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L217-L227
train
rbarrois/django_xworkflows
django_xworkflows/models.py
Workflow._get_log_model_class
def _get_log_model_class(self): """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. """ if self.log_model_class is not None: return self.log_model_class app_label, model_label = self.log_model.rsplit('.', 1) self.log_model_class = apps.get_model(app_label, model_label) return self.log_model_class
python
def _get_log_model_class(self): """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. """ if self.log_model_class is not None: return self.log_model_class app_label, model_label = self.log_model.rsplit('.', 1) self.log_model_class = apps.get_model(app_label, model_label) return self.log_model_class
[ "def", "_get_log_model_class", "(", "self", ")", ":", "if", "self", ".", "log_model_class", "is", "not", "None", ":", "return", "self", ".", "log_model_class", "app_label", ",", "model_label", "=", "self", ".", "log_model", ".", "rsplit", "(", "'.'", ",", ...
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.
[ "Cache", "for", "fetching", "the", "actual", "log", "model", "object", "once", "django", "is", "loaded", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L385-L396
train
rbarrois/django_xworkflows
django_xworkflows/models.py
Workflow.db_log
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 model_class.EXTRA_LOG_ATTRIBUTES: extras[db_field] = kwargs.get(transition_arg, default) return model_class.log_transition( modified_object=instance, transition=transition.name, from_state=from_state.name, to_state=transition.target.name, **extras)
python
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 model_class.EXTRA_LOG_ATTRIBUTES: extras[db_field] = kwargs.get(transition_arg, default) return model_class.log_transition( modified_object=instance, transition=transition.name, from_state=from_state.name, to_state=transition.target.name, **extras)
[ "def", "db_log", "(", "self", ",", "transition", ",", "from_state", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "log_model", ":", "model_class", "=", "self", ".", "_get_log_model_class", "(", ")", "extras", ...
Logs the transition into the database.
[ "Logs", "the", "transition", "into", "the", "database", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L398-L412
train
rbarrois/django_xworkflows
django_xworkflows/models.py
Workflow.log_transition
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, *args, **kwargs) if save: instance.save() if log: self.db_log(transition, from_state, instance, *args, **kwargs)
python
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, *args, **kwargs) if save: instance.save() if log: self.db_log(transition, from_state, instance, *args, **kwargs)
[ "def", "log_transition", "(", "self", ",", "transition", ",", "from_state", ",", "instance", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "save", "=", "kwargs", ".", "pop", "(", "'save'", ",", "True", ")", "log", "=", "kwargs", ".", "pop", ...
Generic transition logging.
[ "Generic", "transition", "logging", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/django_xworkflows/models.py#L414-L423
train
rbarrois/django_xworkflows
setup.py
clean_readme
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.startswith('.. currentmodule') or line.startswith('.. toctree')) )
python
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.startswith('.. currentmodule') or line.startswith('.. toctree')) )
[ "def", "clean_readme", "(", "fname", ")", ":", "with", "codecs", ".", "open", "(", "fname", ",", "'r'", ",", "'utf-8'", ")", "as", "f", ":", "return", "''", ".", "join", "(", "re", ".", "sub", "(", "r':\\w+:`([^`]+?)( <[^<>]+>)?`'", ",", "r'``\\1``'", ...
Cleanup README.rst for proper PyPI formatting.
[ "Cleanup", "README", ".", "rst", "for", "proper", "PyPI", "formatting", "." ]
7f6c3e54e7fd64d39541bffa654c7f2e28685270
https://github.com/rbarrois/django_xworkflows/blob/7f6c3e54e7fd64d39541bffa654c7f2e28685270/setup.py#L31-L38
train
Damgaard/PyImgur
pyimgur/__init__.py
_get_album_or_image
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)
python
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)
[ "def", "_get_album_or_image", "(", "json", ",", "imgur", ")", ":", "if", "json", "[", "'is_album'", "]", ":", "return", "Gallery_album", "(", "json", ",", "imgur", ",", "has_fetched", "=", "False", ")", "return", "Gallery_image", "(", "json", ",", "imgur",...
Return a gallery image/album depending on what the json represent.
[ "Return", "a", "gallery", "image", "/", "album", "depending", "on", "what", "the", "json", "represent", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L66-L70
train
Damgaard/PyImgur
pyimgur/__init__.py
Basic_object.refresh
def refresh(self): """ 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. """ resp = self._imgur._send_request(self._INFO_URL) self._populate(resp) self._has_fetched = True
python
def refresh(self): """ 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. """ resp = self._imgur._send_request(self._INFO_URL) self._populate(resp) self._has_fetched = True
[ "def", "refresh", "(", "self", ")", ":", "resp", "=", "self", ".", "_imgur", ".", "_send_request", "(", "self", ".", "_INFO_URL", ")", "self", ".", "_populate", "(", "resp", ")", "self", ".", "_has_fetched", "=", "True" ]
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.
[ "Refresh", "this", "objects", "attributes", "to", "the", "newest", "values", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L220-L229
train
Damgaard/PyImgur
pyimgur/__init__.py
Album.add_images
def add_images(self, images): """ 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. """ url = self._imgur._base_url + "/3/album/{0}/add".format(self.id) params = {'ids': images} return self._imgur._send_request(url, needs_auth=True, params=params, method="POST")
python
def add_images(self, images): """ 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. """ url = self._imgur._base_url + "/3/album/{0}/add".format(self.id) params = {'ids': images} return self._imgur._send_request(url, needs_auth=True, params=params, method="POST")
[ "def", "add_images", "(", "self", ",", "images", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/album/{0}/add\"", ".", "format", "(", "self", ".", "id", ")", "params", "=", "{", "'ids'", ":", "images", "}", "return", "self", ...
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.
[ "Add", "images", "to", "the", "album", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L265-L277
train
Damgaard/PyImgur
pyimgur/__init__.py
Album.remove_images
def remove_images(self, images): """ 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 silently. """ url = (self._imgur._base_url + "/3/album/{0}/" "remove_images".format(self._delete_or_id_hash)) # NOTE: Returns True and everything seem to be as it should in testing. # Seems most likely to be upstream bug. params = {'ids': images} return self._imgur._send_request(url, params=params, method="DELETE")
python
def remove_images(self, images): """ 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 silently. """ url = (self._imgur._base_url + "/3/album/{0}/" "remove_images".format(self._delete_or_id_hash)) # NOTE: Returns True and everything seem to be as it should in testing. # Seems most likely to be upstream bug. params = {'ids': images} return self._imgur._send_request(url, params=params, method="DELETE")
[ "def", "remove_images", "(", "self", ",", "images", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/album/{0}/\"", "\"remove_images\"", ".", "format", "(", "self", ".", "_delete_or_id_hash", ")", ")", "# NOTE: Returns True and ever...
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 silently.
[ "Remove", "images", "from", "the", "album", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L294-L308
train
Damgaard/PyImgur
pyimgur/__init__.py
Album.set_images
def set_images(self, images): """ 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. """ url = (self._imgur._base_url + "/3/album/" "{0}/".format(self._delete_or_id_hash)) params = {'ids': images} return self._imgur._send_request(url, needs_auth=True, params=params, method="POST")
python
def set_images(self, images): """ 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. """ url = (self._imgur._base_url + "/3/album/" "{0}/".format(self._delete_or_id_hash)) params = {'ids': images} return self._imgur._send_request(url, needs_auth=True, params=params, method="POST")
[ "def", "set_images", "(", "self", ",", "images", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/album/\"", "\"{0}/\"", ".", "format", "(", "self", ".", "_delete_or_id_hash", ")", ")", "params", "=", "{", "'ids'", ":", "i...
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.
[ "Set", "the", "images", "in", "this", "album", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L310-L323
train
Damgaard/PyImgur
pyimgur/__init__.py
Album.submit_to_gallery
def submit_to_gallery(self, title, bypass_terms=False): """ 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 to True to by-pass the terms. """ url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) payload = {'title': title, 'terms': '1' if bypass_terms else '0'} self._imgur._send_request(url, needs_auth=True, params=payload, method='POST') item = self._imgur.get_gallery_album(self.id) _change_object(self, item) return self
python
def submit_to_gallery(self, title, bypass_terms=False): """ 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 to True to by-pass the terms. """ url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) payload = {'title': title, 'terms': '1' if bypass_terms else '0'} self._imgur._send_request(url, needs_auth=True, params=payload, method='POST') item = self._imgur.get_gallery_album(self.id) _change_object(self, item) return self
[ "def", "submit_to_gallery", "(", "self", ",", "title", ",", "bypass_terms", "=", "False", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/gallery/{0}\"", ".", "format", "(", "self", ".", "id", ")", "payload", "=", "{", "'title'"...
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 to True to by-pass the terms.
[ "Add", "this", "to", "the", "gallery", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L325-L343
train
Damgaard/PyImgur
pyimgur/__init__.py
Album.update
def update(self, title=None, description=None, images=None, cover=None, layout=None, privacy=None): """ 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 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. :param privacy: The albums privacy level, can be public, hidden or secret. :param cover: The id of the cover image. :param layout: The way the album is displayed, can be blog, grid, horizontal or vertical. """ url = (self._imgur._base_url + "/3/album/" "{0}".format(self._delete_or_id_hash)) is_updated = self._imgur._send_request(url, params=locals(), method='POST') if is_updated: self.title = title or self.title self.description = description or self.description self.layout = layout or self.layout self.privacy = privacy or self.privacy if cover is not None: self.cover = (cover if isinstance(cover, Image) else Image({'id': cover}, self._imgur, has_fetched=False)) if images: self.images = [img if isinstance(img, Image) else Image({'id': img}, self._imgur, False) for img in images] return is_updated
python
def update(self, title=None, description=None, images=None, cover=None, layout=None, privacy=None): """ 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 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. :param privacy: The albums privacy level, can be public, hidden or secret. :param cover: The id of the cover image. :param layout: The way the album is displayed, can be blog, grid, horizontal or vertical. """ url = (self._imgur._base_url + "/3/album/" "{0}".format(self._delete_or_id_hash)) is_updated = self._imgur._send_request(url, params=locals(), method='POST') if is_updated: self.title = title or self.title self.description = description or self.description self.layout = layout or self.layout self.privacy = privacy or self.privacy if cover is not None: self.cover = (cover if isinstance(cover, Image) else Image({'id': cover}, self._imgur, has_fetched=False)) if images: self.images = [img if isinstance(img, Image) else Image({'id': img}, self._imgur, False) for img in images] return is_updated
[ "def", "update", "(", "self", ",", "title", "=", "None", ",", "description", "=", "None", ",", "images", "=", "None", ",", "cover", "=", "None", ",", "layout", "=", "None", ",", "privacy", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_im...
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 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. :param privacy: The albums privacy level, can be public, hidden or secret. :param cover: The id of the cover image. :param layout: The way the album is displayed, can be blog, grid, horizontal or vertical.
[ "Update", "the", "album", "s", "information", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L345-L381
train
Damgaard/PyImgur
pyimgur/__init__.py
Comment.get_replies
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 in child_comments]
python
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 in child_comments]
[ "def", "get_replies", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/comment/{0}/replies\"", ".", "format", "(", "self", ".", "id", ")", "json", "=", "self", ".", "_imgur", ".", "_send_request", "(", "url", ")", ...
Get the replies to this comment.
[ "Get", "the", "replies", "to", "this", "comment", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L432-L437
train
Damgaard/PyImgur
pyimgur/__init__.py
Gallery_item.comment
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} resp = self._imgur._send_request(url, params=payload, needs_auth=True, method='POST') return Comment(resp, imgur=self._imgur, has_fetched=False)
python
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} resp = self._imgur._send_request(url, params=payload, needs_auth=True, method='POST') return Comment(resp, imgur=self._imgur, has_fetched=False)
[ "def", "comment", "(", "self", ",", "text", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/comment\"", "payload", "=", "{", "'image_id'", ":", "self", ".", "id", ",", "'comment'", ":", "text", "}", "resp", "=", "self", ".",...
Make a top-level comment to this. :param text: The comment text.
[ "Make", "a", "top", "-", "level", "comment", "to", "this", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L464-L474
train
Damgaard/PyImgur
pyimgur/__init__.py
Gallery_item.downvote
def downvote(self): """ 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. """ url = self._imgur._base_url + "/3/gallery/{0}/vote/down".format(self.id) return self._imgur._send_request(url, needs_auth=True, method='POST')
python
def downvote(self): """ 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. """ url = self._imgur._base_url + "/3/gallery/{0}/vote/down".format(self.id) return self._imgur._send_request(url, needs_auth=True, method='POST')
[ "def", "downvote", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/gallery/{0}/vote/down\"", ".", "format", "(", "self", ".", "id", ")", "return", "self", ".", "_imgur", ".", "_send_request", "(", "url", ",", "needs...
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.
[ "Dislike", "this", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L476-L485
train
Damgaard/PyImgur
pyimgur/__init__.py
Gallery_item.get_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]
python
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]
[ "def", "get_comments", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/gallery/{0}/comments\"", ".", "format", "(", "self", ".", "id", ")", "resp", "=", "self", ".", "_imgur", ".", "_send_request", "(", "url", ")", ...
Get a list of the top-level comments.
[ "Get", "a", "list", "of", "the", "top", "-", "level", "comments", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L487-L491
train
Damgaard/PyImgur
pyimgur/__init__.py
Gallery_item.remove_from_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 = self._imgur.get_image(self.id) else: item = self._imgur.get_album(self.id) _change_object(self, item) return self
python
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 = self._imgur.get_image(self.id) else: item = self._imgur.get_album(self.id) _change_object(self, item) return self
[ "def", "remove_from_gallery", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/gallery/{0}\"", ".", "format", "(", "self", ".", "id", ")", "self", ".", "_imgur", ".", "_send_request", "(", "url", ",", "needs_auth", "...
Remove this image from the gallery.
[ "Remove", "this", "image", "from", "the", "gallery", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L493-L502
train
Damgaard/PyImgur
pyimgur/__init__.py
Image.download
def download(self, path='', name=None, overwrite=False, size=None): """ 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, then the title of the image will be used. If the image doesn't have a title, it's id will be used. Note that if the name given by name or title is an invalid filename, then the hash will be used as the name instead. :param overwrite: If True overwrite already existing file with the same name as what we want to save the file as. :param size: Instead of downloading the image in it's original size, we can choose to instead download a thumbnail of it. Options are 'small_square', 'big_square', 'small_thumbnail', 'medium_thumbnail', 'large_thumbnail' or 'huge_thumbnail'. :returns: Name of the new file. """ def save_as(filename): local_path = os.path.join(path, filename) if os.path.exists(local_path) and not overwrite: raise Exception("Trying to save as {0}, but file " "already exists.".format(local_path)) with open(local_path, 'wb') as out_file: out_file.write(resp.content) return local_path valid_sizes = {'small_square': 's', 'big_square': 'b', 'small_thumbnail': 't', 'medium_thumbnail': 'm', 'large_thumbnail': 'l', 'huge_thumbnail': 'h'} if size is not None: size = size.lower().replace(' ', '_') if size not in valid_sizes: raise LookupError('Invalid size. Valid options are: {0}'.format( ", " .join(valid_sizes.keys()))) suffix = valid_sizes.get(size, '') base, sep, ext = self.link.rpartition('.') resp = requests.get(base + suffix + sep + ext) if name or self.title: try: return save_as((name or self.title) + suffix + sep + ext) except IOError: pass # Invalid filename return save_as(self.id + suffix + sep + ext)
python
def download(self, path='', name=None, overwrite=False, size=None): """ 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, then the title of the image will be used. If the image doesn't have a title, it's id will be used. Note that if the name given by name or title is an invalid filename, then the hash will be used as the name instead. :param overwrite: If True overwrite already existing file with the same name as what we want to save the file as. :param size: Instead of downloading the image in it's original size, we can choose to instead download a thumbnail of it. Options are 'small_square', 'big_square', 'small_thumbnail', 'medium_thumbnail', 'large_thumbnail' or 'huge_thumbnail'. :returns: Name of the new file. """ def save_as(filename): local_path = os.path.join(path, filename) if os.path.exists(local_path) and not overwrite: raise Exception("Trying to save as {0}, but file " "already exists.".format(local_path)) with open(local_path, 'wb') as out_file: out_file.write(resp.content) return local_path valid_sizes = {'small_square': 's', 'big_square': 'b', 'small_thumbnail': 't', 'medium_thumbnail': 'm', 'large_thumbnail': 'l', 'huge_thumbnail': 'h'} if size is not None: size = size.lower().replace(' ', '_') if size not in valid_sizes: raise LookupError('Invalid size. Valid options are: {0}'.format( ", " .join(valid_sizes.keys()))) suffix = valid_sizes.get(size, '') base, sep, ext = self.link.rpartition('.') resp = requests.get(base + suffix + sep + ext) if name or self.title: try: return save_as((name or self.title) + suffix + sep + ext) except IOError: pass # Invalid filename return save_as(self.id + suffix + sep + ext)
[ "def", "download", "(", "self", ",", "path", "=", "''", ",", "name", "=", "None", ",", "overwrite", "=", "False", ",", "size", "=", "None", ")", ":", "def", "save_as", "(", "filename", ")", ":", "local_path", "=", "os", ".", "path", ".", "join", ...
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, then the title of the image will be used. If the image doesn't have a title, it's id will be used. Note that if the name given by name or title is an invalid filename, then the hash will be used as the name instead. :param overwrite: If True overwrite already existing file with the same name as what we want to save the file as. :param size: Instead of downloading the image in it's original size, we can choose to instead download a thumbnail of it. Options are 'small_square', 'big_square', 'small_thumbnail', 'medium_thumbnail', 'large_thumbnail' or 'huge_thumbnail'. :returns: Name of the new file.
[ "Download", "the", "image", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L554-L600
train
Damgaard/PyImgur
pyimgur/__init__.py
Image.update
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_request(url, params=locals(), method='POST') if is_updated: self.title = title or self.title self.description = description or self.description return is_updated
python
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_request(url, params=locals(), method='POST') if is_updated: self.title = title or self.title self.description = description or self.description return is_updated
[ "def", "update", "(", "self", ",", "title", "=", "None", ",", "description", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/image/\"", "\"{0}\"", ".", "format", "(", "self", ".", "_delete_or_id_hash", ")", "...
Update the image with a new title and/or description.
[ "Update", "the", "image", "with", "a", "new", "title", "and", "/", "or", "description", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L631-L640
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur._send_request
def _send_request(self, url, needs_auth=False, **kwargs): """ 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 certain server-side errors. - Refresh access token automatically if expired. - Updating ratelimit info :param needs_auth: Is authentication as a user needed for the execution of this method? """ # TODO: Add automatic test for timed_out access_tokens and # automatically refresh it before carrying out the request. if self.access_token is None and needs_auth: # TODO: Use inspect to insert name of method in error msg. raise Exception("Authentication as a user is required to use this " "method.") if self.access_token is None: # Not authenticated as a user. Use anonymous access. auth = {'Authorization': 'Client-ID {0}'.format(self.client_id)} else: auth = {'Authorization': 'Bearer {0}'.format(self.access_token)} if self.mashape_key: auth.update({'X-Mashape-Key': self.mashape_key}) content = [] is_paginated = False if 'limit' in kwargs: is_paginated = True limit = kwargs['limit'] or self.DEFAULT_LIMIT del kwargs['limit'] page = 0 base_url = url url.format(page) kwargs['authentication'] = auth while True: result = request.send_request(url, verify=self.verify, **kwargs) new_content, ratelimit_info = result if is_paginated and new_content and limit > len(new_content): content += new_content page += 1 url = base_url.format(page) else: if is_paginated: content = (content + new_content)[:limit] else: content = new_content break # Note: When the cache is implemented, it's important that the # ratelimit info doesn't get updated with the ratelimit info in the # cache since that's likely incorrect. for key, value in ratelimit_info.items(): setattr(self, key[2:].replace('-', '_'), value) return content
python
def _send_request(self, url, needs_auth=False, **kwargs): """ 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 certain server-side errors. - Refresh access token automatically if expired. - Updating ratelimit info :param needs_auth: Is authentication as a user needed for the execution of this method? """ # TODO: Add automatic test for timed_out access_tokens and # automatically refresh it before carrying out the request. if self.access_token is None and needs_auth: # TODO: Use inspect to insert name of method in error msg. raise Exception("Authentication as a user is required to use this " "method.") if self.access_token is None: # Not authenticated as a user. Use anonymous access. auth = {'Authorization': 'Client-ID {0}'.format(self.client_id)} else: auth = {'Authorization': 'Bearer {0}'.format(self.access_token)} if self.mashape_key: auth.update({'X-Mashape-Key': self.mashape_key}) content = [] is_paginated = False if 'limit' in kwargs: is_paginated = True limit = kwargs['limit'] or self.DEFAULT_LIMIT del kwargs['limit'] page = 0 base_url = url url.format(page) kwargs['authentication'] = auth while True: result = request.send_request(url, verify=self.verify, **kwargs) new_content, ratelimit_info = result if is_paginated and new_content and limit > len(new_content): content += new_content page += 1 url = base_url.format(page) else: if is_paginated: content = (content + new_content)[:limit] else: content = new_content break # Note: When the cache is implemented, it's important that the # ratelimit info doesn't get updated with the ratelimit info in the # cache since that's likely incorrect. for key, value in ratelimit_info.items(): setattr(self, key[2:].replace('-', '_'), value) return content
[ "def", "_send_request", "(", "self", ",", "url", ",", "needs_auth", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# TODO: Add automatic test for timed_out access_tokens and", "# automatically refresh it before carrying out the request.", "if", "self", ".", "access_token...
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 certain server-side errors. - Refresh access token automatically if expired. - Updating ratelimit info :param needs_auth: Is authentication as a user needed for the execution of this method?
[ "Handles", "top", "level", "functionality", "for", "sending", "requests", "to", "Imgur", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L692-L748
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.authorization_url
def authorization_url(self, response, state=""): """ 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 authorizing your application, the user will instead be shown a pin on Imgurs website. Both code and pin are used to get an access_token and refresh token with the exchange_code and exchange_pin functions respectively. :param state: This optional parameter indicates any state which may be useful to your application upon receipt of the response. Imgur round-trips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, nonces, and cross-site-request-forgery mitigations. """ return AUTHORIZE_URL.format(self._base_url, self.client_id, response, state)
python
def authorization_url(self, response, state=""): """ 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 authorizing your application, the user will instead be shown a pin on Imgurs website. Both code and pin are used to get an access_token and refresh token with the exchange_code and exchange_pin functions respectively. :param state: This optional parameter indicates any state which may be useful to your application upon receipt of the response. Imgur round-trips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, nonces, and cross-site-request-forgery mitigations. """ return AUTHORIZE_URL.format(self._base_url, self.client_id, response, state)
[ "def", "authorization_url", "(", "self", ",", "response", ",", "state", "=", "\"\"", ")", ":", "return", "AUTHORIZE_URL", ".", "format", "(", "self", ".", "_base_url", ",", "self", ".", "client_id", ",", "response", ",", "state", ")" ]
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 authorizing your application, the user will instead be shown a pin on Imgurs website. Both code and pin are used to get an access_token and refresh token with the exchange_code and exchange_pin functions respectively. :param state: This optional parameter indicates any state which may be useful to your application upon receipt of the response. Imgur round-trips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, nonces, and cross-site-request-forgery mitigations.
[ "Return", "the", "authorization", "url", "that", "s", "needed", "to", "authorize", "as", "a", "user", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L750-L768
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.change_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_token. Because that doesn't make sense. self.client_id = client_id or self.client_id self.client_secret = client_secret or self.client_secret self.access_token = access_token or self.access_token self.refresh_token = refresh_token or self.refresh_token
python
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_token. Because that doesn't make sense. self.client_id = client_id or self.client_id self.client_secret = client_secret or self.client_secret self.access_token = access_token or self.access_token self.refresh_token = refresh_token or self.refresh_token
[ "def", "change_authentication", "(", "self", ",", "client_id", "=", "None", ",", "client_secret", "=", "None", ",", "access_token", "=", "None", ",", "refresh_token", "=", "None", ")", ":", "# TODO: Add error checking so you cannot change client_id and retain", "# acces...
Change the current authentication.
[ "Change", "the", "current", "authentication", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L770-L778
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.create_album
def create_album(self, title=None, description=None, images=None, cover=None): """ 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 add (non-existing or not owned by you) will not cause exceptions, but fail silently. :param cover: The id of the image you want as the albums cover image. :returns: The newly created album. """ url = self._base_url + "/3/album/" payload = {'ids': images, 'title': title, 'description': description, 'cover': cover} resp = self._send_request(url, params=payload, method='POST') return Album(resp, self, has_fetched=False)
python
def create_album(self, title=None, description=None, images=None, cover=None): """ 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 add (non-existing or not owned by you) will not cause exceptions, but fail silently. :param cover: The id of the image you want as the albums cover image. :returns: The newly created album. """ url = self._base_url + "/3/album/" payload = {'ids': images, 'title': title, 'description': description, 'cover': cover} resp = self._send_request(url, params=payload, method='POST') return Album(resp, self, has_fetched=False)
[ "def", "create_album", "(", "self", ",", "title", "=", "None", ",", "description", "=", "None", ",", "images", "=", "None", ",", "cover", "=", "None", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/album/\"", "payload", "=", "{", "'ids'", ...
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 add (non-existing or not owned by you) will not cause exceptions, but fail silently. :param cover: The id of the image you want as the albums cover image. :returns: The newly created album.
[ "Create", "a", "new", "Album", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L780-L799
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.exchange_code
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_code', 'code': code} result = self._send_request(EXCHANGE_URL.format(self._base_url), params=params, method='POST', data_field=None) self.access_token = result['access_token'] self.refresh_token = result['refresh_token'] return self.access_token, self.refresh_token
python
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_code', 'code': code} result = self._send_request(EXCHANGE_URL.format(self._base_url), params=params, method='POST', data_field=None) self.access_token = result['access_token'] self.refresh_token = result['refresh_token'] return self.access_token, self.refresh_token
[ "def", "exchange_code", "(", "self", ",", "code", ")", ":", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "'grant_type'", ":", "'authorization_code'", ",", "'code'", ":", "co...
Exchange one-use code for an access_token and request_token.
[ "Exchange", "one", "-", "use", "code", "for", "an", "access_token", "and", "request_token", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L813-L824
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.exchange_pin
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', 'pin': pin} result = self._send_request(EXCHANGE_URL.format(self._base_url), params=params, method='POST', data_field=None) self.access_token = result['access_token'] self.refresh_token = result['refresh_token'] return self.access_token, self.refresh_token
python
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', 'pin': pin} result = self._send_request(EXCHANGE_URL.format(self._base_url), params=params, method='POST', data_field=None) self.access_token = result['access_token'] self.refresh_token = result['refresh_token'] return self.access_token, self.refresh_token
[ "def", "exchange_pin", "(", "self", ",", "pin", ")", ":", "params", "=", "{", "'client_id'", ":", "self", ".", "client_id", ",", "'client_secret'", ":", "self", ".", "client_secret", ",", "'grant_type'", ":", "'pin'", ",", "'pin'", ":", "pin", "}", "resu...
Exchange one-use pin for an access_token and request_token.
[ "Exchange", "one", "-", "use", "pin", "for", "an", "access_token", "and", "request_token", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L826-L837
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_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)
python
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)
[ "def", "get_album", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/album/{0}\"", ".", "format", "(", "id", ")", "json", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Album", "(", "json", ",", "self...
Return information about this album.
[ "Return", "information", "about", "this", "album", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L839-L843
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_at_url
def get_at_url(self, url): """ 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 for several different types of object. Using a wrong, but similair call, such as get_subreddit_image on a meme image will not cause an error. But instead return a subset of information, with either the remaining pieces missing or the value set to None. This makes it hard to create a method such as this that attempts to deduce the object from the url. Due to these factors, this method should be considered experimental and used carefully. :param url: The url where the content is located at """ class NullDevice(): def write(self, string): pass def get_gallery_item(id): """ Special helper method to get gallery items. The problem is that it's impossible to distinguish albums and images from each other based on the url. And there isn't a common url endpoints that return either a Gallery_album or a Gallery_image depending on what the id represents. So the only option is to assume it's a Gallery_image and if we get an exception then try Gallery_album. Gallery_image is attempted first because there is the most of them. """ try: # HACK: Problem is that send_request prints the error message # from Imgur when it encounters an error. This is nice because # this error message is more descriptive than just the status # code that Requests give. But since we first assume the id # belong to an image, it means we will get an error whenever # the id belongs to an album. The following code temporarily # disables stdout to avoid give a cryptic and incorrect error. # Code for disabling stdout is from # http://coreygoldberg.blogspot.dk/2009/05/ # python-redirect-or-turn-off-stdout-and.html original_stdout = sys.stdout # keep a reference to STDOUT sys.stdout = NullDevice() # redirect the real STDOUT return self.get_gallery_image(id) # TODO: Add better error codes so I don't have to do a catch-all except Exception: return self.get_gallery_album(id) finally: sys.stdout = original_stdout # turn STDOUT back on if not self.is_imgur_url(url): return None objects = {'album': {'regex': "a/(?P<id>[\w.]*?)$", 'method': self.get_album}, 'comment': {'regex': "gallery/\w*/comment/(?P<id>[\w.]*?)$", 'method': self.get_comment}, 'gallery': {'regex': "(gallery|r/\w*?)/(?P<id>[\w.]*?)$", 'method': get_gallery_item}, # Valid image extensions: http://imgur.com/faq#types # All are between 3 and 4 chars long. 'image': {'regex': "(?P<id>[\w.]*?)(\\.\w{3,4})?$", 'method': self.get_image}, 'user': {'regex': "user/(?P<id>[\w.]*?)$", 'method': self.get_user} } parsed_url = urlparse(url) for obj_type, values in objects.items(): regex_result = re.match('/' + values['regex'], parsed_url.path) if regex_result is not None: obj_id = regex_result.group('id') initial_object = values['method'](obj_id) if obj_type == 'image': try: # A better version might be to ping the url where the # gallery_image should be with a requests.head call. If # we get a 200 returned, then that means it exists and # this becomes less hacky. original_stdout = sys.stdout sys.stdout = NullDevice() if getattr(initial_object, 'section', None): sub = initial_object.section return self.get_subreddit_image(sub, obj_id) return self.get_gallery_image(obj_id) except Exception: pass finally: sys.stdout = original_stdout return initial_object
python
def get_at_url(self, url): """ 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 for several different types of object. Using a wrong, but similair call, such as get_subreddit_image on a meme image will not cause an error. But instead return a subset of information, with either the remaining pieces missing or the value set to None. This makes it hard to create a method such as this that attempts to deduce the object from the url. Due to these factors, this method should be considered experimental and used carefully. :param url: The url where the content is located at """ class NullDevice(): def write(self, string): pass def get_gallery_item(id): """ Special helper method to get gallery items. The problem is that it's impossible to distinguish albums and images from each other based on the url. And there isn't a common url endpoints that return either a Gallery_album or a Gallery_image depending on what the id represents. So the only option is to assume it's a Gallery_image and if we get an exception then try Gallery_album. Gallery_image is attempted first because there is the most of them. """ try: # HACK: Problem is that send_request prints the error message # from Imgur when it encounters an error. This is nice because # this error message is more descriptive than just the status # code that Requests give. But since we first assume the id # belong to an image, it means we will get an error whenever # the id belongs to an album. The following code temporarily # disables stdout to avoid give a cryptic and incorrect error. # Code for disabling stdout is from # http://coreygoldberg.blogspot.dk/2009/05/ # python-redirect-or-turn-off-stdout-and.html original_stdout = sys.stdout # keep a reference to STDOUT sys.stdout = NullDevice() # redirect the real STDOUT return self.get_gallery_image(id) # TODO: Add better error codes so I don't have to do a catch-all except Exception: return self.get_gallery_album(id) finally: sys.stdout = original_stdout # turn STDOUT back on if not self.is_imgur_url(url): return None objects = {'album': {'regex': "a/(?P<id>[\w.]*?)$", 'method': self.get_album}, 'comment': {'regex': "gallery/\w*/comment/(?P<id>[\w.]*?)$", 'method': self.get_comment}, 'gallery': {'regex': "(gallery|r/\w*?)/(?P<id>[\w.]*?)$", 'method': get_gallery_item}, # Valid image extensions: http://imgur.com/faq#types # All are between 3 and 4 chars long. 'image': {'regex': "(?P<id>[\w.]*?)(\\.\w{3,4})?$", 'method': self.get_image}, 'user': {'regex': "user/(?P<id>[\w.]*?)$", 'method': self.get_user} } parsed_url = urlparse(url) for obj_type, values in objects.items(): regex_result = re.match('/' + values['regex'], parsed_url.path) if regex_result is not None: obj_id = regex_result.group('id') initial_object = values['method'](obj_id) if obj_type == 'image': try: # A better version might be to ping the url where the # gallery_image should be with a requests.head call. If # we get a 200 returned, then that means it exists and # this becomes less hacky. original_stdout = sys.stdout sys.stdout = NullDevice() if getattr(initial_object, 'section', None): sub = initial_object.section return self.get_subreddit_image(sub, obj_id) return self.get_gallery_image(obj_id) except Exception: pass finally: sys.stdout = original_stdout return initial_object
[ "def", "get_at_url", "(", "self", ",", "url", ")", ":", "class", "NullDevice", "(", ")", ":", "def", "write", "(", "self", ",", "string", ")", ":", "pass", "def", "get_gallery_item", "(", "id", ")", ":", "\"\"\"\n Special helper method to get galler...
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 for several different types of object. Using a wrong, but similair call, such as get_subreddit_image on a meme image will not cause an error. But instead return a subset of information, with either the remaining pieces missing or the value set to None. This makes it hard to create a method such as this that attempts to deduce the object from the url. Due to these factors, this method should be considered experimental and used carefully. :param url: The url where the content is located at
[ "Return", "a", "object", "representing", "the", "content", "at", "url", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L845-L939
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_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)
python
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)
[ "def", "get_comment", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/comment/{0}\"", ".", "format", "(", "id", ")", "json", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Comment", "(", "json", ",", ...
Return information about this comment.
[ "Return", "information", "about", "this", "comment", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L941-L945
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_gallery
def get_gallery(self, section='hot', sort='viral', window='day', show_viral=True, limit=None): """ 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. :param show_viral: true | false - Show or hide viral images from the 'user' section. Defaults to true. :param limit: The number of items to return. """ url = (self._base_url + "/3/gallery/{}/{}/{}/{}?showViral=" "{}".format(section, sort, window, '{}', show_viral)) resp = self._send_request(url, limit=limit) return [_get_album_or_image(thing, self) for thing in resp]
python
def get_gallery(self, section='hot', sort='viral', window='day', show_viral=True, limit=None): """ 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. :param show_viral: true | false - Show or hide viral images from the 'user' section. Defaults to true. :param limit: The number of items to return. """ url = (self._base_url + "/3/gallery/{}/{}/{}/{}?showViral=" "{}".format(section, sort, window, '{}', show_viral)) resp = self._send_request(url, limit=limit) return [_get_album_or_image(thing, self) for thing in resp]
[ "def", "get_gallery", "(", "self", ",", "section", "=", "'hot'", ",", "sort", "=", "'viral'", ",", "window", "=", "'day'", ",", "show_viral", "=", "True", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_base_url", "+", "\"/3/gall...
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. :param show_viral: true | false - Show or hide viral images from the 'user' section. Defaults to true. :param limit: The number of items to return.
[ "Return", "a", "list", "of", "gallery", "albums", "and", "gallery", "images", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L947-L963
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_gallery_album
def get_gallery_album(self, id): """ 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. """ url = self._base_url + "/3/gallery/album/{0}".format(id) resp = self._send_request(url) return Gallery_album(resp, self)
python
def get_gallery_album(self, id): """ 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. """ url = self._base_url + "/3/gallery/album/{0}".format(id) resp = self._send_request(url) return Gallery_album(resp, self)
[ "def", "get_gallery_album", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/gallery/album/{0}\"", ".", "format", "(", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Gallery_album", "(", ...
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.
[ "Return", "the", "gallery", "album", "matching", "the", "id", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L965-L975
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_gallery_image
def get_gallery_image(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. """ url = self._base_url + "/3/gallery/image/{0}".format(id) resp = self._send_request(url) return Gallery_image(resp, self)
python
def get_gallery_image(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. """ url = self._base_url + "/3/gallery/image/{0}".format(id) resp = self._send_request(url) return Gallery_image(resp, self)
[ "def", "get_gallery_image", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/gallery/image/{0}\"", ".", "format", "(", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Gallery_image", "(", ...
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.
[ "Return", "the", "gallery", "image", "matching", "the", "id", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L977-L987
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_image
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)
python
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)
[ "def", "get_image", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/image/{0}\"", ".", "format", "(", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Image", "(", "resp", ",", "self...
Return a Image object representing the image with the given id.
[ "Return", "a", "Image", "object", "representing", "the", "image", "with", "the", "given", "id", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L989-L993
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_message
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) resp = self._send_request(url) return Message(resp, self)
python
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) resp = self._send_request(url) return Message(resp, self)
[ "def", "get_message", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/message/{0}\"", ".", "format", "(", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Message", "(", "resp", ",", ...
Return a Message object for given id. :param id: The id of the message object to return.
[ "Return", "a", "Message", "object", "for", "given", "id", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L995-L1003
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_notification
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) resp = self._send_request(url) return Notification(resp, self)
python
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) resp = self._send_request(url) return Notification(resp, self)
[ "def", "get_notification", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/notification/{0}\"", ".", "format", "(", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url", ")", "return", "Notification", "(", "...
Return a Notification object. :param id: The id of the notification object to return.
[ "Return", "a", "Notification", "object", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1005-L1013
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_memes_gallery
def get_memes_gallery(self, sort='viral', window='week', limit=None): """ 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 | year | all, defaults to week. :param limit: The number of items to return. """ url = (self._base_url + "/3/gallery/g/memes/{0}/{1}/{2}".format( sort, window, '{}')) resp = self._send_request(url, limit=limit) return [_get_album_or_image(thing, self) for thing in resp]
python
def get_memes_gallery(self, sort='viral', window='week', limit=None): """ 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 | year | all, defaults to week. :param limit: The number of items to return. """ url = (self._base_url + "/3/gallery/g/memes/{0}/{1}/{2}".format( sort, window, '{}')) resp = self._send_request(url, limit=limit) return [_get_album_or_image(thing, self) for thing in resp]
[ "def", "get_memes_gallery", "(", "self", ",", "sort", "=", "'viral'", ",", "window", "=", "'week'", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_base_url", "+", "\"/3/gallery/g/memes/{0}/{1}/{2}\"", ".", "format", "(", "sort", ",", ...
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 | year | all, defaults to week. :param limit: The number of items to return.
[ "Return", "a", "list", "of", "gallery", "albums", "/", "images", "submitted", "to", "the", "memes", "gallery" ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1015-L1029
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_subreddit_gallery
def get_subreddit_gallery(self, subreddit, sort='time', window='top', limit=None): """ 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: Change the date range of the request if the section is "top", day | week | month | year | all, defaults to day. :param limit: The number of items to return. """ url = (self._base_url + "/3/gallery/r/{0}/{1}/{2}/{3}".format( subreddit, sort, window, '{}')) resp = self._send_request(url, limit=limit) return [_get_album_or_image(thing, self) for thing in resp]
python
def get_subreddit_gallery(self, subreddit, sort='time', window='top', limit=None): """ 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: Change the date range of the request if the section is "top", day | week | month | year | all, defaults to day. :param limit: The number of items to return. """ url = (self._base_url + "/3/gallery/r/{0}/{1}/{2}/{3}".format( subreddit, sort, window, '{}')) resp = self._send_request(url, limit=limit) return [_get_album_or_image(thing, self) for thing in resp]
[ "def", "get_subreddit_gallery", "(", "self", ",", "subreddit", ",", "sort", "=", "'time'", ",", "window", "=", "'top'", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_base_url", "+", "\"/3/gallery/r/{0}/{1}/{2}/{3}\"", ".", "format", ...
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: Change the date range of the request if the section is "top", day | week | month | year | all, defaults to day. :param limit: The number of items to return.
[ "Return", "a", "list", "of", "gallery", "albums", "/", "images", "submitted", "to", "a", "subreddit", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1048-L1065
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_subreddit_image
def get_subreddit_image(self, subreddit, id): """ 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. """ url = self._base_url + "/3/gallery/r/{0}/{1}".format(subreddit, id) resp = self._send_request(url) return Gallery_image(resp, self)
python
def get_subreddit_image(self, subreddit, id): """ 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. """ url = self._base_url + "/3/gallery/r/{0}/{1}".format(subreddit, id) resp = self._send_request(url) return Gallery_image(resp, self)
[ "def", "get_subreddit_image", "(", "self", ",", "subreddit", ",", "id", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/gallery/r/{0}/{1}\"", ".", "format", "(", "subreddit", ",", "id", ")", "resp", "=", "self", ".", "_send_request", "(", "url",...
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.
[ "Return", "the", "Gallery_image", "with", "the", "id", "submitted", "to", "subreddit", "gallery" ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1067-L1076
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.get_user
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._base_url + "/3/account/{0}".format(username) json = self._send_request(url) return User(json, self)
python
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._base_url + "/3/account/{0}".format(username) json = self._send_request(url) return User(json, self)
[ "def", "get_user", "(", "self", ",", "username", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/account/{0}\"", ".", "format", "(", "username", ")", "json", "=", "self", ".", "_send_request", "(", "url", ")", "return", "User", "(", "json", ...
Return a User object for this username. :param username: The name of the user we want more information about.
[ "Return", "a", "User", "object", "for", "this", "username", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1078-L1086
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.refresh_access_token
def refresh_access_token(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. """ if self.client_secret is None: raise Exception("client_secret must be set to execute " "refresh_access_token.") if self.refresh_token is None: raise Exception("refresh_token must be set to execute " "refresh_access_token.") params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token} result = self._send_request(REFRESH_URL.format(self._base_url), params=params, method='POST', data_field=None) self.access_token = result['access_token'] return self.access_token
python
def refresh_access_token(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. """ if self.client_secret is None: raise Exception("client_secret must be set to execute " "refresh_access_token.") if self.refresh_token is None: raise Exception("refresh_token must be set to execute " "refresh_access_token.") params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token} result = self._send_request(REFRESH_URL.format(self._base_url), params=params, method='POST', data_field=None) self.access_token = result['access_token'] return self.access_token
[ "def", "refresh_access_token", "(", "self", ")", ":", "if", "self", ".", "client_secret", "is", "None", ":", "raise", "Exception", "(", "\"client_secret must be set to execute \"", "\"refresh_access_token.\"", ")", "if", "self", ".", "refresh_token", "is", "None", "...
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.
[ "Refresh", "the", "access_token", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1092-L1113
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.search_gallery
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]
python
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]
[ "def", "search_gallery", "(", "self", ",", "q", ")", ":", "url", "=", "self", ".", "_base_url", "+", "\"/3/gallery/search?q={0}\"", ".", "format", "(", "q", ")", "resp", "=", "self", ".", "_send_request", "(", "url", ")", "return", "[", "_get_album_or_imag...
Search the gallery with the given query string.
[ "Search", "the", "gallery", "with", "the", "given", "query", "string", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1115-L1119
train
Damgaard/PyImgur
pyimgur/__init__.py
Imgur.upload_image
def upload_image(self, path=None, url=None, title=None, description=None, album=None): """ 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. :param album: The album the image will be added to when uploaded. Can be either a Album object or it's id. Leave at None to upload without adding to an Album, adding it later is possible. Authentication as album owner is necessary to upload to an album with this function. :returns: An Image object representing the uploaded image. """ if bool(path) == bool(url): raise LookupError("Either path or url must be given.") if path: with open(path, 'rb') as image_file: binary_data = image_file.read() image = b64encode(binary_data) else: image = url payload = {'album_id': album, 'image': image, 'title': title, 'description': description} resp = self._send_request(self._base_url + "/3/image", params=payload, method='POST') # TEMPORARY HACK: # On 5-08-2013 I noticed Imgur now returned enough information from # this call to fully populate the Image object. However those variables # that matched arguments were always None, even if they had been given. # See https://groups.google.com/forum/#!topic/imgur/F3uVb55TMGo resp['title'] = title resp['description'] = description if album is not None: resp['album'] = (Album({'id': album}, self, False) if not isinstance(album, Album) else album) return Image(resp, self)
python
def upload_image(self, path=None, url=None, title=None, description=None, album=None): """ 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. :param album: The album the image will be added to when uploaded. Can be either a Album object or it's id. Leave at None to upload without adding to an Album, adding it later is possible. Authentication as album owner is necessary to upload to an album with this function. :returns: An Image object representing the uploaded image. """ if bool(path) == bool(url): raise LookupError("Either path or url must be given.") if path: with open(path, 'rb') as image_file: binary_data = image_file.read() image = b64encode(binary_data) else: image = url payload = {'album_id': album, 'image': image, 'title': title, 'description': description} resp = self._send_request(self._base_url + "/3/image", params=payload, method='POST') # TEMPORARY HACK: # On 5-08-2013 I noticed Imgur now returned enough information from # this call to fully populate the Image object. However those variables # that matched arguments were always None, even if they had been given. # See https://groups.google.com/forum/#!topic/imgur/F3uVb55TMGo resp['title'] = title resp['description'] = description if album is not None: resp['album'] = (Album({'id': album}, self, False) if not isinstance(album, Album) else album) return Image(resp, self)
[ "def", "upload_image", "(", "self", ",", "path", "=", "None", ",", "url", "=", "None", ",", "title", "=", "None", ",", "description", "=", "None", ",", "album", "=", "None", ")", ":", "if", "bool", "(", "path", ")", "==", "bool", "(", "url", ")",...
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. :param album: The album the image will be added to when uploaded. Can be either a Album object or it's id. Leave at None to upload without adding to an Album, adding it later is possible. Authentication as album owner is necessary to upload to an album with this function. :returns: An Image object representing the uploaded image.
[ "Upload", "the", "image", "at", "either", "path", "or", "url", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1121-L1162
train
Damgaard/PyImgur
pyimgur/__init__.py
Message.delete
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')
python
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')
[ "def", "delete", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/message/{0}\"", ".", "format", "(", "self", ".", "id", ")", "return", "self", ".", "_imgur", ".", "_send_request", "(", "url", ",", "method", "=", ...
Delete the message.
[ "Delete", "the", "message", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1182-L1185
train
Damgaard/PyImgur
pyimgur/__init__.py
Message.get_thread
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._imgur) for msg in resp]
python
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._imgur) for msg in resp]
[ "def", "get_thread", "(", "self", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/message/{0}/thread\"", ".", "format", "(", "self", ".", "first_message", ".", "id", ")", ")", "resp", "=", "self", ".", "_imgur", ".", "_se...
Return the message thread this Message is in.
[ "Return", "the", "message", "thread", "this", "Message", "is", "in", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1187-L1192
train
Damgaard/PyImgur
pyimgur/__init__.py
Message.reply
def reply(self, body): """ 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. """ return self.author.send_message(body=body, reply_to=self.id)
python
def reply(self, body): """ 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. """ return self.author.send_message(body=body, reply_to=self.id)
[ "def", "reply", "(", "self", ",", "body", ")", ":", "return", "self", ".", "author", ".", "send_message", "(", "body", "=", "body", ",", "reply_to", "=", "self", ".", "id", ")" ]
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.
[ "Reply", "to", "this", "message", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1194-L1204
train
Damgaard/PyImgur
pyimgur/__init__.py
User.change_settings
def change_settings(self, bio=None, public_images=None, messaging_enabled=None, album_privacy=None, accepted_gallery_terms=None): """ 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_enabled: Set to True to enable messaging. :param album_privacy: The default privacy level of albums created by the user. Can be public, hidden or secret. :param accepted_gallery_terms: The user agreement to Imgur Gallery terms. Necessary before the user can submit to the gallery. """ # NOTE: album_privacy should maybe be renamed to default_privacy # NOTE: public_images is a boolean, despite the documentation saying it # is a string. url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name) resp = self._imgur._send_request(url, needs_auth=True, params=locals(), method='POST') return resp
python
def change_settings(self, bio=None, public_images=None, messaging_enabled=None, album_privacy=None, accepted_gallery_terms=None): """ 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_enabled: Set to True to enable messaging. :param album_privacy: The default privacy level of albums created by the user. Can be public, hidden or secret. :param accepted_gallery_terms: The user agreement to Imgur Gallery terms. Necessary before the user can submit to the gallery. """ # NOTE: album_privacy should maybe be renamed to default_privacy # NOTE: public_images is a boolean, despite the documentation saying it # is a string. url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name) resp = self._imgur._send_request(url, needs_auth=True, params=locals(), method='POST') return resp
[ "def", "change_settings", "(", "self", ",", "bio", "=", "None", ",", "public_images", "=", "None", ",", "messaging_enabled", "=", "None", ",", "album_privacy", "=", "None", ",", "accepted_gallery_terms", "=", "None", ")", ":", "# NOTE: album_privacy should maybe b...
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_enabled: Set to True to enable messaging. :param album_privacy: The default privacy level of albums created by the user. Can be public, hidden or secret. :param accepted_gallery_terms: The user agreement to Imgur Gallery terms. Necessary before the user can submit to the gallery.
[ "Update", "the", "settings", "for", "the", "user", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1265-L1287
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_albums
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. """ url = (self._imgur._base_url + "/3/account/{0}/albums/{1}".format(self.name, '{}')) resp = self._imgur._send_request(url, limit=limit) return [Album(alb, self._imgur, False) for alb in resp]
python
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. """ url = (self._imgur._base_url + "/3/account/{0}/albums/{1}".format(self.name, '{}')) resp = self._imgur._send_request(url, limit=limit) return [Album(alb, self._imgur, False) for alb in resp]
[ "def", "get_albums", "(", "self", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/albums/{1}\"", ".", "format", "(", "self", ".", "name", ",", "'{}'", ")", ")", "resp", "=", "self", ...
Return a list of the user's albums. Secret and hidden albums are only returned if this is the logged-in user.
[ "Return", "a", "list", "of", "the", "user", "s", "albums", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1294-L1304
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_favorites
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 thing in resp]
python
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 thing in resp]
[ "def", "get_favorites", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/favorites\"", ".", "format", "(", "self", ".", "name", ")", "resp", "=", "self", ".", "_imgur", ".", "_send_request", "(", "url", "...
Return the users favorited images.
[ "Return", "the", "users", "favorited", "images", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1312-L1316
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_gallery_favorites
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_request(url) return [Image(img, self._imgur) for img in resp]
python
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_request(url) return [Image(img, self._imgur) for img in resp]
[ "def", "get_gallery_favorites", "(", "self", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/gallery_favorites\"", ".", "format", "(", "self", ".", "name", ")", ")", "resp", "=", "self", ".", "_imgur", ".", "_send...
Get a list of the images in the gallery this user has favorited.
[ "Get", "a", "list", "of", "the", "images", "in", "the", "gallery", "this", "user", "has", "favorited", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1318-L1323
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_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)
python
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)
[ "def", "get_gallery_profile", "(", "self", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/\"", "\"gallery_profile\"", ".", "format", "(", "self", ".", "name", ")", ")", "return", "self", ".", "_imgur", ".", "_sen...
Return the users gallery profile.
[ "Return", "the", "users", "gallery", "profile", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1325-L1329
train
Damgaard/PyImgur
pyimgur/__init__.py
User.has_verified_email
def has_verified_email(self): """ 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. """ url = (self._imgur._base_url + "/3/account/{0}/" "verifyemail".format(self.name)) return self._imgur._send_request(url, needs_auth=True)
python
def has_verified_email(self): """ 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. """ url = (self._imgur._base_url + "/3/account/{0}/" "verifyemail".format(self.name)) return self._imgur._send_request(url, needs_auth=True)
[ "def", "has_verified_email", "(", "self", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/\"", "\"verifyemail\"", ".", "format", "(", "self", ".", "name", ")", ")", "return", "self", ".", "_imgur", ".", "_send_req...
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.
[ "Has", "the", "user", "verified", "that", "the", "email", "he", "has", "given", "is", "legit?" ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1331-L1341
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_images
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 [Image(img, self._imgur) for img in resp]
python
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 [Image(img, self._imgur) for img in resp]
[ "def", "get_images", "(", "self", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/\"", "\"images/{1}\"", ".", "format", "(", "self", ".", "name", ",", "'{}'", ")", ")", "resp", "=", ...
Return all of the images associated with the user.
[ "Return", "all", "of", "the", "images", "associated", "with", "the", "user", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1343-L1348
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_messages
def get_messages(self, new=True): """ Return all messages sent to this user, formatted as a notification. :param new: False for all notifications, True for only non-viewed notifications. """ url = (self._imgur._base_url + "/3/account/{0}/notifications/" "messages".format(self.name)) result = self._imgur._send_request(url, params=locals(), needs_auth=True) return [Notification(msg_dict, self._imgur, has_fetched=True) for msg_dict in result]
python
def get_messages(self, new=True): """ Return all messages sent to this user, formatted as a notification. :param new: False for all notifications, True for only non-viewed notifications. """ url = (self._imgur._base_url + "/3/account/{0}/notifications/" "messages".format(self.name)) result = self._imgur._send_request(url, params=locals(), needs_auth=True) return [Notification(msg_dict, self._imgur, has_fetched=True) for msg_dict in result]
[ "def", "get_messages", "(", "self", ",", "new", "=", "True", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/notifications/\"", "\"messages\"", ".", "format", "(", "self", ".", "name", ")", ")", "result", "=", "...
Return all messages sent to this user, formatted as a notification. :param new: False for all notifications, True for only non-viewed notifications.
[ "Return", "all", "messages", "sent", "to", "this", "user", "formatted", "as", "a", "notification", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1350-L1362
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_notifications
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_auth=True) msgs = [Message(msg_dict, self._imgur, has_fetched=True) for msg_dict in resp['messages']] replies = [Comment(com_dict, self._imgur, has_fetched=True) for com_dict in resp['replies']] return {'messages': msgs, 'replies': replies}
python
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_auth=True) msgs = [Message(msg_dict, self._imgur, has_fetched=True) for msg_dict in resp['messages']] replies = [Comment(com_dict, self._imgur, has_fetched=True) for com_dict in resp['replies']] return {'messages': msgs, 'replies': replies}
[ "def", "get_notifications", "(", "self", ",", "new", "=", "True", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/\"", "\"notifications\"", ".", "format", "(", "self", ".", "name", ")", ")", "resp", "=", "self",...
Return all the notifications for this user.
[ "Return", "all", "the", "notifications", "for", "this", "user", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1364-L1373
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_replies
def get_replies(self, new=True): """ Return all reply notifications for this user. :param new: False for all notifications, True for only non-viewed notifications. """ url = (self._imgur._base_url + "/3/account/{0}/" "notifications/replies".format(self.name)) return self._imgur._send_request(url, needs_auth=True)
python
def get_replies(self, new=True): """ Return all reply notifications for this user. :param new: False for all notifications, True for only non-viewed notifications. """ url = (self._imgur._base_url + "/3/account/{0}/" "notifications/replies".format(self.name)) return self._imgur._send_request(url, needs_auth=True)
[ "def", "get_replies", "(", "self", ",", "new", "=", "True", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/\"", "\"notifications/replies\"", ".", "format", "(", "self", ".", "name", ")", ")", "return", "self", ...
Return all reply notifications for this user. :param new: False for all notifications, True for only non-viewed notifications.
[ "Return", "all", "reply", "notifications", "for", "this", "user", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1375-L1384
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_settings
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._imgur._send_request(url)
python
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._imgur._send_request(url)
[ "def", "get_settings", "(", "self", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/settings\"", ".", "format", "(", "self", ".", "name", ")", "return", "self", ".", "_imgur", ".", "_send_request", "(", "url", ")" ]
Returns current settings. Only accessible if authenticated as the user.
[ "Returns", "current", "settings", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1386-L1393
train
Damgaard/PyImgur
pyimgur/__init__.py
User.get_submissions
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._imgur._send_request(url, limit=limit) return [_get_album_or_image(thing, self._imgur) for thing in resp]
python
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._imgur._send_request(url, limit=limit) return [_get_album_or_image(thing, self._imgur) for thing in resp]
[ "def", "get_submissions", "(", "self", ",", "limit", "=", "None", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}/submissions/\"", "\"{1}\"", ".", "format", "(", "self", ".", "name", ",", "'{}'", ")", ")", "resp...
Return a list of the images a user has submitted to the gallery.
[ "Return", "a", "list", "of", "the", "images", "a", "user", "has", "submitted", "to", "the", "gallery", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1400-L1405
train
Damgaard/PyImgur
pyimgur/__init__.py
User.send_message
def send_message(self, body, subject=None, reply_to=None): """ 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 either be replies to other messages or start a new message thread. If this is None it will start a new message thread. If it's a Message object or message_id, then the new message will be sent as a reply to the reply_to message. """ url = self._imgur._base_url + "/3/message" parent_id = reply_to.id if isinstance(reply_to, Message) else reply_to payload = {'recipient': self.name, 'body': body, 'subject': subject, 'parent_id': parent_id} self._imgur._send_request(url, params=payload, needs_auth=True, method='POST')
python
def send_message(self, body, subject=None, reply_to=None): """ 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 either be replies to other messages or start a new message thread. If this is None it will start a new message thread. If it's a Message object or message_id, then the new message will be sent as a reply to the reply_to message. """ url = self._imgur._base_url + "/3/message" parent_id = reply_to.id if isinstance(reply_to, Message) else reply_to payload = {'recipient': self.name, 'body': body, 'subject': subject, 'parent_id': parent_id} self._imgur._send_request(url, params=payload, needs_auth=True, method='POST')
[ "def", "send_message", "(", "self", ",", "body", ",", "subject", "=", "None", ",", "reply_to", "=", "None", ")", ":", "url", "=", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/message\"", "parent_id", "=", "reply_to", ".", "id", "if", "isinstance",...
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 either be replies to other messages or start a new message thread. If this is None it will start a new message thread. If it's a Message object or message_id, then the new message will be sent as a reply to the reply_to message.
[ "Send", "a", "message", "to", "this", "user", "from", "the", "logged", "in", "user", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1407-L1425
train
Damgaard/PyImgur
pyimgur/__init__.py
User.send_verification_email
def send_verification_email(self): """ Send verification email to this users email address. Remember that the verification email may end up in the users spam folder. """ url = (self._imgur._base_url + "/3/account/{0}" "/verifyemail".format(self.name)) self._imgur._send_request(url, needs_auth=True, method='POST')
python
def send_verification_email(self): """ Send verification email to this users email address. Remember that the verification email may end up in the users spam folder. """ url = (self._imgur._base_url + "/3/account/{0}" "/verifyemail".format(self.name)) self._imgur._send_request(url, needs_auth=True, method='POST')
[ "def", "send_verification_email", "(", "self", ")", ":", "url", "=", "(", "self", ".", "_imgur", ".", "_base_url", "+", "\"/3/account/{0}\"", "\"/verifyemail\"", ".", "format", "(", "self", ".", "name", ")", ")", "self", ".", "_imgur", ".", "_send_request", ...
Send verification email to this users email address. Remember that the verification email may end up in the users spam folder.
[ "Send", "verification", "email", "to", "this", "users", "email", "address", "." ]
606f17078d24158632f807430f8d0b9b3cd8b312
https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/__init__.py#L1427-L1436
train
nir0s/backtrace
backtrace.py
hook
def hook(reverse=False, align=False, strip_path=False, enable_on_envvar_only=False, on_tty=False, conservative=False, styles=None, tb=None, tpe=None, value=None): """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 environment variable `ENABLE_BACKTRACE` is set, backtrace will be activated. If `on_tty` is True, backtrace will be activated only if you're running in a readl terminal (i.e. not piped, redirected, etc..). If `convervative` is True, the traceback will have more seemingly original style (There will be no alignment by default, 'File', 'line' and 'in' prefixes and will ignore any styling provided by the user.) See https://github.com/nir0s/backtrace/blob/master/README.md for information on `styles`. """ if enable_on_envvar_only and 'ENABLE_BACKTRACE' not in os.environ: return isatty = getattr(sys.stderr, 'isatty', lambda: False) if on_tty and not isatty(): return if conservative: styles = CONVERVATIVE_STYLES align = align or False elif styles: for k in STYLES.keys(): styles[k] = styles.get(k, STYLES[k]) else: styles = STYLES # For Windows colorama.init() def backtrace_excepthook(tpe, value, tb=None): # Don't know if we're getting traceback or traceback entries. # We'll try to parse a traceback object. try: traceback_entries = traceback.extract_tb(tb) except AttributeError: traceback_entries = tb parser = _Hook(traceback_entries, align, strip_path, conservative) tpe = tpe if isinstance(tpe, str) else tpe.__name__ tb_message = styles['backtrace'].format('Traceback ({0}):'.format( 'Most recent call ' + ('first' if reverse else 'last'))) + \ Style.RESET_ALL err_message = styles['error'].format(tpe + ': ' + str(value)) + \ Style.RESET_ALL if reverse: parser.reverse() _flush(tb_message) backtrace = parser.generate_backtrace(styles) backtrace.insert(0 if reverse else len(backtrace), err_message) for entry in backtrace: _flush(entry) if tb: backtrace_excepthook(tpe=tpe, value=value, tb=tb) else: sys.excepthook = backtrace_excepthook
python
def hook(reverse=False, align=False, strip_path=False, enable_on_envvar_only=False, on_tty=False, conservative=False, styles=None, tb=None, tpe=None, value=None): """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 environment variable `ENABLE_BACKTRACE` is set, backtrace will be activated. If `on_tty` is True, backtrace will be activated only if you're running in a readl terminal (i.e. not piped, redirected, etc..). If `convervative` is True, the traceback will have more seemingly original style (There will be no alignment by default, 'File', 'line' and 'in' prefixes and will ignore any styling provided by the user.) See https://github.com/nir0s/backtrace/blob/master/README.md for information on `styles`. """ if enable_on_envvar_only and 'ENABLE_BACKTRACE' not in os.environ: return isatty = getattr(sys.stderr, 'isatty', lambda: False) if on_tty and not isatty(): return if conservative: styles = CONVERVATIVE_STYLES align = align or False elif styles: for k in STYLES.keys(): styles[k] = styles.get(k, STYLES[k]) else: styles = STYLES # For Windows colorama.init() def backtrace_excepthook(tpe, value, tb=None): # Don't know if we're getting traceback or traceback entries. # We'll try to parse a traceback object. try: traceback_entries = traceback.extract_tb(tb) except AttributeError: traceback_entries = tb parser = _Hook(traceback_entries, align, strip_path, conservative) tpe = tpe if isinstance(tpe, str) else tpe.__name__ tb_message = styles['backtrace'].format('Traceback ({0}):'.format( 'Most recent call ' + ('first' if reverse else 'last'))) + \ Style.RESET_ALL err_message = styles['error'].format(tpe + ': ' + str(value)) + \ Style.RESET_ALL if reverse: parser.reverse() _flush(tb_message) backtrace = parser.generate_backtrace(styles) backtrace.insert(0 if reverse else len(backtrace), err_message) for entry in backtrace: _flush(entry) if tb: backtrace_excepthook(tpe=tpe, value=value, tb=tb) else: sys.excepthook = backtrace_excepthook
[ "def", "hook", "(", "reverse", "=", "False", ",", "align", "=", "False", ",", "strip_path", "=", "False", ",", "enable_on_envvar_only", "=", "False", ",", "on_tty", "=", "False", ",", "conservative", "=", "False", ",", "styles", "=", "None", ",", "tb", ...
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 environment variable `ENABLE_BACKTRACE` is set, backtrace will be activated. If `on_tty` is True, backtrace will be activated only if you're running in a readl terminal (i.e. not piped, redirected, etc..). If `convervative` is True, the traceback will have more seemingly original style (There will be no alignment by default, 'File', 'line' and 'in' prefixes and will ignore any styling provided by the user.) See https://github.com/nir0s/backtrace/blob/master/README.md for information on `styles`.
[ "Hook", "the", "current", "excepthook", "to", "the", "backtrace", "." ]
a1f75c956f669a6175088693802d5392e6bd7e51
https://github.com/nir0s/backtrace/blob/a1f75c956f669a6175088693802d5392e6bd7e51/backtrace.py#L108-L186
train
nir0s/backtrace
backtrace.py
_extract_traceback
def _extract_traceback(text): """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't handled, only the reraise. Each of the traceback lines are then handled two lines at a time for each stack object. Note that all parts of each stack object are stripped from newlines and spaces to keep the output clean. """ capture = False entries = [] all_else = [] ignore_trace = False # In python 3, a traceback may includes output from a reraise. # e.g, an exception is captured and reraised with another exception. # This marks that we should ignore if text.count(TRACEBACK_IDENTIFIER) == 2: ignore_trace = True for index, line in enumerate(text): if TRACEBACK_IDENTIFIER in line: if ignore_trace: ignore_trace = False continue capture = True # We're not capturing and making sure we only read lines # with spaces since, after the initial identifier, all traceback lines # contain a prefix spacing. elif capture and line.startswith(' '): if index % 2 == 0: # Line containing a file, line and module. line = line.strip().strip('\n') next_line = text[index + 1].strip('\n') entries.append(line + ', ' + next_line) elif capture: # Line containing the module call. entries.append(line) break else: # Add everything else after the traceback. all_else.append(line) traceback_entries = [] # Build the traceback structure later passed for formatting. for index, line in enumerate(entries[:-2]): # TODO: This should be done in a _parse_entry function element = line.split(',') element[0] = element[0].strip().lstrip('File').strip(' "') element[1] = element[1].strip().lstrip('line').strip() element[2] = element[2].strip().lstrip('in').strip() traceback_entries.append(tuple(element)) return traceback_entries, all_else
python
def _extract_traceback(text): """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't handled, only the reraise. Each of the traceback lines are then handled two lines at a time for each stack object. Note that all parts of each stack object are stripped from newlines and spaces to keep the output clean. """ capture = False entries = [] all_else = [] ignore_trace = False # In python 3, a traceback may includes output from a reraise. # e.g, an exception is captured and reraised with another exception. # This marks that we should ignore if text.count(TRACEBACK_IDENTIFIER) == 2: ignore_trace = True for index, line in enumerate(text): if TRACEBACK_IDENTIFIER in line: if ignore_trace: ignore_trace = False continue capture = True # We're not capturing and making sure we only read lines # with spaces since, after the initial identifier, all traceback lines # contain a prefix spacing. elif capture and line.startswith(' '): if index % 2 == 0: # Line containing a file, line and module. line = line.strip().strip('\n') next_line = text[index + 1].strip('\n') entries.append(line + ', ' + next_line) elif capture: # Line containing the module call. entries.append(line) break else: # Add everything else after the traceback. all_else.append(line) traceback_entries = [] # Build the traceback structure later passed for formatting. for index, line in enumerate(entries[:-2]): # TODO: This should be done in a _parse_entry function element = line.split(',') element[0] = element[0].strip().lstrip('File').strip(' "') element[1] = element[1].strip().lstrip('line').strip() element[2] = element[2].strip().lstrip('in').strip() traceback_entries.append(tuple(element)) return traceback_entries, all_else
[ "def", "_extract_traceback", "(", "text", ")", ":", "capture", "=", "False", "entries", "=", "[", "]", "all_else", "=", "[", "]", "ignore_trace", "=", "False", "# In python 3, a traceback may includes output from a reraise.", "# e.g, an exception is captured and reraised wi...
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't handled, only the reraise. Each of the traceback lines are then handled two lines at a time for each stack object. Note that all parts of each stack object are stripped from newlines and spaces to keep the output clean.
[ "Receive", "a", "list", "of", "strings", "representing", "the", "input", "from", "stdin", "and", "return", "the", "restructured", "backtrace", "." ]
a1f75c956f669a6175088693802d5392e6bd7e51
https://github.com/nir0s/backtrace/blob/a1f75c956f669a6175088693802d5392e6bd7e51/backtrace.py#L195-L254
train
nir0s/backtrace
backtrace.py
_Hook.generate_backtrace
def generate_backtrace(self, styles): """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? """ backtrace = [] for entry in self.entries: backtrace.append(self.rebuild_entry(entry, styles)) # Get the lenght of the longest string for each field of an entry lengths = self.align_all(backtrace) if self.align else [1, 1, 1, 1] aligned_backtrace = [] for entry in backtrace: aligned_backtrace.append(self.align_entry(entry, lengths)) return aligned_backtrace
python
def generate_backtrace(self, styles): """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? """ backtrace = [] for entry in self.entries: backtrace.append(self.rebuild_entry(entry, styles)) # Get the lenght of the longest string for each field of an entry lengths = self.align_all(backtrace) if self.align else [1, 1, 1, 1] aligned_backtrace = [] for entry in backtrace: aligned_backtrace.append(self.align_entry(entry, lengths)) return aligned_backtrace
[ "def", "generate_backtrace", "(", "self", ",", "styles", ")", ":", "backtrace", "=", "[", "]", "for", "entry", "in", "self", ".", "entries", ":", "backtrace", ".", "append", "(", "self", ".", "rebuild_entry", "(", "entry", ",", "styles", ")", ")", "# G...
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?
[ "Return", "the", "(", "potentially", ")", "aligned", "rebuit", "traceback" ]
a1f75c956f669a6175088693802d5392e6bd7e51
https://github.com/nir0s/backtrace/blob/a1f75c956f669a6175088693802d5392e6bd7e51/backtrace.py#L88-L105
train
PaulHancock/Aegean
AegeanTools/models.py
classify_catalog
def classify_catalog(catalog): """ 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 : list List of sources of type OutputSource islands : list List of sources of type IslandSource simples : list List of source of type SimpleSource """ components = [] islands = [] simples = [] for source in catalog: if isinstance(source, OutputSource): components.append(source) elif isinstance(source, IslandSource): islands.append(source) elif isinstance(source, SimpleSource): simples.append(source) return components, islands, simples
python
def classify_catalog(catalog): """ 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 : list List of sources of type OutputSource islands : list List of sources of type IslandSource simples : list List of source of type SimpleSource """ components = [] islands = [] simples = [] for source in catalog: if isinstance(source, OutputSource): components.append(source) elif isinstance(source, IslandSource): islands.append(source) elif isinstance(source, SimpleSource): simples.append(source) return components, islands, simples
[ "def", "classify_catalog", "(", "catalog", ")", ":", "components", "=", "[", "]", "islands", "=", "[", "]", "simples", "=", "[", "]", "for", "source", "in", "catalog", ":", "if", "isinstance", "(", "source", ",", "OutputSource", ")", ":", "components", ...
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 : list List of sources of type OutputSource islands : list List of sources of type IslandSource simples : list List of source of type SimpleSource
[ "Look", "at", "a", "list", "of", "sources", "and", "split", "them", "according", "to", "their", "class", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/models.py#L520-L551
train
PaulHancock/Aegean
AegeanTools/models.py
island_itergen
def island_itergen(catalog): """ 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 A list of all sources within an island, one island at a time. """ # reverse sort so that we can pop the last elements and get an increasing island number catalog = sorted(catalog) catalog.reverse() group = [] # using pop and keeping track of the list length ourselves is faster than # constantly asking for len(catalog) src = catalog.pop() c_len = len(catalog) isle_num = src.island while c_len >= 0: if src.island == isle_num: group.append(src) c_len -= 1 if c_len <0: # we have just added the last item from the catalog # and there are no more to pop yield group else: src = catalog.pop() else: isle_num += 1 # maybe there are no sources in this island so skip it if group == []: continue yield group group = [] return
python
def island_itergen(catalog): """ 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 A list of all sources within an island, one island at a time. """ # reverse sort so that we can pop the last elements and get an increasing island number catalog = sorted(catalog) catalog.reverse() group = [] # using pop and keeping track of the list length ourselves is faster than # constantly asking for len(catalog) src = catalog.pop() c_len = len(catalog) isle_num = src.island while c_len >= 0: if src.island == isle_num: group.append(src) c_len -= 1 if c_len <0: # we have just added the last item from the catalog # and there are no more to pop yield group else: src = catalog.pop() else: isle_num += 1 # maybe there are no sources in this island so skip it if group == []: continue yield group group = [] return
[ "def", "island_itergen", "(", "catalog", ")", ":", "# reverse sort so that we can pop the last elements and get an increasing island number", "catalog", "=", "sorted", "(", "catalog", ")", "catalog", ".", "reverse", "(", ")", "group", "=", "[", "]", "# using pop and keepi...
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 A list of all sources within an island, one island at a time.
[ "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" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/models.py#L554-L597
train
PaulHancock/Aegean
AegeanTools/models.py
SimpleSource._sanitise
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.float32): # np.float32 has a broken __str__ method self.__dict__[k] = np.float64(self.__dict__[k])
python
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.float32): # np.float32 has a broken __str__ method self.__dict__[k] = np.float64(self.__dict__[k])
[ "def", "_sanitise", "(", "self", ")", ":", "for", "k", "in", "self", ".", "__dict__", ":", "if", "isinstance", "(", "self", ".", "__dict__", "[", "k", "]", ",", "np", ".", "float32", ")", ":", "# np.float32 has a broken __str__ method", "self", ".", "__d...
Convert attributes of type npumpy.float32 to numpy.float64 so that they will print properly.
[ "Convert", "attributes", "of", "type", "npumpy", ".", "float32", "to", "numpy", ".", "float64", "so", "that", "they", "will", "print", "properly", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/models.py#L74-L80
train
PaulHancock/Aegean
AegeanTools/models.py
SimpleSource.as_list
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
python
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
[ "def", "as_list", "(", "self", ")", ":", "self", ".", "_sanitise", "(", ")", "l", "=", "[", "]", "for", "name", "in", "self", ".", "names", ":", "l", ".", "append", "(", "getattr", "(", "self", ",", "name", ")", ")", "return", "l" ]
Return an *ordered* list of the source attributes
[ "Return", "an", "*", "ordered", "*", "list", "of", "the", "source", "attributes" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/models.py#L89-L97
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.add_circles
def add_circles(self, ra_cen, dec_cen, radius, depth=None): """ 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. """ if depth is None or depth > self.maxdepth: depth = self.maxdepth try: sky = list(zip(ra_cen, dec_cen)) rad = radius except TypeError: sky = [[ra_cen, dec_cen]] rad = [radius] sky = np.array(sky) rad = np.array(rad) vectors = self.sky2vec(sky) for vec, r in zip(vectors, rad): pix = hp.query_disc(2**depth, vec, r, inclusive=True, nest=True) self.add_pixels(pix, depth) self._renorm() return
python
def add_circles(self, ra_cen, dec_cen, radius, depth=None): """ 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. """ if depth is None or depth > self.maxdepth: depth = self.maxdepth try: sky = list(zip(ra_cen, dec_cen)) rad = radius except TypeError: sky = [[ra_cen, dec_cen]] rad = [radius] sky = np.array(sky) rad = np.array(rad) vectors = self.sky2vec(sky) for vec, r in zip(vectors, rad): pix = hp.query_disc(2**depth, vec, r, inclusive=True, nest=True) self.add_pixels(pix, depth) self._renorm() return
[ "def", "add_circles", "(", "self", ",", "ra_cen", ",", "dec_cen", ",", "radius", ",", "depth", "=", "None", ")", ":", "if", "depth", "is", "None", "or", "depth", ">", "self", ".", "maxdepth", ":", "depth", "=", "self", ".", "maxdepth", "try", ":", ...
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.
[ "Add", "one", "or", "more", "circles", "to", "this", "region" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L83-L111
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.add_poly
def add_poly(self, positions, depth=None): """ 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. """ if not (len(positions) >= 3): raise AssertionError("A minimum of three coordinate pairs are required") if depth is None or depth > self.maxdepth: depth = self.maxdepth ras, decs = np.array(list(zip(*positions))) sky = self.radec2sky(ras, decs) pix = hp.query_polygon(2**depth, self.sky2vec(sky), inclusive=True, nest=True) self.add_pixels(pix, depth) self._renorm() return
python
def add_poly(self, positions, depth=None): """ 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. """ if not (len(positions) >= 3): raise AssertionError("A minimum of three coordinate pairs are required") if depth is None or depth > self.maxdepth: depth = self.maxdepth ras, decs = np.array(list(zip(*positions))) sky = self.radec2sky(ras, decs) pix = hp.query_polygon(2**depth, self.sky2vec(sky), inclusive=True, nest=True) self.add_pixels(pix, depth) self._renorm() return
[ "def", "add_poly", "(", "self", ",", "positions", ",", "depth", "=", "None", ")", ":", "if", "not", "(", "len", "(", "positions", ")", ">=", "3", ")", ":", "raise", "AssertionError", "(", "\"A minimum of three coordinate pairs are required\"", ")", "if", "de...
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.
[ "Add", "a", "single", "polygon", "to", "this", "region", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L113-L135
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.add_pixels
def add_pixels(self, pix, depth): """ 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. """ if depth not in self.pixeldict: self.pixeldict[depth] = set() self.pixeldict[depth].update(set(pix))
python
def add_pixels(self, pix, depth): """ 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. """ if depth not in self.pixeldict: self.pixeldict[depth] = set() self.pixeldict[depth].update(set(pix))
[ "def", "add_pixels", "(", "self", ",", "pix", ",", "depth", ")", ":", "if", "depth", "not", "in", "self", ".", "pixeldict", ":", "self", ".", "pixeldict", "[", "depth", "]", "=", "set", "(", ")", "self", ".", "pixeldict", "[", "depth", "]", ".", ...
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.
[ "Add", "one", "or", "more", "HEALPix", "pixels", "to", "this", "region", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L137-L151
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.get_area
def get_area(self, degrees=True): """ 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. """ area = 0 for d in range(1, self.maxdepth+1): area += len(self.pixeldict[d])*hp.nside2pixarea(2**d, degrees=degrees) return area
python
def get_area(self, degrees=True): """ 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. """ area = 0 for d in range(1, self.maxdepth+1): area += len(self.pixeldict[d])*hp.nside2pixarea(2**d, degrees=degrees) return area
[ "def", "get_area", "(", "self", ",", "degrees", "=", "True", ")", ":", "area", "=", "0", "for", "d", "in", "range", "(", "1", ",", "self", ".", "maxdepth", "+", "1", ")", ":", "area", "+=", "len", "(", "self", ".", "pixeldict", "[", "d", "]", ...
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.
[ "Calculate", "the", "total", "area", "represented", "by", "this", "region", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L153-L171
train
PaulHancock/Aegean
AegeanTools/regions.py
Region._demote_all
def _demote_all(self): """ 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. """ # only do the calculations if the demoted list is empty if len(self.demoted) == 0: pd = self.pixeldict for d in range(1, self.maxdepth): for p in pd[d]: pd[d+1].update(set((4*p, 4*p+1, 4*p+2, 4*p+3))) pd[d] = set() # clear the pixels from this level self.demoted = pd[d+1] return
python
def _demote_all(self): """ 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. """ # only do the calculations if the demoted list is empty if len(self.demoted) == 0: pd = self.pixeldict for d in range(1, self.maxdepth): for p in pd[d]: pd[d+1].update(set((4*p, 4*p+1, 4*p+2, 4*p+3))) pd[d] = set() # clear the pixels from this level self.demoted = pd[d+1] return
[ "def", "_demote_all", "(", "self", ")", ":", "# only do the calculations if the demoted list is empty", "if", "len", "(", "self", ".", "demoted", ")", "==", "0", ":", "pd", "=", "self", ".", "pixeldict", "for", "d", "in", "range", "(", "1", ",", "self", "....
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.
[ "Convert", "the", "multi", "-", "depth", "pixeldict", "into", "a", "single", "set", "of", "pixels", "at", "the", "deepest", "layer", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L185-L199
train
PaulHancock/Aegean
AegeanTools/regions.py
Region._renorm
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 lowest level self._demote_all() # now promote as needed for d in range(self.maxdepth, 2, -1): plist = self.pixeldict[d].copy() for p in plist: if p % 4 == 0: nset = set((p, p+1, p+2, p+3)) if p+1 in plist and p+2 in plist and p+3 in plist: # remove the four pixels from this level self.pixeldict[d].difference_update(nset) # add a new pixel to the next level up self.pixeldict[d-1].add(p/4) self.demoted = set() return
python
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 lowest level self._demote_all() # now promote as needed for d in range(self.maxdepth, 2, -1): plist = self.pixeldict[d].copy() for p in plist: if p % 4 == 0: nset = set((p, p+1, p+2, p+3)) if p+1 in plist and p+2 in plist and p+3 in plist: # remove the four pixels from this level self.pixeldict[d].difference_update(nset) # add a new pixel to the next level up self.pixeldict[d-1].add(p/4) self.demoted = set() return
[ "def", "_renorm", "(", "self", ")", ":", "self", ".", "demoted", "=", "set", "(", ")", "# convert all to lowest level", "self", ".", "_demote_all", "(", ")", "# now promote as needed", "for", "d", "in", "range", "(", "self", ".", "maxdepth", ",", "2", ",",...
Remake the pixel dictionary, merging groups of pixels at level N into a single pixel at level N-1
[ "Remake", "the", "pixel", "dictionary", "merging", "groups", "of", "pixels", "at", "level", "N", "into", "a", "single", "pixel", "at", "level", "N", "-", "1" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L201-L221
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.sky_within
def sky_within(self, ra, dec, degin=False): """ 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 : bool True if the given position is within one of the region's pixels. """ sky = self.radec2sky(ra, dec) if degin: sky = np.radians(sky) theta_phi = self.sky2ang(sky) # Set values that are nan to be zero and record a mask mask = np.bitwise_not(np.logical_and.reduce(np.isfinite(theta_phi), axis=1)) theta_phi[mask, :] = 0 theta, phi = theta_phi.transpose() pix = hp.ang2pix(2**self.maxdepth, theta, phi, nest=True) pixelset = self.get_demoted() result = np.in1d(pix, list(pixelset)) # apply the mask and set the shonky values to False result[mask] = False return result
python
def sky_within(self, ra, dec, degin=False): """ 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 : bool True if the given position is within one of the region's pixels. """ sky = self.radec2sky(ra, dec) if degin: sky = np.radians(sky) theta_phi = self.sky2ang(sky) # Set values that are nan to be zero and record a mask mask = np.bitwise_not(np.logical_and.reduce(np.isfinite(theta_phi), axis=1)) theta_phi[mask, :] = 0 theta, phi = theta_phi.transpose() pix = hp.ang2pix(2**self.maxdepth, theta, phi, nest=True) pixelset = self.get_demoted() result = np.in1d(pix, list(pixelset)) # apply the mask and set the shonky values to False result[mask] = False return result
[ "def", "sky_within", "(", "self", ",", "ra", ",", "dec", ",", "degin", "=", "False", ")", ":", "sky", "=", "self", ".", "radec2sky", "(", "ra", ",", "dec", ")", "if", "degin", ":", "sky", "=", "np", ".", "radians", "(", "sky", ")", "theta_phi", ...
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 : bool True if the given position is within one of the region's pixels.
[ "Test", "whether", "a", "sky", "position", "is", "within", "this", "region" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L223-L257
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.union
def union(self, other, renorm=True): """ 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. """ # merge the pixels that are common to both for d in range(1, min(self.maxdepth, other.maxdepth)+1): self.add_pixels(other.pixeldict[d], d) # if the other region is at higher resolution, then include a degraded version of the remaining pixels. if self.maxdepth < other.maxdepth: for d in range(self.maxdepth+1, other.maxdepth+1): for p in other.pixeldict[d]: # promote this pixel to self.maxdepth pp = p/4**(d-self.maxdepth) self.pixeldict[self.maxdepth].add(pp) if renorm: self._renorm() return
python
def union(self, other, renorm=True): """ 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. """ # merge the pixels that are common to both for d in range(1, min(self.maxdepth, other.maxdepth)+1): self.add_pixels(other.pixeldict[d], d) # if the other region is at higher resolution, then include a degraded version of the remaining pixels. if self.maxdepth < other.maxdepth: for d in range(self.maxdepth+1, other.maxdepth+1): for p in other.pixeldict[d]: # promote this pixel to self.maxdepth pp = p/4**(d-self.maxdepth) self.pixeldict[self.maxdepth].add(pp) if renorm: self._renorm() return
[ "def", "union", "(", "self", ",", "other", ",", "renorm", "=", "True", ")", ":", "# merge the pixels that are common to both", "for", "d", "in", "range", "(", "1", ",", "min", "(", "self", ".", "maxdepth", ",", "other", ".", "maxdepth", ")", "+", "1", ...
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.
[ "Add", "another", "Region", "by", "performing", "union", "on", "their", "pixlists", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L259-L285
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.without
def without(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. """ # work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].difference_update(opd) self._renorm() return
python
def without(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. """ # work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].difference_update(opd) self._renorm() return
[ "def", "without", "(", "self", ",", "other", ")", ":", "# work only on the lowest level", "# TODO: Allow this to be done for regions with different depths.", "if", "not", "(", "self", ".", "maxdepth", "==", "other", ".", "maxdepth", ")", ":", "raise", "AssertionError", ...
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.
[ "Subtract", "another", "Region", "by", "performing", "a", "difference", "operation", "on", "their", "pixlists", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L287-L305
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.intersect
def intersect(self, other): """ 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. """ # work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].intersection_update(opd) self._renorm() return
python
def intersect(self, other): """ 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. """ # work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].intersection_update(opd) self._renorm() return
[ "def", "intersect", "(", "self", ",", "other", ")", ":", "# work only on the lowest level", "# TODO: Allow this to be done for regions with different depths.", "if", "not", "(", "self", ".", "maxdepth", "==", "other", ".", "maxdepth", ")", ":", "raise", "AssertionError"...
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.
[ "Combine", "with", "another", "Region", "by", "performing", "intersection", "on", "their", "pixlists", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L307-L325
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.symmetric_difference
def symmetric_difference(self, other): """ 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. """ # work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].symmetric_difference_update(opd) self._renorm() return
python
def symmetric_difference(self, other): """ 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. """ # work only on the lowest level # TODO: Allow this to be done for regions with different depths. if not (self.maxdepth == other.maxdepth): raise AssertionError("Regions must have the same maxdepth") self._demote_all() opd = set(other.get_demoted()) self.pixeldict[self.maxdepth].symmetric_difference_update(opd) self._renorm() return
[ "def", "symmetric_difference", "(", "self", ",", "other", ")", ":", "# work only on the lowest level", "# TODO: Allow this to be done for regions with different depths.", "if", "not", "(", "self", ".", "maxdepth", "==", "other", ".", "maxdepth", ")", ":", "raise", "Asse...
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.
[ "Combine", "with", "another", "Region", "by", "performing", "the", "symmetric", "difference", "of", "their", "pixlists", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L327-L345
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.write_reg
def write_reg(self, filename): """ Write a ds9 region file that represents this region as a set of diamonds. Parameters ---------- filename : str File to write """ with open(filename, 'w') as out: for d in range(1, self.maxdepth+1): for p in self.pixeldict[d]: line = "fk5; polygon(" # the following int() gets around some problems with np.int64 that exist prior to numpy v 1.8.1 vectors = list(zip(*hp.boundaries(2**d, int(p), step=1, nest=True))) positions = [] for sky in self.vec2sky(np.array(vectors), degrees=True): ra, dec = sky pos = SkyCoord(ra/15, dec, unit=(u.degree, u.degree)) positions.append(pos.ra.to_string(sep=':', precision=2)) positions.append(pos.dec.to_string(sep=':', precision=2)) line += ','.join(positions) line += ")" print(line, file=out) return
python
def write_reg(self, filename): """ Write a ds9 region file that represents this region as a set of diamonds. Parameters ---------- filename : str File to write """ with open(filename, 'w') as out: for d in range(1, self.maxdepth+1): for p in self.pixeldict[d]: line = "fk5; polygon(" # the following int() gets around some problems with np.int64 that exist prior to numpy v 1.8.1 vectors = list(zip(*hp.boundaries(2**d, int(p), step=1, nest=True))) positions = [] for sky in self.vec2sky(np.array(vectors), degrees=True): ra, dec = sky pos = SkyCoord(ra/15, dec, unit=(u.degree, u.degree)) positions.append(pos.ra.to_string(sep=':', precision=2)) positions.append(pos.dec.to_string(sep=':', precision=2)) line += ','.join(positions) line += ")" print(line, file=out) return
[ "def", "write_reg", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "out", ":", "for", "d", "in", "range", "(", "1", ",", "self", ".", "maxdepth", "+", "1", ")", ":", "for", "p", "in", "self", "."...
Write a ds9 region file that represents this region as a set of diamonds. Parameters ---------- filename : str File to write
[ "Write", "a", "ds9", "region", "file", "that", "represents", "this", "region", "as", "a", "set", "of", "diamonds", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L347-L371
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.write_fits
def write_fits(self, filename, moctool=''): """ 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 = '' """ datafile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'MOC.fits') hdulist = fits.open(datafile) cols = fits.Column(name='NPIX', array=self._uniq(), format='1K') tbhdu = fits.BinTableHDU.from_columns([cols]) hdulist[1] = tbhdu hdulist[1].header['PIXTYPE'] = ('HEALPIX ', 'HEALPix magic code') hdulist[1].header['ORDERING'] = ('NUNIQ ', 'NUNIQ coding method') hdulist[1].header['COORDSYS'] = ('C ', 'ICRS reference frame') hdulist[1].header['MOCORDER'] = (self.maxdepth, 'MOC resolution (best order)') hdulist[1].header['MOCTOOL'] = (moctool, 'Name of the MOC generator') hdulist[1].header['MOCTYPE'] = ('CATALOG', 'Source type (IMAGE or CATALOG)') hdulist[1].header['MOCID'] = (' ', 'Identifier of the collection') hdulist[1].header['ORIGIN'] = (' ', 'MOC origin') time = datetime.datetime.utcnow() hdulist[1].header['DATE'] = (datetime.datetime.strftime(time, format="%Y-%m-%dT%H:%m:%SZ"), 'MOC creation date') hdulist.writeto(filename, overwrite=True) return
python
def write_fits(self, filename, moctool=''): """ 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 = '' """ datafile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'MOC.fits') hdulist = fits.open(datafile) cols = fits.Column(name='NPIX', array=self._uniq(), format='1K') tbhdu = fits.BinTableHDU.from_columns([cols]) hdulist[1] = tbhdu hdulist[1].header['PIXTYPE'] = ('HEALPIX ', 'HEALPix magic code') hdulist[1].header['ORDERING'] = ('NUNIQ ', 'NUNIQ coding method') hdulist[1].header['COORDSYS'] = ('C ', 'ICRS reference frame') hdulist[1].header['MOCORDER'] = (self.maxdepth, 'MOC resolution (best order)') hdulist[1].header['MOCTOOL'] = (moctool, 'Name of the MOC generator') hdulist[1].header['MOCTYPE'] = ('CATALOG', 'Source type (IMAGE or CATALOG)') hdulist[1].header['MOCID'] = (' ', 'Identifier of the collection') hdulist[1].header['ORIGIN'] = (' ', 'MOC origin') time = datetime.datetime.utcnow() hdulist[1].header['DATE'] = (datetime.datetime.strftime(time, format="%Y-%m-%dT%H:%m:%SZ"), 'MOC creation date') hdulist.writeto(filename, overwrite=True) return
[ "def", "write_fits", "(", "self", ",", "filename", ",", "moctool", "=", "''", ")", ":", "datafile", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",...
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 = ''
[ "Write", "a", "fits", "file", "representing", "the", "MOC", "of", "this", "region", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L373-L402
train
PaulHancock/Aegean
AegeanTools/regions.py
Region._uniq
def _uniq(self): """ 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. """ pd = [] for d in range(1, self.maxdepth): pd.extend(map(lambda x: int(4**(d+1) + x), self.pixeldict[d])) return sorted(pd)
python
def _uniq(self): """ 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. """ pd = [] for d in range(1, self.maxdepth): pd.extend(map(lambda x: int(4**(d+1) + x), self.pixeldict[d])) return sorted(pd)
[ "def", "_uniq", "(", "self", ")", ":", "pd", "=", "[", "]", "for", "d", "in", "range", "(", "1", ",", "self", ".", "maxdepth", ")", ":", "pd", ".", "extend", "(", "map", "(", "lambda", "x", ":", "int", "(", "4", "**", "(", "d", "+", "1", ...
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.
[ "Create", "a", "list", "of", "all", "the", "pixels", "that", "cover", "this", "region", ".", "This", "list", "contains", "overlapping", "pixels", "of", "different", "orders", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L404-L417
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.radec2sky
def radec2sky(ra, dec): """ 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. """ try: sky = np.array(list(zip(ra, dec))) except TypeError: sky = np.array([(ra, dec)]) return sky
python
def radec2sky(ra, dec): """ 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. """ try: sky = np.array(list(zip(ra, dec))) except TypeError: sky = np.array([(ra, dec)]) return sky
[ "def", "radec2sky", "(", "ra", ",", "dec", ")", ":", "try", ":", "sky", "=", "np", ".", "array", "(", "list", "(", "zip", "(", "ra", ",", "dec", ")", ")", ")", "except", "TypeError", ":", "sky", "=", "np", ".", "array", "(", "[", "(", "ra", ...
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.
[ "Convert", "[", "ra", "]", "[", "dec", "]", "to", "[", "(", "ra", "[", "0", "]", "dec", "[", "0", "]", ")", "....", "]", "and", "also", "ra", "dec", "to", "[", "(", "ra", "dec", ")", "]", "if", "ra", "/", "dec", "are", "not", "iterable" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L420-L439
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.sky2ang
def sky2ang(sky): """ 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.array Array of (theta,phi) coordinates. """ try: theta_phi = sky.copy() except AttributeError as _: theta_phi = np.array(sky) theta_phi[:, [1, 0]] = theta_phi[:, [0, 1]] theta_phi[:, 0] = np.pi/2 - theta_phi[:, 0] # # force 0<=theta<=2pi # theta_phi[:, 0] -= 2*np.pi*(theta_phi[:, 0]//(2*np.pi)) # # and now -pi<=theta<=pi # theta_phi[:, 0] -= (theta_phi[:, 0] > np.pi)*2*np.pi return theta_phi
python
def sky2ang(sky): """ 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.array Array of (theta,phi) coordinates. """ try: theta_phi = sky.copy() except AttributeError as _: theta_phi = np.array(sky) theta_phi[:, [1, 0]] = theta_phi[:, [0, 1]] theta_phi[:, 0] = np.pi/2 - theta_phi[:, 0] # # force 0<=theta<=2pi # theta_phi[:, 0] -= 2*np.pi*(theta_phi[:, 0]//(2*np.pi)) # # and now -pi<=theta<=pi # theta_phi[:, 0] -= (theta_phi[:, 0] > np.pi)*2*np.pi return theta_phi
[ "def", "sky2ang", "(", "sky", ")", ":", "try", ":", "theta_phi", "=", "sky", ".", "copy", "(", ")", "except", "AttributeError", "as", "_", ":", "theta_phi", "=", "np", ".", "array", "(", "sky", ")", "theta_phi", "[", ":", ",", "[", "1", ",", "0",...
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.array Array of (theta,phi) coordinates.
[ "Convert", "ra", "dec", "coordinates", "to", "theta", "phi", "coordinates", "ra", "-", ">", "phi", "dec", "-", ">", "theta" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L442-L469
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.sky2vec
def sky2vec(cls, sky): """ 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 -------- :func:`AegeanTools.regions.Region.vec2sky` """ theta_phi = cls.sky2ang(sky) theta, phi = map(np.array, list(zip(*theta_phi))) vec = hp.ang2vec(theta, phi) return vec
python
def sky2vec(cls, sky): """ 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 -------- :func:`AegeanTools.regions.Region.vec2sky` """ theta_phi = cls.sky2ang(sky) theta, phi = map(np.array, list(zip(*theta_phi))) vec = hp.ang2vec(theta, phi) return vec
[ "def", "sky2vec", "(", "cls", ",", "sky", ")", ":", "theta_phi", "=", "cls", ".", "sky2ang", "(", "sky", ")", "theta", ",", "phi", "=", "map", "(", "np", ".", "array", ",", "list", "(", "zip", "(", "*", "theta_phi", ")", ")", ")", "vec", "=", ...
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 -------- :func:`AegeanTools.regions.Region.vec2sky`
[ "Convert", "sky", "positions", "in", "to", "3d", "-", "vectors", "on", "the", "unit", "sphere", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L472-L493
train
PaulHancock/Aegean
AegeanTools/regions.py
Region.vec2sky
def vec2sky(cls, vec, degrees=False): """ 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 -------- :func:`AegeanTools.regions.Region.sky2vec` """ theta, phi = hp.vec2ang(vec) ra = phi dec = np.pi/2-theta if degrees: ra = np.degrees(ra) dec = np.degrees(dec) return cls.radec2sky(ra, dec)
python
def vec2sky(cls, vec, degrees=False): """ 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 -------- :func:`AegeanTools.regions.Region.sky2vec` """ theta, phi = hp.vec2ang(vec) ra = phi dec = np.pi/2-theta if degrees: ra = np.degrees(ra) dec = np.degrees(dec) return cls.radec2sky(ra, dec)
[ "def", "vec2sky", "(", "cls", ",", "vec", ",", "degrees", "=", "False", ")", ":", "theta", ",", "phi", "=", "hp", ".", "vec2ang", "(", "vec", ")", "ra", "=", "phi", "dec", "=", "np", ".", "pi", "/", "2", "-", "theta", "if", "degrees", ":", "r...
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 -------- :func:`AegeanTools.regions.Region.sky2vec`
[ "Convert", "[", "x", "y", "z", "]", "vectors", "into", "sky", "coordinates", "ra", "dec" ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/regions.py#L496-L523
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.from_header
def from_header(cls, header, beam=None, lat=None): """ 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 None then one is constructed form the header. lat : float The latitude of the telescope. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object. """ try: wcs = pywcs.WCS(header, naxis=2) except: # TODO: figure out what error is being thrown wcs = pywcs.WCS(str(header), naxis=2) if beam is None: beam = get_beam(header) else: beam = beam if beam is None: logging.critical("Cannot determine beam information") _, pixscale = get_pixinfo(header) refpix = (header['CRPIX1'], header['CRPIX2']) return cls(wcs, beam, pixscale, refpix, lat)
python
def from_header(cls, header, beam=None, lat=None): """ 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 None then one is constructed form the header. lat : float The latitude of the telescope. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object. """ try: wcs = pywcs.WCS(header, naxis=2) except: # TODO: figure out what error is being thrown wcs = pywcs.WCS(str(header), naxis=2) if beam is None: beam = get_beam(header) else: beam = beam if beam is None: logging.critical("Cannot determine beam information") _, pixscale = get_pixinfo(header) refpix = (header['CRPIX1'], header['CRPIX2']) return cls(wcs, beam, pixscale, refpix, lat)
[ "def", "from_header", "(", "cls", ",", "header", ",", "beam", "=", "None", ",", "lat", "=", "None", ")", ":", "try", ":", "wcs", "=", "pywcs", ".", "WCS", "(", "header", ",", "naxis", "=", "2", ")", "except", ":", "# TODO: figure out what error is bein...
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 None then one is constructed form the header. lat : float The latitude of the telescope. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object.
[ "Create", "a", "new", "WCSHelper", "class", "from", "the", "given", "header", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L62-L97
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.from_file
def from_file(cls, filename, beam=None): """ 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. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object """ header = fits.getheader(filename) return cls.from_header(header, beam)
python
def from_file(cls, filename, beam=None): """ 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. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object """ header = fits.getheader(filename) return cls.from_header(header, beam)
[ "def", "from_file", "(", "cls", ",", "filename", ",", "beam", "=", "None", ")", ":", "header", "=", "fits", ".", "getheader", "(", "filename", ")", "return", "cls", ".", "from_header", "(", "header", ",", "beam", ")" ]
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. Returns ------- obj : :class:`AegeanTools.wcs_helpers.WCSHelper` A helper object
[ "Create", "a", "new", "WCSHelper", "class", "from", "a", "given", "fits", "file", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L100-L118
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.pix2sky
def pix2sky(self, pixel): """ 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 """ x, y = pixel # wcs and pyfits have oposite ideas of x/y return self.wcs.wcs_pix2world([[y, x]], 1)[0]
python
def pix2sky(self, pixel): """ 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 """ x, y = pixel # wcs and pyfits have oposite ideas of x/y return self.wcs.wcs_pix2world([[y, x]], 1)[0]
[ "def", "pix2sky", "(", "self", ",", "pixel", ")", ":", "x", ",", "y", "=", "pixel", "# wcs and pyfits have oposite ideas of x/y", "return", "self", ".", "wcs", ".", "wcs_pix2world", "(", "[", "[", "y", ",", "x", "]", "]", ",", "1", ")", "[", "0", "]"...
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
[ "Convert", "pixel", "coordinates", "into", "sky", "coordinates", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L120-L137
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.sky2pix
def sky2pix(self, pos): """ 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 """ pixel = self.wcs.wcs_world2pix([pos], 1) # wcs and pyfits have oposite ideas of x/y return [pixel[0][1], pixel[0][0]]
python
def sky2pix(self, pos): """ 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 """ pixel = self.wcs.wcs_world2pix([pos], 1) # wcs and pyfits have oposite ideas of x/y return [pixel[0][1], pixel[0][0]]
[ "def", "sky2pix", "(", "self", ",", "pos", ")", ":", "pixel", "=", "self", ".", "wcs", ".", "wcs_world2pix", "(", "[", "pos", "]", ",", "1", ")", "# wcs and pyfits have oposite ideas of x/y", "return", "[", "pixel", "[", "0", "]", "[", "1", "]", ",", ...
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
[ "Convert", "sky", "coordinates", "into", "pixel", "coordinates", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L139-L156
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.sky2pix_vec
def sky2pix_vec(self, pos, r, pa): """ 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 (degrees). pa : float The position angle of the vector (degrees). Returns ------- x, y : float The pixel coordinates of the origin. r, theta : float The magnitude (pixels) and angle (degrees) of the vector. """ ra, dec = pos x, y = self.sky2pix(pos) a = translate(ra, dec, r, pa) locations = self.sky2pix(a) x_off, y_off = locations a = np.sqrt((x - x_off) ** 2 + (y - y_off) ** 2) theta = np.degrees(np.arctan2((y_off - y), (x_off - x))) return x, y, a, theta
python
def sky2pix_vec(self, pos, r, pa): """ 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 (degrees). pa : float The position angle of the vector (degrees). Returns ------- x, y : float The pixel coordinates of the origin. r, theta : float The magnitude (pixels) and angle (degrees) of the vector. """ ra, dec = pos x, y = self.sky2pix(pos) a = translate(ra, dec, r, pa) locations = self.sky2pix(a) x_off, y_off = locations a = np.sqrt((x - x_off) ** 2 + (y - y_off) ** 2) theta = np.degrees(np.arctan2((y_off - y), (x_off - x))) return x, y, a, theta
[ "def", "sky2pix_vec", "(", "self", ",", "pos", ",", "r", ",", "pa", ")", ":", "ra", ",", "dec", "=", "pos", "x", ",", "y", "=", "self", ".", "sky2pix", "(", "pos", ")", "a", "=", "translate", "(", "ra", ",", "dec", ",", "r", ",", "pa", ")",...
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 (degrees). pa : float The position angle of the vector (degrees). Returns ------- x, y : float The pixel coordinates of the origin. r, theta : float The magnitude (pixels) and angle (degrees) of the vector.
[ "Convert", "a", "vector", "from", "sky", "to", "pixel", "coords", ".", "The", "vector", "has", "a", "magnitude", "angle", "and", "an", "origin", "on", "the", "sky", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L158-L189
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.pix2sky_vec
def pix2sky_vec(self, pixel, r, theta): """ 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 : float angle of vector in degrees Returns ------- ra, dec : float The (ra, dec) of the origin point (degrees). r, pa : float The magnitude and position angle of the vector (degrees). """ ra1, dec1 = self.pix2sky(pixel) x, y = pixel a = [x + r * np.cos(np.radians(theta)), y + r * np.sin(np.radians(theta))] locations = self.pix2sky(a) ra2, dec2 = locations a = gcd(ra1, dec1, ra2, dec2) pa = bear(ra1, dec1, ra2, dec2) return ra1, dec1, a, pa
python
def pix2sky_vec(self, pixel, r, theta): """ 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 : float angle of vector in degrees Returns ------- ra, dec : float The (ra, dec) of the origin point (degrees). r, pa : float The magnitude and position angle of the vector (degrees). """ ra1, dec1 = self.pix2sky(pixel) x, y = pixel a = [x + r * np.cos(np.radians(theta)), y + r * np.sin(np.radians(theta))] locations = self.pix2sky(a) ra2, dec2 = locations a = gcd(ra1, dec1, ra2, dec2) pa = bear(ra1, dec1, ra2, dec2) return ra1, dec1, a, pa
[ "def", "pix2sky_vec", "(", "self", ",", "pixel", ",", "r", ",", "theta", ")", ":", "ra1", ",", "dec1", "=", "self", ".", "pix2sky", "(", "pixel", ")", "x", ",", "y", "=", "pixel", "a", "=", "[", "x", "+", "r", "*", "np", ".", "cos", "(", "n...
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 : float angle of vector in degrees Returns ------- ra, dec : float The (ra, dec) of the origin point (degrees). r, pa : float The magnitude and position angle of the vector (degrees).
[ "Given", "and", "input", "position", "and", "vector", "in", "pixel", "coordinates", "calculate", "the", "equivalent", "position", "and", "vector", "in", "sky", "coordinates", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L191-L220
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.sky2pix_ellipse
def sky2pix_ellipse(self, pos, a, b, pa): """ 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 ------- x,y : float The (x, y) pixel coordinates of the ellipse center. sx, sy : float The major and minor axes (FWHM) in pixels. theta : float The rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis. """ ra, dec = pos x, y = self.sky2pix(pos) x_off, y_off = self.sky2pix(translate(ra, dec, a, pa)) sx = np.hypot((x - x_off), (y - y_off)) theta = np.arctan2((y_off - y), (x_off - x)) x_off, y_off = self.sky2pix(translate(ra, dec, b, pa - 90)) sy = np.hypot((x - x_off), (y - y_off)) theta2 = np.arctan2((y_off - y), (x_off - x)) - np.pi / 2 # The a/b vectors are perpendicular in sky space, but not always in pixel space # so we have to account for this by calculating the angle between the two vectors # and modifying the minor axis length defect = theta - theta2 sy *= abs(np.cos(defect)) return x, y, sx, sy, np.degrees(theta)
python
def sky2pix_ellipse(self, pos, a, b, pa): """ 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 ------- x,y : float The (x, y) pixel coordinates of the ellipse center. sx, sy : float The major and minor axes (FWHM) in pixels. theta : float The rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis. """ ra, dec = pos x, y = self.sky2pix(pos) x_off, y_off = self.sky2pix(translate(ra, dec, a, pa)) sx = np.hypot((x - x_off), (y - y_off)) theta = np.arctan2((y_off - y), (x_off - x)) x_off, y_off = self.sky2pix(translate(ra, dec, b, pa - 90)) sy = np.hypot((x - x_off), (y - y_off)) theta2 = np.arctan2((y_off - y), (x_off - x)) - np.pi / 2 # The a/b vectors are perpendicular in sky space, but not always in pixel space # so we have to account for this by calculating the angle between the two vectors # and modifying the minor axis length defect = theta - theta2 sy *= abs(np.cos(defect)) return x, y, sx, sy, np.degrees(theta)
[ "def", "sky2pix_ellipse", "(", "self", ",", "pos", ",", "a", ",", "b", ",", "pa", ")", ":", "ra", ",", "dec", "=", "pos", "x", ",", "y", "=", "self", ".", "sky2pix", "(", "pos", ")", "x_off", ",", "y_off", "=", "self", ".", "sky2pix", "(", "t...
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 ------- x,y : float The (x, y) pixel coordinates of the ellipse center. sx, sy : float The major and minor axes (FWHM) in pixels. theta : float The rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis.
[ "Convert", "an", "ellipse", "from", "sky", "to", "pixel", "coordinates", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L222-L261
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.pix2sky_ellipse
def pix2sky_ellipse(self, pixel, sx, sy, theta): """ 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 rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis. Returns ------- ra, dec : float The (ra, dec) coordinates of the center of the ellipse (degrees). a, b : float The semi-major and semi-minor axis of the ellipse (degrees). pa : float The position angle of the ellipse (degrees). """ ra, dec = self.pix2sky(pixel) x, y = pixel v_sx = [x + sx * np.cos(np.radians(theta)), y + sx * np.sin(np.radians(theta))] ra2, dec2 = self.pix2sky(v_sx) major = gcd(ra, dec, ra2, dec2) pa = bear(ra, dec, ra2, dec2) v_sy = [x + sy * np.cos(np.radians(theta - 90)), y + sy * np.sin(np.radians(theta - 90))] ra2, dec2 = self.pix2sky(v_sy) minor = gcd(ra, dec, ra2, dec2) pa2 = bear(ra, dec, ra2, dec2) - 90 # The a/b vectors are perpendicular in sky space, but not always in pixel space # so we have to account for this by calculating the angle between the two vectors # and modifying the minor axis length defect = pa - pa2 minor *= abs(np.cos(np.radians(defect))) return ra, dec, major, minor, pa
python
def pix2sky_ellipse(self, pixel, sx, sy, theta): """ 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 rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis. Returns ------- ra, dec : float The (ra, dec) coordinates of the center of the ellipse (degrees). a, b : float The semi-major and semi-minor axis of the ellipse (degrees). pa : float The position angle of the ellipse (degrees). """ ra, dec = self.pix2sky(pixel) x, y = pixel v_sx = [x + sx * np.cos(np.radians(theta)), y + sx * np.sin(np.radians(theta))] ra2, dec2 = self.pix2sky(v_sx) major = gcd(ra, dec, ra2, dec2) pa = bear(ra, dec, ra2, dec2) v_sy = [x + sy * np.cos(np.radians(theta - 90)), y + sy * np.sin(np.radians(theta - 90))] ra2, dec2 = self.pix2sky(v_sy) minor = gcd(ra, dec, ra2, dec2) pa2 = bear(ra, dec, ra2, dec2) - 90 # The a/b vectors are perpendicular in sky space, but not always in pixel space # so we have to account for this by calculating the angle between the two vectors # and modifying the minor axis length defect = pa - pa2 minor *= abs(np.cos(np.radians(defect))) return ra, dec, major, minor, pa
[ "def", "pix2sky_ellipse", "(", "self", ",", "pixel", ",", "sx", ",", "sy", ",", "theta", ")", ":", "ra", ",", "dec", "=", "self", ".", "pix2sky", "(", "pixel", ")", "x", ",", "y", "=", "pixel", "v_sx", "=", "[", "x", "+", "sx", "*", "np", "."...
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 rotation angle of the ellipse (degrees). theta = 0 corresponds to the ellipse being aligned with the x-axis. Returns ------- ra, dec : float The (ra, dec) coordinates of the center of the ellipse (degrees). a, b : float The semi-major and semi-minor axis of the ellipse (degrees). pa : float The position angle of the ellipse (degrees).
[ "Convert", "an", "ellipse", "from", "pixel", "to", "sky", "coordinates", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L263-L307
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.get_pixbeam_pixel
def get_pixbeam_pixel(self, x, y): """ 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/b/pa in pixel coordinates. """ ra, dec = self.pix2sky((x, y)) return self.get_pixbeam(ra, dec)
python
def get_pixbeam_pixel(self, x, y): """ 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/b/pa in pixel coordinates. """ ra, dec = self.pix2sky((x, y)) return self.get_pixbeam(ra, dec)
[ "def", "get_pixbeam_pixel", "(", "self", ",", "x", ",", "y", ")", ":", "ra", ",", "dec", "=", "self", ".", "pix2sky", "(", "(", "x", ",", "y", ")", ")", "return", "self", ".", "get_pixbeam", "(", "ra", ",", "dec", ")" ]
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/b/pa in pixel coordinates.
[ "Determine", "the", "beam", "in", "pixels", "at", "the", "given", "location", "in", "pixel", "coordinates", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L309-L324
train
PaulHancock/Aegean
AegeanTools/wcs_helpers.py
WCSHelper.get_beam
def get_beam(self, ra, dec): """ 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 """ # check to see if we need to scale the major axis based on the declination if self.lat is None: factor = 1 else: # this works if the pa is zero. For non-zero pa it's a little more difficult factor = np.cos(np.radians(dec - self.lat)) return Beam(self.beam.a / factor, self.beam.b, self.beam.pa)
python
def get_beam(self, ra, dec): """ 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 """ # check to see if we need to scale the major axis based on the declination if self.lat is None: factor = 1 else: # this works if the pa is zero. For non-zero pa it's a little more difficult factor = np.cos(np.radians(dec - self.lat)) return Beam(self.beam.a / factor, self.beam.b, self.beam.pa)
[ "def", "get_beam", "(", "self", ",", "ra", ",", "dec", ")", ":", "# check to see if we need to scale the major axis based on the declination", "if", "self", ".", "lat", "is", "None", ":", "factor", "=", "1", "else", ":", "# this works if the pa is zero. For non-zero pa ...
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
[ "Determine", "the", "beam", "at", "the", "given", "sky", "location", "." ]
185d2b4a51b48441a1df747efc9a5271c79399fd
https://github.com/PaulHancock/Aegean/blob/185d2b4a51b48441a1df747efc9a5271c79399fd/AegeanTools/wcs_helpers.py#L326-L346
train