repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
datadesk/python-documentcloud
documentcloud/__init__.py
ProjectClient.create
def create(self, title, description=None, document_ids=None): """ Creates a new project. Returns its unique identifer in documentcloud Example usage: >> documentcloud.projects.create("The Ruben Salazar Files") """ params = { 'title': title, } if description: params['description'] = description params = urllib.parse.urlencode(params, doseq=True) if document_ids: # These need to be specially formatted in the style documentcloud # expects arrays. The example they provide is: # ?document_ids[]=28-boumediene&document_ids[]=207-academy\ # &document_ids[]=30-insider-trading params += "".join([ '&document_ids[]=%s' % id for id in document_ids ]) response = self._make_request( self.BASE_URI + "projects.json", params.encode("utf-8") ) new_id = json.loads(response.decode("utf-8"))['project']['id'] # If it doesn't exist, that suggests the project already exists if not new_id: raise DuplicateObjectError("The Project title you tried to create \ already exists") # Fetch the actual project object from the API and return that. return self.get(new_id)
python
def create(self, title, description=None, document_ids=None): """ Creates a new project. Returns its unique identifer in documentcloud Example usage: >> documentcloud.projects.create("The Ruben Salazar Files") """ params = { 'title': title, } if description: params['description'] = description params = urllib.parse.urlencode(params, doseq=True) if document_ids: # These need to be specially formatted in the style documentcloud # expects arrays. The example they provide is: # ?document_ids[]=28-boumediene&document_ids[]=207-academy\ # &document_ids[]=30-insider-trading params += "".join([ '&document_ids[]=%s' % id for id in document_ids ]) response = self._make_request( self.BASE_URI + "projects.json", params.encode("utf-8") ) new_id = json.loads(response.decode("utf-8"))['project']['id'] # If it doesn't exist, that suggests the project already exists if not new_id: raise DuplicateObjectError("The Project title you tried to create \ already exists") # Fetch the actual project object from the API and return that. return self.get(new_id)
[ "def", "create", "(", "self", ",", "title", ",", "description", "=", "None", ",", "document_ids", "=", "None", ")", ":", "params", "=", "{", "'title'", ":", "title", ",", "}", "if", "description", ":", "params", "[", "'description'", "]", "=", "descrip...
Creates a new project. Returns its unique identifer in documentcloud Example usage: >> documentcloud.projects.create("The Ruben Salazar Files")
[ "Creates", "a", "new", "project", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L497-L532
train
33,600
datadesk/python-documentcloud
documentcloud/__init__.py
ProjectClient.get_or_create_by_title
def get_or_create_by_title(self, title): """ Fetch a title, if it exists. Create it if it doesn't. Returns a tuple with the object first, and then a boolean that indicates whether or not the object was created fresh. True means it's brand new. """ try: obj = self.get_by_title(title) created = False except DoesNotExistError: obj = self.create(title=title) created = True return obj, created
python
def get_or_create_by_title(self, title): """ Fetch a title, if it exists. Create it if it doesn't. Returns a tuple with the object first, and then a boolean that indicates whether or not the object was created fresh. True means it's brand new. """ try: obj = self.get_by_title(title) created = False except DoesNotExistError: obj = self.create(title=title) created = True return obj, created
[ "def", "get_or_create_by_title", "(", "self", ",", "title", ")", ":", "try", ":", "obj", "=", "self", ".", "get_by_title", "(", "title", ")", "created", "=", "False", "except", "DoesNotExistError", ":", "obj", "=", "self", ".", "create", "(", "title", "=...
Fetch a title, if it exists. Create it if it doesn't. Returns a tuple with the object first, and then a boolean that indicates whether or not the object was created fresh. True means it's brand new.
[ "Fetch", "a", "title", "if", "it", "exists", ".", "Create", "it", "if", "it", "doesn", "t", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L535-L549
train
33,601
datadesk/python-documentcloud
documentcloud/__init__.py
Annotation.get_location
def get_location(self): """ Return the location as a good """ image_string = self.__dict__['location']['image'] image_ints = list(map(int, image_string.split(","))) return Location(*image_ints)
python
def get_location(self): """ Return the location as a good """ image_string = self.__dict__['location']['image'] image_ints = list(map(int, image_string.split(","))) return Location(*image_ints)
[ "def", "get_location", "(", "self", ")", ":", "image_string", "=", "self", ".", "__dict__", "[", "'location'", "]", "[", "'image'", "]", "image_ints", "=", "list", "(", "map", "(", "int", ",", "image_string", ".", "split", "(", "\",\"", ")", ")", ")", ...
Return the location as a good
[ "Return", "the", "location", "as", "a", "good" ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L594-L600
train
33,602
datadesk/python-documentcloud
documentcloud/__init__.py
Document.put
def put(self): """ Save changes made to the object to DocumentCloud. According to DocumentCloud's docs, edits are allowed for the following fields: * title * source * description * related_article * access * published_url * data key/value pairs Returns nothing. """ params = dict( title=self.title or '', source=self.source or '', description=self.description or '', related_article=self.resources.related_article or '', published_url=self.resources.published_url or '', access=self.access, data=self.data, ) self._connection.put('documents/%s.json' % self.id, params)
python
def put(self): """ Save changes made to the object to DocumentCloud. According to DocumentCloud's docs, edits are allowed for the following fields: * title * source * description * related_article * access * published_url * data key/value pairs Returns nothing. """ params = dict( title=self.title or '', source=self.source or '', description=self.description or '', related_article=self.resources.related_article or '', published_url=self.resources.published_url or '', access=self.access, data=self.data, ) self._connection.put('documents/%s.json' % self.id, params)
[ "def", "put", "(", "self", ")", ":", "params", "=", "dict", "(", "title", "=", "self", ".", "title", "or", "''", ",", "source", "=", "self", ".", "source", "or", "''", ",", "description", "=", "self", ".", "description", "or", "''", ",", "related_a...
Save changes made to the object to DocumentCloud. According to DocumentCloud's docs, edits are allowed for the following fields: * title * source * description * related_article * access * published_url * data key/value pairs Returns nothing.
[ "Save", "changes", "made", "to", "the", "object", "to", "DocumentCloud", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L652-L678
train
33,603
datadesk/python-documentcloud
documentcloud/__init__.py
Document._lazy_load
def _lazy_load(self): """ Fetch metadata if it was overlooked during the object's creation. This can happen when you retrieve documents via search, because the JSON response does not include complete meta data for all results. """ obj = self._connection.documents.get(id=self.id) self.__dict__['contributor'] = obj.contributor self.__dict__['contributor_organization'] = \ obj.contributor_organization self.__dict__['data'] = obj.data self.__dict__['annotations'] = obj.__dict__['annotations'] self.__dict__['sections'] = obj.__dict__['sections']
python
def _lazy_load(self): """ Fetch metadata if it was overlooked during the object's creation. This can happen when you retrieve documents via search, because the JSON response does not include complete meta data for all results. """ obj = self._connection.documents.get(id=self.id) self.__dict__['contributor'] = obj.contributor self.__dict__['contributor_organization'] = \ obj.contributor_organization self.__dict__['data'] = obj.data self.__dict__['annotations'] = obj.__dict__['annotations'] self.__dict__['sections'] = obj.__dict__['sections']
[ "def", "_lazy_load", "(", "self", ")", ":", "obj", "=", "self", ".", "_connection", ".", "documents", ".", "get", "(", "id", "=", "self", ".", "id", ")", "self", ".", "__dict__", "[", "'contributor'", "]", "=", "obj", ".", "contributor", "self", ".",...
Fetch metadata if it was overlooked during the object's creation. This can happen when you retrieve documents via search, because the JSON response does not include complete meta data for all results.
[ "Fetch", "metadata", "if", "it", "was", "overlooked", "during", "the", "object", "s", "creation", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L696-L710
train
33,604
datadesk/python-documentcloud
documentcloud/__init__.py
Document.set_data
def set_data(self, data): """ Update the data attribute, making sure it's a dictionary. """ # Make sure a dict got passed it if not isinstance(data, type({})): raise TypeError("This attribute must be a dictionary.") # Set the attribute self.__dict__['data'] = DocumentDataDict(data)
python
def set_data(self, data): """ Update the data attribute, making sure it's a dictionary. """ # Make sure a dict got passed it if not isinstance(data, type({})): raise TypeError("This attribute must be a dictionary.") # Set the attribute self.__dict__['data'] = DocumentDataDict(data)
[ "def", "set_data", "(", "self", ",", "data", ")", ":", "# Make sure a dict got passed it", "if", "not", "isinstance", "(", "data", ",", "type", "(", "{", "}", ")", ")", ":", "raise", "TypeError", "(", "\"This attribute must be a dictionary.\"", ")", "# Set the a...
Update the data attribute, making sure it's a dictionary.
[ "Update", "the", "data", "attribute", "making", "sure", "it", "s", "a", "dictionary", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L734-L742
train
33,605
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_data
def get_data(self): """ Fetch the data field if it does not exist. """ try: return DocumentDataDict(self.__dict__['data']) except KeyError: self._lazy_load() return DocumentDataDict(self.__dict__['data'])
python
def get_data(self): """ Fetch the data field if it does not exist. """ try: return DocumentDataDict(self.__dict__['data']) except KeyError: self._lazy_load() return DocumentDataDict(self.__dict__['data'])
[ "def", "get_data", "(", "self", ")", ":", "try", ":", "return", "DocumentDataDict", "(", "self", ".", "__dict__", "[", "'data'", "]", ")", "except", "KeyError", ":", "self", ".", "_lazy_load", "(", ")", "return", "DocumentDataDict", "(", "self", ".", "__...
Fetch the data field if it does not exist.
[ "Fetch", "the", "data", "field", "if", "it", "does", "not", "exist", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L744-L752
train
33,606
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_annotations
def get_annotations(self): """ Fetch the annotations field if it does not exist. """ try: obj_list = self.__dict__['annotations'] return [Annotation(i) for i in obj_list] except KeyError: self._lazy_load() obj_list = self.__dict__['annotations'] return [Annotation(i) for i in obj_list]
python
def get_annotations(self): """ Fetch the annotations field if it does not exist. """ try: obj_list = self.__dict__['annotations'] return [Annotation(i) for i in obj_list] except KeyError: self._lazy_load() obj_list = self.__dict__['annotations'] return [Annotation(i) for i in obj_list]
[ "def", "get_annotations", "(", "self", ")", ":", "try", ":", "obj_list", "=", "self", ".", "__dict__", "[", "'annotations'", "]", "return", "[", "Annotation", "(", "i", ")", "for", "i", "in", "obj_list", "]", "except", "KeyError", ":", "self", ".", "_l...
Fetch the annotations field if it does not exist.
[ "Fetch", "the", "annotations", "field", "if", "it", "does", "not", "exist", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L755-L765
train
33,607
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_sections
def get_sections(self): """ Fetch the sections field if it does not exist. """ try: obj_list = self.__dict__['sections'] return [Section(i) for i in obj_list] except KeyError: self._lazy_load() obj_list = self.__dict__['sections'] return [Section(i) for i in obj_list]
python
def get_sections(self): """ Fetch the sections field if it does not exist. """ try: obj_list = self.__dict__['sections'] return [Section(i) for i in obj_list] except KeyError: self._lazy_load() obj_list = self.__dict__['sections'] return [Section(i) for i in obj_list]
[ "def", "get_sections", "(", "self", ")", ":", "try", ":", "obj_list", "=", "self", ".", "__dict__", "[", "'sections'", "]", "return", "[", "Section", "(", "i", ")", "for", "i", "in", "obj_list", "]", "except", "KeyError", ":", "self", ".", "_lazy_load"...
Fetch the sections field if it does not exist.
[ "Fetch", "the", "sections", "field", "if", "it", "does", "not", "exist", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L768-L778
train
33,608
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_entities
def get_entities(self): """ Fetch the entities extracted from this document by OpenCalais. """ try: return self.__dict__['entities'] except KeyError: entities = self._connection.fetch( "documents/%s/entities.json" % self.id ).get("entities") obj_list = [] for type, entity_list in list(entities.items()): for entity in entity_list: entity['type'] = type obj = Entity(entity) obj_list.append(obj) self.__dict__['entities'] = obj_list return self.__dict__['entities']
python
def get_entities(self): """ Fetch the entities extracted from this document by OpenCalais. """ try: return self.__dict__['entities'] except KeyError: entities = self._connection.fetch( "documents/%s/entities.json" % self.id ).get("entities") obj_list = [] for type, entity_list in list(entities.items()): for entity in entity_list: entity['type'] = type obj = Entity(entity) obj_list.append(obj) self.__dict__['entities'] = obj_list return self.__dict__['entities']
[ "def", "get_entities", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__dict__", "[", "'entities'", "]", "except", "KeyError", ":", "entities", "=", "self", ".", "_connection", ".", "fetch", "(", "\"documents/%s/entities.json\"", "%", "self", "."...
Fetch the entities extracted from this document by OpenCalais.
[ "Fetch", "the", "entities", "extracted", "from", "this", "document", "by", "OpenCalais", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L781-L798
train
33,609
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_page_text_url
def get_page_text_url(self, page): """ Returns the URL for the full text of a particular page in the document. """ template = self.resources.page.get('text') url = template.replace("{page}", str(page)) return url
python
def get_page_text_url(self, page): """ Returns the URL for the full text of a particular page in the document. """ template = self.resources.page.get('text') url = template.replace("{page}", str(page)) return url
[ "def", "get_page_text_url", "(", "self", ",", "page", ")", ":", "template", "=", "self", ".", "resources", ".", "page", ".", "get", "(", "'text'", ")", "url", "=", "template", ".", "replace", "(", "\"{page}\"", ",", "str", "(", "page", ")", ")", "ret...
Returns the URL for the full text of a particular page in the document.
[ "Returns", "the", "URL", "for", "the", "full", "text", "of", "a", "particular", "page", "in", "the", "document", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L832-L838
train
33,610
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_page_text
def get_page_text(self, page): """ Downloads and returns the full text of a particular page in the document. """ url = self.get_page_text_url(page) return self._get_url(url)
python
def get_page_text(self, page): """ Downloads and returns the full text of a particular page in the document. """ url = self.get_page_text_url(page) return self._get_url(url)
[ "def", "get_page_text", "(", "self", ",", "page", ")", ":", "url", "=", "self", ".", "get_page_text_url", "(", "page", ")", "return", "self", ".", "_get_url", "(", "url", ")" ]
Downloads and returns the full text of a particular page in the document.
[ "Downloads", "and", "returns", "the", "full", "text", "of", "a", "particular", "page", "in", "the", "document", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L840-L846
train
33,611
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_small_image_url
def get_small_image_url(self, page=1): """ Returns the URL for the small sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace( "{page}", str(page) ).replace("{size}", "small")
python
def get_small_image_url(self, page=1): """ Returns the URL for the small sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace( "{page}", str(page) ).replace("{size}", "small")
[ "def", "get_small_image_url", "(", "self", ",", "page", "=", "1", ")", ":", "template", "=", "self", ".", "resources", ".", "page", ".", "get", "(", "'image'", ")", "return", "template", ".", "replace", "(", "\"{page}\"", ",", "str", "(", "page", ")", ...
Returns the URL for the small sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Returns", "the", "URL", "for", "the", "small", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L866-L876
train
33,612
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_thumbnail_image_url
def get_thumbnail_image_url(self, page=1): """ Returns the URL for the thumbnail sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace( "{page}", str(page) ).replace("{size}", "thumbnail")
python
def get_thumbnail_image_url(self, page=1): """ Returns the URL for the thumbnail sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace( "{page}", str(page) ).replace("{size}", "thumbnail")
[ "def", "get_thumbnail_image_url", "(", "self", ",", "page", "=", "1", ")", ":", "template", "=", "self", ".", "resources", ".", "page", ".", "get", "(", "'image'", ")", "return", "template", ".", "replace", "(", "\"{page}\"", ",", "str", "(", "page", "...
Returns the URL for the thumbnail sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Returns", "the", "URL", "for", "the", "thumbnail", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L879-L889
train
33,613
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_normal_image_url
def get_normal_image_url(self, page=1): """ Returns the URL for the "normal" sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace( "{page}", str(page) ).replace("{size}", "normal")
python
def get_normal_image_url(self, page=1): """ Returns the URL for the "normal" sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace( "{page}", str(page) ).replace("{size}", "normal")
[ "def", "get_normal_image_url", "(", "self", ",", "page", "=", "1", ")", ":", "template", "=", "self", ".", "resources", ".", "page", ".", "get", "(", "'image'", ")", "return", "template", ".", "replace", "(", "\"{page}\"", ",", "str", "(", "page", ")",...
Returns the URL for the "normal" sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Returns", "the", "URL", "for", "the", "normal", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L892-L902
train
33,614
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_large_image_url
def get_large_image_url(self, page=1): """ Returns the URL for the large sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace("{page}", str(page)).replace("{size}", "large")
python
def get_large_image_url(self, page=1): """ Returns the URL for the large sized image of a single page. The page kwarg specifies which page to return. One is the default. """ template = self.resources.page.get('image') return template.replace("{page}", str(page)).replace("{size}", "large")
[ "def", "get_large_image_url", "(", "self", ",", "page", "=", "1", ")", ":", "template", "=", "self", ".", "resources", ".", "page", ".", "get", "(", "'image'", ")", "return", "template", ".", "replace", "(", "\"{page}\"", ",", "str", "(", "page", ")", ...
Returns the URL for the large sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Returns", "the", "URL", "for", "the", "large", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L905-L912
train
33,615
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_small_image
def get_small_image(self, page=1): """ Downloads and returns the small sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_small_image_url(page=page) return self._get_url(url)
python
def get_small_image(self, page=1): """ Downloads and returns the small sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_small_image_url(page=page) return self._get_url(url)
[ "def", "get_small_image", "(", "self", ",", "page", "=", "1", ")", ":", "url", "=", "self", ".", "get_small_image_url", "(", "page", "=", "page", ")", "return", "self", ".", "_get_url", "(", "url", ")" ]
Downloads and returns the small sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Downloads", "and", "returns", "the", "small", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L945-L952
train
33,616
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_thumbnail_image
def get_thumbnail_image(self, page=1): """ Downloads and returns the thumbnail sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_thumbnail_image_url(page=page) return self._get_url(url)
python
def get_thumbnail_image(self, page=1): """ Downloads and returns the thumbnail sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_thumbnail_image_url(page=page) return self._get_url(url)
[ "def", "get_thumbnail_image", "(", "self", ",", "page", "=", "1", ")", ":", "url", "=", "self", ".", "get_thumbnail_image_url", "(", "page", "=", "page", ")", "return", "self", ".", "_get_url", "(", "url", ")" ]
Downloads and returns the thumbnail sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Downloads", "and", "returns", "the", "thumbnail", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L955-L962
train
33,617
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_normal_image
def get_normal_image(self, page=1): """ Downloads and returns the normal sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_normal_image_url(page=page) return self._get_url(url)
python
def get_normal_image(self, page=1): """ Downloads and returns the normal sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_normal_image_url(page=page) return self._get_url(url)
[ "def", "get_normal_image", "(", "self", ",", "page", "=", "1", ")", ":", "url", "=", "self", ".", "get_normal_image_url", "(", "page", "=", "page", ")", "return", "self", ".", "_get_url", "(", "url", ")" ]
Downloads and returns the normal sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Downloads", "and", "returns", "the", "normal", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L965-L972
train
33,618
datadesk/python-documentcloud
documentcloud/__init__.py
Document.get_large_image
def get_large_image(self, page=1): """ Downloads and returns the large sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_large_image_url(page=page) return self._get_url(url)
python
def get_large_image(self, page=1): """ Downloads and returns the large sized image of a single page. The page kwarg specifies which page to return. One is the default. """ url = self.get_large_image_url(page=page) return self._get_url(url)
[ "def", "get_large_image", "(", "self", ",", "page", "=", "1", ")", ":", "url", "=", "self", ".", "get_large_image_url", "(", "page", "=", "page", ")", "return", "self", ".", "_get_url", "(", "url", ")" ]
Downloads and returns the large sized image of a single page. The page kwarg specifies which page to return. One is the default.
[ "Downloads", "and", "returns", "the", "large", "sized", "image", "of", "a", "single", "page", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L975-L982
train
33,619
datadesk/python-documentcloud
documentcloud/__init__.py
Project.put
def put(self): """ Save changes made to the object to documentcloud.org According to DocumentCloud's docs, edits are allowed for the following fields: * title * description * document_ids Returns nothing. """ params = dict( title=self.title or '', description=self.description or '', document_ids=[str(i.id) for i in self.document_list] ) self._connection.put('projects/%s.json' % self.id, params)
python
def put(self): """ Save changes made to the object to documentcloud.org According to DocumentCloud's docs, edits are allowed for the following fields: * title * description * document_ids Returns nothing. """ params = dict( title=self.title or '', description=self.description or '', document_ids=[str(i.id) for i in self.document_list] ) self._connection.put('projects/%s.json' % self.id, params)
[ "def", "put", "(", "self", ")", ":", "params", "=", "dict", "(", "title", "=", "self", ".", "title", "or", "''", ",", "description", "=", "self", ".", "description", "or", "''", ",", "document_ids", "=", "[", "str", "(", "i", ".", "id", ")", "for...
Save changes made to the object to documentcloud.org According to DocumentCloud's docs, edits are allowed for the following fields: * title * description * document_ids Returns nothing.
[ "Save", "changes", "made", "to", "the", "object", "to", "documentcloud", ".", "org" ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L1104-L1122
train
33,620
datadesk/python-documentcloud
documentcloud/__init__.py
Project.get_document_list
def get_document_list(self): """ Retrieves all documents included in this project. """ try: return self.__dict__['document_list'] except KeyError: obj_list = DocumentSet([ self._connection.documents.get(i) for i in self.document_ids ]) self.__dict__['document_list'] = obj_list return obj_list
python
def get_document_list(self): """ Retrieves all documents included in this project. """ try: return self.__dict__['document_list'] except KeyError: obj_list = DocumentSet([ self._connection.documents.get(i) for i in self.document_ids ]) self.__dict__['document_list'] = obj_list return obj_list
[ "def", "get_document_list", "(", "self", ")", ":", "try", ":", "return", "self", ".", "__dict__", "[", "'document_list'", "]", "except", "KeyError", ":", "obj_list", "=", "DocumentSet", "(", "[", "self", ".", "_connection", ".", "documents", ".", "get", "(...
Retrieves all documents included in this project.
[ "Retrieves", "all", "documents", "included", "in", "this", "project", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L1140-L1151
train
33,621
datadesk/python-documentcloud
documentcloud/__init__.py
Project.get_document
def get_document(self, id): """ Retrieves a particular document from this project. """ obj_list = self.document_list matches = [i for i in obj_list if str(i.id) == str(id)] if not matches: raise DoesNotExistError("The resource you've requested does not \ exist or is unavailable without the proper credentials.") return matches[0]
python
def get_document(self, id): """ Retrieves a particular document from this project. """ obj_list = self.document_list matches = [i for i in obj_list if str(i.id) == str(id)] if not matches: raise DoesNotExistError("The resource you've requested does not \ exist or is unavailable without the proper credentials.") return matches[0]
[ "def", "get_document", "(", "self", ",", "id", ")", ":", "obj_list", "=", "self", ".", "document_list", "matches", "=", "[", "i", "for", "i", "in", "obj_list", "if", "str", "(", "i", ".", "id", ")", "==", "str", "(", "id", ")", "]", "if", "not", ...
Retrieves a particular document from this project.
[ "Retrieves", "a", "particular", "document", "from", "this", "project", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/__init__.py#L1154-L1163
train
33,622
mrstephenneal/pdfconduit
pdf/conduit/watermark/watermark.py
Watermark.draw
def draw(self, text1=None, text2=None, copyright=True, image=IMAGE_DEFAULT, rotate=30, opacity=0.08, compress=0, flatten=False, add=False): """ Draw watermark PDF file. Create watermark using either a reportlabs canvas or a PIL image. :param text1: str Text line 1 :param text2: str Text line 2 :param copyright: bool Draw copyright and year to canvas :param image: str Logo image to be used as base watermark :param rotate: int Degrees to rotate canvas by :param opacity: float Watermark opacity :param compress: bool Compress watermark contents (not entire PDF) :param flatten: bool Draw watermark with multiple layers or a single flattened layer :param add: bool Add watermark to original document :return: str Watermark PDF file full path """ im_path = os.path.join(IMAGE_DIRECTORY, image) if os.path.isfile(im_path): image = im_path # Add to receipt if self.use_receipt: self.receipt.add('Text1', text1) self.receipt.add('Text2', text2) self.receipt.add('Image', os.path.basename(image)) self.receipt.add('WM Opacity', str(int(opacity * 100)) + '%') self.receipt.add('WM Compression', compress) self.receipt.add('WM Flattening', flatten) co = CanvasConstructor(text1, text2, copyright, image, rotate, opacity, tempdir=self.tempdir) objects, rotate = co.img() if flatten else co.canvas() # Run img constructor method if flatten is True # Draw watermark to file self.watermark = WatermarkDraw(objects, rotate=rotate, compress=compress, tempdir=self.tempdir, pagesize=Info(self.document_og).size, pagescale=True).write() if not add: return self.watermark else: self.add() return self.cleanup()
python
def draw(self, text1=None, text2=None, copyright=True, image=IMAGE_DEFAULT, rotate=30, opacity=0.08, compress=0, flatten=False, add=False): """ Draw watermark PDF file. Create watermark using either a reportlabs canvas or a PIL image. :param text1: str Text line 1 :param text2: str Text line 2 :param copyright: bool Draw copyright and year to canvas :param image: str Logo image to be used as base watermark :param rotate: int Degrees to rotate canvas by :param opacity: float Watermark opacity :param compress: bool Compress watermark contents (not entire PDF) :param flatten: bool Draw watermark with multiple layers or a single flattened layer :param add: bool Add watermark to original document :return: str Watermark PDF file full path """ im_path = os.path.join(IMAGE_DIRECTORY, image) if os.path.isfile(im_path): image = im_path # Add to receipt if self.use_receipt: self.receipt.add('Text1', text1) self.receipt.add('Text2', text2) self.receipt.add('Image', os.path.basename(image)) self.receipt.add('WM Opacity', str(int(opacity * 100)) + '%') self.receipt.add('WM Compression', compress) self.receipt.add('WM Flattening', flatten) co = CanvasConstructor(text1, text2, copyright, image, rotate, opacity, tempdir=self.tempdir) objects, rotate = co.img() if flatten else co.canvas() # Run img constructor method if flatten is True # Draw watermark to file self.watermark = WatermarkDraw(objects, rotate=rotate, compress=compress, tempdir=self.tempdir, pagesize=Info(self.document_og).size, pagescale=True).write() if not add: return self.watermark else: self.add() return self.cleanup()
[ "def", "draw", "(", "self", ",", "text1", "=", "None", ",", "text2", "=", "None", ",", "copyright", "=", "True", ",", "image", "=", "IMAGE_DEFAULT", ",", "rotate", "=", "30", ",", "opacity", "=", "0.08", ",", "compress", "=", "0", ",", "flatten", "...
Draw watermark PDF file. Create watermark using either a reportlabs canvas or a PIL image. :param text1: str Text line 1 :param text2: str Text line 2 :param copyright: bool Draw copyright and year to canvas :param image: str Logo image to be used as base watermark :param rotate: int Degrees to rotate canvas by :param opacity: float Watermark opacity :param compress: bool Compress watermark contents (not entire PDF) :param flatten: bool Draw watermark with multiple layers or a single flattened layer :param add: bool Add watermark to original document :return: str Watermark PDF file full path
[ "Draw", "watermark", "PDF", "file", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/conduit/watermark/watermark.py#L81-L133
train
33,623
mrstephenneal/pdfconduit
pdf/conduit/watermark/watermark.py
Watermark.add
def add(self, document=None, watermark=None, underneath=False, output=None, suffix='watermarked', method='pdfrw'): """ Add a watermark file to an existing PDF document. Rotate and upscale watermark file as needed to fit existing PDF document. Watermark can be overlayed or placed underneath. :param document: str PDF document full path :param watermark: str Watermark PDF full path :param underneath: bool Place watermark either under or over existing PDF document :param output: str Output file path :param suffix: str Suffix to append to existing PDF document file name :param method: str PDF library to be used for watermark adding :return: str Watermarked PDF Document full path """ if self.use_receipt: self.receipt.add('WM Placement', 'Overlay') if not watermark: watermark = self.watermark if not document: document = self.document self.document = str(WatermarkAdd(document, watermark, output=output, underneath=underneath, tempdir=self.tempdir, suffix=suffix, method=method)) if self.use_receipt: self.receipt.add('Watermarked PDF', os.path.basename(self.document)) if self.open_file: open_window(self.document) return self.document
python
def add(self, document=None, watermark=None, underneath=False, output=None, suffix='watermarked', method='pdfrw'): """ Add a watermark file to an existing PDF document. Rotate and upscale watermark file as needed to fit existing PDF document. Watermark can be overlayed or placed underneath. :param document: str PDF document full path :param watermark: str Watermark PDF full path :param underneath: bool Place watermark either under or over existing PDF document :param output: str Output file path :param suffix: str Suffix to append to existing PDF document file name :param method: str PDF library to be used for watermark adding :return: str Watermarked PDF Document full path """ if self.use_receipt: self.receipt.add('WM Placement', 'Overlay') if not watermark: watermark = self.watermark if not document: document = self.document self.document = str(WatermarkAdd(document, watermark, output=output, underneath=underneath, tempdir=self.tempdir, suffix=suffix, method=method)) if self.use_receipt: self.receipt.add('Watermarked PDF', os.path.basename(self.document)) if self.open_file: open_window(self.document) return self.document
[ "def", "add", "(", "self", ",", "document", "=", "None", ",", "watermark", "=", "None", ",", "underneath", "=", "False", ",", "output", "=", "None", ",", "suffix", "=", "'watermarked'", ",", "method", "=", "'pdfrw'", ")", ":", "if", "self", ".", "use...
Add a watermark file to an existing PDF document. Rotate and upscale watermark file as needed to fit existing PDF document. Watermark can be overlayed or placed underneath. :param document: str PDF document full path :param watermark: str Watermark PDF full path :param underneath: bool Place watermark either under or over existing PDF document :param output: str Output file path :param suffix: str Suffix to append to existing PDF document file name :param method: str PDF library to be used for watermark adding :return: str Watermarked PDF Document full path
[ "Add", "a", "watermark", "file", "to", "an", "existing", "PDF", "document", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/conduit/watermark/watermark.py#L135-L169
train
33,624
mrstephenneal/pdfconduit
pdf/conduit/watermark/watermark.py
Watermark.encrypt
def encrypt(self, user_pw='', owner_pw=None, encrypt_128=True, allow_printing=True, allow_commenting=False, document=None): """ Encrypt a PDF document to add passwords and restrict permissions. Add a user password that must be entered to view document and a owner password that must be entered to alter permissions and security settings. Encryption keys are 128 bit when encrypt_128 is True and 40 bit when False. By default permissions are restricted to print only, when set to false all permissions are allowed. TODO: Add additional permission parameters :param user_pw: str User password required to open and view PDF document :param owner_pw: str Owner password required to alter security settings and permissions :param encrypt_128: bool Encrypt PDF document using 128 bit keys :param allow_printing: bool Restrict permissions to print only :return: str Encrypted PDF full path """ document = self.document if document is None else document if self.use_receipt: self.receipt.add('User pw', user_pw) self.receipt.add('Owner pw', owner_pw) if encrypt_128: self.receipt.add('Encryption key size', '128') else: self.receipt.add('Encryption key size', '40') if allow_printing: self.receipt.add('Permissions', 'Allow printing') else: self.receipt.add('Permissions', 'Allow ALL') p = str(Encrypt(document, user_pw, owner_pw, output=add_suffix(self.document_og, 'secured'), bit128=encrypt_128, allow_printing=allow_printing, allow_commenting=allow_commenting, progress_bar_enabled=self.progress_bar_enabled, progress_bar=self.progress_bar)) if self.use_receipt: self.receipt.add('Secured PDF', os.path.basename(p)) return p
python
def encrypt(self, user_pw='', owner_pw=None, encrypt_128=True, allow_printing=True, allow_commenting=False, document=None): """ Encrypt a PDF document to add passwords and restrict permissions. Add a user password that must be entered to view document and a owner password that must be entered to alter permissions and security settings. Encryption keys are 128 bit when encrypt_128 is True and 40 bit when False. By default permissions are restricted to print only, when set to false all permissions are allowed. TODO: Add additional permission parameters :param user_pw: str User password required to open and view PDF document :param owner_pw: str Owner password required to alter security settings and permissions :param encrypt_128: bool Encrypt PDF document using 128 bit keys :param allow_printing: bool Restrict permissions to print only :return: str Encrypted PDF full path """ document = self.document if document is None else document if self.use_receipt: self.receipt.add('User pw', user_pw) self.receipt.add('Owner pw', owner_pw) if encrypt_128: self.receipt.add('Encryption key size', '128') else: self.receipt.add('Encryption key size', '40') if allow_printing: self.receipt.add('Permissions', 'Allow printing') else: self.receipt.add('Permissions', 'Allow ALL') p = str(Encrypt(document, user_pw, owner_pw, output=add_suffix(self.document_og, 'secured'), bit128=encrypt_128, allow_printing=allow_printing, allow_commenting=allow_commenting, progress_bar_enabled=self.progress_bar_enabled, progress_bar=self.progress_bar)) if self.use_receipt: self.receipt.add('Secured PDF', os.path.basename(p)) return p
[ "def", "encrypt", "(", "self", ",", "user_pw", "=", "''", ",", "owner_pw", "=", "None", ",", "encrypt_128", "=", "True", ",", "allow_printing", "=", "True", ",", "allow_commenting", "=", "False", ",", "document", "=", "None", ")", ":", "document", "=", ...
Encrypt a PDF document to add passwords and restrict permissions. Add a user password that must be entered to view document and a owner password that must be entered to alter permissions and security settings. Encryption keys are 128 bit when encrypt_128 is True and 40 bit when False. By default permissions are restricted to print only, when set to false all permissions are allowed. TODO: Add additional permission parameters :param user_pw: str User password required to open and view PDF document :param owner_pw: str Owner password required to alter security settings and permissions :param encrypt_128: bool Encrypt PDF document using 128 bit keys :param allow_printing: bool Restrict permissions to print only :return: str Encrypted PDF full path
[ "Encrypt", "a", "PDF", "document", "to", "add", "passwords", "and", "restrict", "permissions", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/conduit/watermark/watermark.py#L171-L209
train
33,625
datadesk/python-documentcloud
documentcloud/toolbox.py
credentials_required
def credentials_required(method_func): """ Decorator for methods that checks that the client has credentials. Throws a CredentialsMissingError when they are absent. """ def _checkcredentials(self, *args, **kwargs): if self.username and self.password: return method_func(self, *args, **kwargs) else: raise CredentialsMissingError("This is a private method. \ You must provide a username and password when you initialize the \ DocumentCloud client to attempt this type of request.") return wraps(method_func)(_checkcredentials)
python
def credentials_required(method_func): """ Decorator for methods that checks that the client has credentials. Throws a CredentialsMissingError when they are absent. """ def _checkcredentials(self, *args, **kwargs): if self.username and self.password: return method_func(self, *args, **kwargs) else: raise CredentialsMissingError("This is a private method. \ You must provide a username and password when you initialize the \ DocumentCloud client to attempt this type of request.") return wraps(method_func)(_checkcredentials)
[ "def", "credentials_required", "(", "method_func", ")", ":", "def", "_checkcredentials", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "username", "and", "self", ".", "password", ":", "return", "method_func", "(", "...
Decorator for methods that checks that the client has credentials. Throws a CredentialsMissingError when they are absent.
[ "Decorator", "for", "methods", "that", "checks", "that", "the", "client", "has", "credentials", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/toolbox.py#L45-L59
train
33,626
datadesk/python-documentcloud
documentcloud/toolbox.py
retry
def retry(ExceptionToCheck, tries=3, delay=2, backoff=2): """ Retry decorator published by Saltry Crane. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ """ def deco_retry(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay try_one_last_time = True while mtries > 1: try: return f(*args, **kwargs) try_one_last_time = False break except ExceptionToCheck: six.print_("Retrying in %s seconds" % str(mdelay)) time.sleep(mdelay) mtries -= 1 mdelay *= backoff if try_one_last_time: return f(*args, **kwargs) return return f_retry # true decorator return deco_retry
python
def retry(ExceptionToCheck, tries=3, delay=2, backoff=2): """ Retry decorator published by Saltry Crane. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ """ def deco_retry(f): def f_retry(*args, **kwargs): mtries, mdelay = tries, delay try_one_last_time = True while mtries > 1: try: return f(*args, **kwargs) try_one_last_time = False break except ExceptionToCheck: six.print_("Retrying in %s seconds" % str(mdelay)) time.sleep(mdelay) mtries -= 1 mdelay *= backoff if try_one_last_time: return f(*args, **kwargs) return return f_retry # true decorator return deco_retry
[ "def", "retry", "(", "ExceptionToCheck", ",", "tries", "=", "3", ",", "delay", "=", "2", ",", "backoff", "=", "2", ")", ":", "def", "deco_retry", "(", "f", ")", ":", "def", "f_retry", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "mtries",...
Retry decorator published by Saltry Crane. http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
[ "Retry", "decorator", "published", "by", "Saltry", "Crane", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/toolbox.py#L62-L86
train
33,627
mrstephenneal/pdfconduit
pdf/modify/draw/pdf.py
text_width
def text_width(string, font_name, font_size): """Determine with width in pixels of string.""" return stringWidth(string, fontName=font_name, fontSize=font_size)
python
def text_width(string, font_name, font_size): """Determine with width in pixels of string.""" return stringWidth(string, fontName=font_name, fontSize=font_size)
[ "def", "text_width", "(", "string", ",", "font_name", ",", "font_size", ")", ":", "return", "stringWidth", "(", "string", ",", "fontName", "=", "font_name", ",", "fontSize", "=", "font_size", ")" ]
Determine with width in pixels of string.
[ "Determine", "with", "width", "in", "pixels", "of", "string", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L15-L17
train
33,628
mrstephenneal/pdfconduit
pdf/modify/draw/pdf.py
center_str
def center_str(txt, font_name, font_size, offset=0): """Center a string on the x axis of a reportslab canvas""" return -(text_width(txt, font_name, font_size) / 2.0) + offset
python
def center_str(txt, font_name, font_size, offset=0): """Center a string on the x axis of a reportslab canvas""" return -(text_width(txt, font_name, font_size) / 2.0) + offset
[ "def", "center_str", "(", "txt", ",", "font_name", ",", "font_size", ",", "offset", "=", "0", ")", ":", "return", "-", "(", "text_width", "(", "txt", ",", "font_name", ",", "font_size", ")", "/", "2.0", ")", "+", "offset" ]
Center a string on the x axis of a reportslab canvas
[ "Center", "a", "string", "on", "the", "x", "axis", "of", "a", "reportslab", "canvas" ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L20-L22
train
33,629
mrstephenneal/pdfconduit
pdf/modify/draw/pdf.py
split_str
def split_str(string): """Split string in half to return two strings""" split = string.split(' ') return ' '.join(split[:len(split) // 2]), ' '.join(split[len(split) // 2:])
python
def split_str(string): """Split string in half to return two strings""" split = string.split(' ') return ' '.join(split[:len(split) // 2]), ' '.join(split[len(split) // 2:])
[ "def", "split_str", "(", "string", ")", ":", "split", "=", "string", ".", "split", "(", "' '", ")", "return", "' '", ".", "join", "(", "split", "[", ":", "len", "(", "split", ")", "//", "2", "]", ")", ",", "' '", ".", "join", "(", "split", "[",...
Split string in half to return two strings
[ "Split", "string", "in", "half", "to", "return", "two", "strings" ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L25-L28
train
33,630
mrstephenneal/pdfconduit
pdf/modify/draw/pdf.py
WatermarkDraw._draw_image
def _draw_image(self, ci): """ Draw image object to reportlabs canvas. :param ci: CanvasImage object """ img = img_adjust(ci.image, ci.opacity, tempdir=self.dir) self.can.drawImage(img, x=ci.x, y=ci.y, width=ci.w, height=ci.h, mask=ci.mask, preserveAspectRatio=ci.preserve_aspect_ratio, anchorAtXY=True)
python
def _draw_image(self, ci): """ Draw image object to reportlabs canvas. :param ci: CanvasImage object """ img = img_adjust(ci.image, ci.opacity, tempdir=self.dir) self.can.drawImage(img, x=ci.x, y=ci.y, width=ci.w, height=ci.h, mask=ci.mask, preserveAspectRatio=ci.preserve_aspect_ratio, anchorAtXY=True)
[ "def", "_draw_image", "(", "self", ",", "ci", ")", ":", "img", "=", "img_adjust", "(", "ci", ".", "image", ",", "ci", ".", "opacity", ",", "tempdir", "=", "self", ".", "dir", ")", "self", ".", "can", ".", "drawImage", "(", "img", ",", "x", "=", ...
Draw image object to reportlabs canvas. :param ci: CanvasImage object
[ "Draw", "image", "object", "to", "reportlabs", "canvas", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L105-L113
train
33,631
mrstephenneal/pdfconduit
pdf/modify/draw/pdf.py
WatermarkDraw._draw_string
def _draw_string(self, cs): """ Draw string object to reportlabs canvas. Canvas Parameter changes (applied if set values differ from string object values) 1. Font name 2. Font size 3. Font fill color & opacity 4. X and Y position :param cs: CanvasString object """ # 1. Font name if self.can._fontname != cs.font: self.can.setFont(cs.font, cs.size) # 2. Font size elif self.can._fontsize != cs.size: self.can.setFontSize(cs.size) # 3. Font file color self.can.setFillColor(cs.color, cs.opacity) # 4. X and Y positions # X and Y are both centered if cs.y_centered and cs.x_centered: # Check if text_width is greater than the canvas page width if text_width(cs.string, cs.font, cs.size) > self.can._pagesize[0]: str1, str2 = split_str(cs.string) self.can.drawString(x=center_str(str1, cs.font, cs.size, offset=0), y=cs.size, text=str1) self.can.drawString(x=center_str(str2, cs.font, cs.size, offset=0), y=-cs.size, text=str2) return else: x = center_str(cs.string, cs.font, cs.size, offset=0) y = 0 # Y is centered and X is not elif cs.y_centered and not cs.x_centered: x = cs.x y = 0 # X is centered and Y is not elif cs.x_centered and not cs.y_centered: x = center_str(cs.string, cs.font, cs.size, offset=0) y = cs.y else: x = cs.x y = cs.y self.can.drawString(x=x, y=y, text=cs.string) return
python
def _draw_string(self, cs): """ Draw string object to reportlabs canvas. Canvas Parameter changes (applied if set values differ from string object values) 1. Font name 2. Font size 3. Font fill color & opacity 4. X and Y position :param cs: CanvasString object """ # 1. Font name if self.can._fontname != cs.font: self.can.setFont(cs.font, cs.size) # 2. Font size elif self.can._fontsize != cs.size: self.can.setFontSize(cs.size) # 3. Font file color self.can.setFillColor(cs.color, cs.opacity) # 4. X and Y positions # X and Y are both centered if cs.y_centered and cs.x_centered: # Check if text_width is greater than the canvas page width if text_width(cs.string, cs.font, cs.size) > self.can._pagesize[0]: str1, str2 = split_str(cs.string) self.can.drawString(x=center_str(str1, cs.font, cs.size, offset=0), y=cs.size, text=str1) self.can.drawString(x=center_str(str2, cs.font, cs.size, offset=0), y=-cs.size, text=str2) return else: x = center_str(cs.string, cs.font, cs.size, offset=0) y = 0 # Y is centered and X is not elif cs.y_centered and not cs.x_centered: x = cs.x y = 0 # X is centered and Y is not elif cs.x_centered and not cs.y_centered: x = center_str(cs.string, cs.font, cs.size, offset=0) y = cs.y else: x = cs.x y = cs.y self.can.drawString(x=x, y=y, text=cs.string) return
[ "def", "_draw_string", "(", "self", ",", "cs", ")", ":", "# 1. Font name", "if", "self", ".", "can", ".", "_fontname", "!=", "cs", ".", "font", ":", "self", ".", "can", ".", "setFont", "(", "cs", ".", "font", ",", "cs", ".", "size", ")", "# 2. Font...
Draw string object to reportlabs canvas. Canvas Parameter changes (applied if set values differ from string object values) 1. Font name 2. Font size 3. Font fill color & opacity 4. X and Y position :param cs: CanvasString object
[ "Draw", "string", "object", "to", "reportlabs", "canvas", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/modify/draw/pdf.py#L115-L164
train
33,632
mrstephenneal/pdfconduit
pdf/transform/merge.py
Merge._get_pdf_list
def _get_pdf_list(self, input_pdfs): """ Generate list of PDF documents. :param input_pdfs: List of PDFs or a directory path Directory - Scans directory contents List - Filters list to assert all list items are paths to PDF documents :return: List of PDF paths """ if isinstance(input_pdfs, list): return [pdf for pdf in input_pdfs if self.validate(pdf)] elif os.path.isdir(input_pdfs): return [os.path.join(input_pdfs, pdf) for pdf in os.listdir(input_pdfs) if self.validate(pdf)]
python
def _get_pdf_list(self, input_pdfs): """ Generate list of PDF documents. :param input_pdfs: List of PDFs or a directory path Directory - Scans directory contents List - Filters list to assert all list items are paths to PDF documents :return: List of PDF paths """ if isinstance(input_pdfs, list): return [pdf for pdf in input_pdfs if self.validate(pdf)] elif os.path.isdir(input_pdfs): return [os.path.join(input_pdfs, pdf) for pdf in os.listdir(input_pdfs) if self.validate(pdf)]
[ "def", "_get_pdf_list", "(", "self", ",", "input_pdfs", ")", ":", "if", "isinstance", "(", "input_pdfs", ",", "list", ")", ":", "return", "[", "pdf", "for", "pdf", "in", "input_pdfs", "if", "self", ".", "validate", "(", "pdf", ")", "]", "elif", "os", ...
Generate list of PDF documents. :param input_pdfs: List of PDFs or a directory path Directory - Scans directory contents List - Filters list to assert all list items are paths to PDF documents :return: List of PDF paths
[ "Generate", "list", "of", "PDF", "documents", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/transform/merge.py#L24-L36
train
33,633
mrstephenneal/pdfconduit
pdf/transform/merge.py
Merge.merge
def merge(self, pdf_files, output): """Merge list of PDF files to a single PDF file.""" if self.method is 'pypdf3': return self.pypdf3(pdf_files, output) else: return self.pdfrw(pdf_files, output)
python
def merge(self, pdf_files, output): """Merge list of PDF files to a single PDF file.""" if self.method is 'pypdf3': return self.pypdf3(pdf_files, output) else: return self.pdfrw(pdf_files, output)
[ "def", "merge", "(", "self", ",", "pdf_files", ",", "output", ")", ":", "if", "self", ".", "method", "is", "'pypdf3'", ":", "return", "self", ".", "pypdf3", "(", "pdf_files", ",", "output", ")", "else", ":", "return", "self", ".", "pdfrw", "(", "pdf_...
Merge list of PDF files to a single PDF file.
[ "Merge", "list", "of", "PDF", "files", "to", "a", "single", "PDF", "file", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/transform/merge.py#L38-L43
train
33,634
mrstephenneal/pdfconduit
pdf/utils/path.py
set_destination
def set_destination(source, suffix, filename=False, ext=None): """Create new pdf filename for temp files""" source_dirname = os.path.dirname(source) # Do not create nested temp folders (/temp/temp) if not source_dirname.endswith('temp'): directory = os.path.join(source_dirname, 'temp') # directory else: directory = source_dirname # Create temp dir if it does not exist if not os.path.isdir(directory): os.mkdir(directory) # Parse source filename if filename: src_file_name = filename else: src_file_name = Path(source).stem # file name if ext: src_file_ext = ext else: src_file_ext = Path(source).suffix # file extension # Concatenate new filename dst_path = src_file_name + '_' + suffix + src_file_ext full_path = os.path.join(directory, dst_path) # new full path if not os.path.exists(full_path): return full_path else: # If file exists, increment number until filename is unique number = 1 while True: dst_path = src_file_name + '_' + suffix + '_' + str(number) + src_file_ext if not os.path.exists(dst_path): break number = number + 1 full_path = os.path.join(directory, dst_path) # new full path return full_path
python
def set_destination(source, suffix, filename=False, ext=None): """Create new pdf filename for temp files""" source_dirname = os.path.dirname(source) # Do not create nested temp folders (/temp/temp) if not source_dirname.endswith('temp'): directory = os.path.join(source_dirname, 'temp') # directory else: directory = source_dirname # Create temp dir if it does not exist if not os.path.isdir(directory): os.mkdir(directory) # Parse source filename if filename: src_file_name = filename else: src_file_name = Path(source).stem # file name if ext: src_file_ext = ext else: src_file_ext = Path(source).suffix # file extension # Concatenate new filename dst_path = src_file_name + '_' + suffix + src_file_ext full_path = os.path.join(directory, dst_path) # new full path if not os.path.exists(full_path): return full_path else: # If file exists, increment number until filename is unique number = 1 while True: dst_path = src_file_name + '_' + suffix + '_' + str(number) + src_file_ext if not os.path.exists(dst_path): break number = number + 1 full_path = os.path.join(directory, dst_path) # new full path return full_path
[ "def", "set_destination", "(", "source", ",", "suffix", ",", "filename", "=", "False", ",", "ext", "=", "None", ")", ":", "source_dirname", "=", "os", ".", "path", ".", "dirname", "(", "source", ")", "# Do not create nested temp folders (/temp/temp)", "if", "n...
Create new pdf filename for temp files
[ "Create", "new", "pdf", "filename", "for", "temp", "files" ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/utils/path.py#L25-L64
train
33,635
datadesk/python-documentcloud
documentcloud/MultipartPostHandler.py
getsize
def getsize(o_file): """ get the size, either by seeeking to the end. """ startpos = o_file.tell() o_file.seek(0) o_file.seek(0, SEEK_END) size = o_file.tell() o_file.seek(startpos) return size
python
def getsize(o_file): """ get the size, either by seeeking to the end. """ startpos = o_file.tell() o_file.seek(0) o_file.seek(0, SEEK_END) size = o_file.tell() o_file.seek(startpos) return size
[ "def", "getsize", "(", "o_file", ")", ":", "startpos", "=", "o_file", ".", "tell", "(", ")", "o_file", ".", "seek", "(", "0", ")", "o_file", ".", "seek", "(", "0", ",", "SEEK_END", ")", "size", "=", "o_file", ".", "tell", "(", ")", "o_file", ".",...
get the size, either by seeeking to the end.
[ "get", "the", "size", "either", "by", "seeeking", "to", "the", "end", "." ]
0d7f42cbf1edf5c61fca37ed846362cba4abfd76
https://github.com/datadesk/python-documentcloud/blob/0d7f42cbf1edf5c61fca37ed846362cba4abfd76/documentcloud/MultipartPostHandler.py#L201-L210
train
33,636
mrstephenneal/pdfconduit
pdf/gui/forms/watermark.py
WatermarkGUI.window
def window(self): """GUI window for Watermark parameters input.""" platform = system() # Tabbed layout for Windows if platform is 'Windows': layout_tab_1 = [] layout_tab_1.extend(header('PDF Watermark Utility')) layout_tab_1.extend(self.input_source()) layout_tab_1.extend(self.input_text()) layout_tab_1.extend(self.input_encryption()) layout_tab_1.extend(self.footer()) layout_tab_2 = [] layout_tab_2.extend(self.input_watermark_settings()) layout = [[gui.TabGroup([[gui.Tab('Document Settings', layout_tab_1), gui.Tab('Watermark Settings', layout_tab_2)]])]] window = gui.Window('PDF Watermark Utility', auto_close=False) button, values = window.Layout(layout).Read() window.Close() return button, values, platform # Standard layout for macOS else: layout = [] layout.extend(header('PDF Watermark Utility')) layout.extend(self.input_source()) layout.extend(self.input_text()) layout.extend(self.input_watermark_settings()) layout.extend(self.input_encryption()) layout.extend(self.footer()) window = gui.Window(TITLE, default_element_size=(40, 1), auto_close=False) button, values = window.Layout(layout).Read() window.Close() return button, values, platform
python
def window(self): """GUI window for Watermark parameters input.""" platform = system() # Tabbed layout for Windows if platform is 'Windows': layout_tab_1 = [] layout_tab_1.extend(header('PDF Watermark Utility')) layout_tab_1.extend(self.input_source()) layout_tab_1.extend(self.input_text()) layout_tab_1.extend(self.input_encryption()) layout_tab_1.extend(self.footer()) layout_tab_2 = [] layout_tab_2.extend(self.input_watermark_settings()) layout = [[gui.TabGroup([[gui.Tab('Document Settings', layout_tab_1), gui.Tab('Watermark Settings', layout_tab_2)]])]] window = gui.Window('PDF Watermark Utility', auto_close=False) button, values = window.Layout(layout).Read() window.Close() return button, values, platform # Standard layout for macOS else: layout = [] layout.extend(header('PDF Watermark Utility')) layout.extend(self.input_source()) layout.extend(self.input_text()) layout.extend(self.input_watermark_settings()) layout.extend(self.input_encryption()) layout.extend(self.footer()) window = gui.Window(TITLE, default_element_size=(40, 1), auto_close=False) button, values = window.Layout(layout).Read() window.Close() return button, values, platform
[ "def", "window", "(", "self", ")", ":", "platform", "=", "system", "(", ")", "# Tabbed layout for Windows", "if", "platform", "is", "'Windows'", ":", "layout_tab_1", "=", "[", "]", "layout_tab_1", ".", "extend", "(", "header", "(", "'PDF Watermark Utility'", "...
GUI window for Watermark parameters input.
[ "GUI", "window", "for", "Watermark", "parameters", "input", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/gui/forms/watermark.py#L143-L177
train
33,637
mrstephenneal/pdfconduit
pdf/convert/pdf2img.py
pdf2img
def pdf2img(file_name, output=None, tempdir=None, ext='png', progress_bar=None): """Wrapper function for PDF2IMG class""" return PDF2IMG(file_name=file_name, output=output, tempdir=tempdir, ext=ext, progress_bar=progress_bar).save()
python
def pdf2img(file_name, output=None, tempdir=None, ext='png', progress_bar=None): """Wrapper function for PDF2IMG class""" return PDF2IMG(file_name=file_name, output=output, tempdir=tempdir, ext=ext, progress_bar=progress_bar).save()
[ "def", "pdf2img", "(", "file_name", ",", "output", "=", "None", ",", "tempdir", "=", "None", ",", "ext", "=", "'png'", ",", "progress_bar", "=", "None", ")", ":", "return", "PDF2IMG", "(", "file_name", "=", "file_name", ",", "output", "=", "output", ",...
Wrapper function for PDF2IMG class
[ "Wrapper", "function", "for", "PDF2IMG", "class" ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/convert/pdf2img.py#L123-L125
train
33,638
mrstephenneal/pdfconduit
pdf/convert/pdf2img.py
PDF2IMG._get_page_data
def _get_page_data(self, pno, zoom=0): """ Return a PNG image for a document page number. If zoom is other than 0, one of the 4 page quadrants are zoomed-in instead and the corresponding clip returned. """ dlist = self.dlist_tab[pno] # get display list if not dlist: # create if not yet there self.dlist_tab[pno] = self.doc[pno].getDisplayList() dlist = self.dlist_tab[pno] r = dlist.rect # page rectangle mp = r.tl + (r.br - r.tl) * 0.5 # rect middle point mt = r.tl + (r.tr - r.tl) * 0.5 # middle of top edge ml = r.tl + (r.bl - r.tl) * 0.5 # middle of left edge mr = r.tr + (r.br - r.tr) * 0.5 # middle of right egde mb = r.bl + (r.br - r.bl) * 0.5 # middle of bottom edge mat = fitz.Matrix(2, 2) # zoom matrix if zoom == 1: # top-left quadrant clip = fitz.Rect(r.tl, mp) elif zoom == 4: # bot-right quadrant clip = fitz.Rect(mp, r.br) elif zoom == 2: # top-right clip = fitz.Rect(mt, mr) elif zoom == 3: # bot-left clip = fitz.Rect(ml, mb) if zoom == 0: # total page pix = dlist.getPixmap(alpha=False) else: pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip) return pix.getPNGData()
python
def _get_page_data(self, pno, zoom=0): """ Return a PNG image for a document page number. If zoom is other than 0, one of the 4 page quadrants are zoomed-in instead and the corresponding clip returned. """ dlist = self.dlist_tab[pno] # get display list if not dlist: # create if not yet there self.dlist_tab[pno] = self.doc[pno].getDisplayList() dlist = self.dlist_tab[pno] r = dlist.rect # page rectangle mp = r.tl + (r.br - r.tl) * 0.5 # rect middle point mt = r.tl + (r.tr - r.tl) * 0.5 # middle of top edge ml = r.tl + (r.bl - r.tl) * 0.5 # middle of left edge mr = r.tr + (r.br - r.tr) * 0.5 # middle of right egde mb = r.bl + (r.br - r.bl) * 0.5 # middle of bottom edge mat = fitz.Matrix(2, 2) # zoom matrix if zoom == 1: # top-left quadrant clip = fitz.Rect(r.tl, mp) elif zoom == 4: # bot-right quadrant clip = fitz.Rect(mp, r.br) elif zoom == 2: # top-right clip = fitz.Rect(mt, mr) elif zoom == 3: # bot-left clip = fitz.Rect(ml, mb) if zoom == 0: # total page pix = dlist.getPixmap(alpha=False) else: pix = dlist.getPixmap(alpha=False, matrix=mat, clip=clip) return pix.getPNGData()
[ "def", "_get_page_data", "(", "self", ",", "pno", ",", "zoom", "=", "0", ")", ":", "dlist", "=", "self", ".", "dlist_tab", "[", "pno", "]", "# get display list", "if", "not", "dlist", ":", "# create if not yet there", "self", ".", "dlist_tab", "[", "pno", ...
Return a PNG image for a document page number. If zoom is other than 0, one of the 4 page quadrants are zoomed-in instead and the corresponding clip returned.
[ "Return", "a", "PNG", "image", "for", "a", "document", "page", "number", ".", "If", "zoom", "is", "other", "than", "0", "one", "of", "the", "4", "page", "quadrants", "are", "zoomed", "-", "in", "instead", "and", "the", "corresponding", "clip", "returned"...
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/convert/pdf2img.py#L51-L79
train
33,639
mrstephenneal/pdfconduit
pdf/conduit/extract.py
text_extract
def text_extract(path, password=None): """Extract text from a PDF file""" pdf = Info(path, password).pdf return [pdf.getPage(i).extractText() for i in range(pdf.getNumPages())]
python
def text_extract(path, password=None): """Extract text from a PDF file""" pdf = Info(path, password).pdf return [pdf.getPage(i).extractText() for i in range(pdf.getNumPages())]
[ "def", "text_extract", "(", "path", ",", "password", "=", "None", ")", ":", "pdf", "=", "Info", "(", "path", ",", "password", ")", ".", "pdf", "return", "[", "pdf", ".", "getPage", "(", "i", ")", ".", "extractText", "(", ")", "for", "i", "in", "r...
Extract text from a PDF file
[ "Extract", "text", "from", "a", "PDF", "file" ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/conduit/extract.py#L44-L48
train
33,640
mrstephenneal/pdfconduit
pdf/utils/view.py
open_window
def open_window(path): """Open path in finder or explorer window""" if 'pathlib' in modules: try: call(["open", "-R", str(Path(str(path)))]) except FileNotFoundError: Popen(r'explorer /select,' + str(Path(str(path)))) else: print('pathlib module must be installed to execute open_window function')
python
def open_window(path): """Open path in finder or explorer window""" if 'pathlib' in modules: try: call(["open", "-R", str(Path(str(path)))]) except FileNotFoundError: Popen(r'explorer /select,' + str(Path(str(path)))) else: print('pathlib module must be installed to execute open_window function')
[ "def", "open_window", "(", "path", ")", ":", "if", "'pathlib'", "in", "modules", ":", "try", ":", "call", "(", "[", "\"open\"", ",", "\"-R\"", ",", "str", "(", "Path", "(", "str", "(", "path", ")", ")", ")", "]", ")", "except", "FileNotFoundError", ...
Open path in finder or explorer window
[ "Open", "path", "in", "finder", "or", "explorer", "window" ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/utils/view.py#L7-L15
train
33,641
mrstephenneal/pdfconduit
sandbox/pdftk_encrypt.py
secure
def secure(pdf, user_pw, owner_pw, restrict_permission=True, pdftk=get_pdftk_path(), output=None): """ Encrypt a PDF file and restrict permissions to print only. Utilizes pdftk command line tool. :param pdf: Path to PDF file :param user_pw: Password to open and view :param owner_pw: Password to transform permissions :param restrict_permission: Restrict permissions to print only :param pdftk: Path to pdftk binary :param output: Output path :return: Output path """ if pdftk: # Check that PDF file is encrypted with open(pdf, 'rb') as f: reader = PdfFileReader(f) if reader.isEncrypted: print('PDF is already encrypted') return pdf # Create output filename if not already set if not output: output = add_suffix(pdf, 'secured') # Replace spaces within paths with backslashes followed by a space pdf_en = pdf.replace(' ', '\ ') output_en = output.replace(' ', '\ ') # Concatenate bash command command = pdftk + ' ' + pdf_en + ' output ' + output_en + ' owner_pw ' + owner_pw + ' user_pw ' + user_pw # Append string to command if printing is allowed if restrict_permission: command += ' allow printing' # Execute command os.system(command) print('Secured PDF saved to...', output) return output else: print('Unable to locate pdftk binary')
python
def secure(pdf, user_pw, owner_pw, restrict_permission=True, pdftk=get_pdftk_path(), output=None): """ Encrypt a PDF file and restrict permissions to print only. Utilizes pdftk command line tool. :param pdf: Path to PDF file :param user_pw: Password to open and view :param owner_pw: Password to transform permissions :param restrict_permission: Restrict permissions to print only :param pdftk: Path to pdftk binary :param output: Output path :return: Output path """ if pdftk: # Check that PDF file is encrypted with open(pdf, 'rb') as f: reader = PdfFileReader(f) if reader.isEncrypted: print('PDF is already encrypted') return pdf # Create output filename if not already set if not output: output = add_suffix(pdf, 'secured') # Replace spaces within paths with backslashes followed by a space pdf_en = pdf.replace(' ', '\ ') output_en = output.replace(' ', '\ ') # Concatenate bash command command = pdftk + ' ' + pdf_en + ' output ' + output_en + ' owner_pw ' + owner_pw + ' user_pw ' + user_pw # Append string to command if printing is allowed if restrict_permission: command += ' allow printing' # Execute command os.system(command) print('Secured PDF saved to...', output) return output else: print('Unable to locate pdftk binary')
[ "def", "secure", "(", "pdf", ",", "user_pw", ",", "owner_pw", ",", "restrict_permission", "=", "True", ",", "pdftk", "=", "get_pdftk_path", "(", ")", ",", "output", "=", "None", ")", ":", "if", "pdftk", ":", "# Check that PDF file is encrypted", "with", "ope...
Encrypt a PDF file and restrict permissions to print only. Utilizes pdftk command line tool. :param pdf: Path to PDF file :param user_pw: Password to open and view :param owner_pw: Password to transform permissions :param restrict_permission: Restrict permissions to print only :param pdftk: Path to pdftk binary :param output: Output path :return: Output path
[ "Encrypt", "a", "PDF", "file", "and", "restrict", "permissions", "to", "print", "only", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/sandbox/pdftk_encrypt.py#L29-L71
train
33,642
mrstephenneal/pdfconduit
pdf/conduit/watermark/add.py
WatermarkAdd.add
def add(self, document, watermark): """Add watermark to PDF by merging original PDF and watermark file.""" # 5a. Create output PDF file name output_filename = self.output_filename def pypdf3(): """Much slower than PyPDF3 method.""" # 5b. Get our files ready document_reader = PdfFileReader(document) output_file = PdfFileWriter() # Number of pages in input document page_count = document_reader.getNumPages() # Watermark objects watermark_reader = PdfFileReader(watermark) wtrmrk_page = watermark_reader.getPage(0) wtrmrk_width = (wtrmrk_page.mediaBox.getWidth() / 2) + 0 wtrmrk_height = (wtrmrk_page.mediaBox.getHeight() / 2) + 80 wtrmrk_rotate = -int(Info(watermark_reader).rotate) if Info(watermark_reader).rotate is not None else 0 # 5c. Go through all the input file pages to add a watermark to them for page_number in range(page_count): # Merge the watermark with the page if not self.underneath: input_page = document_reader.getPage(page_number) if wtrmrk_rotate is not 0: input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height) else: wtrmrk_width = 0 wtrmrk_height = 0 input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height) else: size = Info(document_reader).dimensions input_page = PageObject().createBlankPage(document_reader, size['w'], size['h']) if wtrmrk_rotate is not 0: input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height) else: wtrmrk_width = 0 wtrmrk_height = 0 input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height) input_page.mergePage(document_reader.getPage(page_number)) # Add page from input file to output document output_file.addPage(input_page) # 5d. finally, write "output" to PDF with open(output_filename, "wb") as outputStream: output_file.write(outputStream) return output_filename def pdfrw(): """Faster than PyPDF3 method by as much as 15x.""" # TODO: Fix issue where watermark is improperly placed on large pagesize PDFs # print(Info(document).size) # print(Info(watermark).size) # print('\n') # Open both the source files wmark_trailer = PdfReader(watermark) trailer = PdfReader(document) # Handle different sized pages in same document with # a memoization cache, so we don't create more watermark # objects than we need to (typically only one per document). wmark_page = wmark_trailer.pages[0] wmark_cache = {} # Process every page for pagenum, page in enumerate(trailer.pages, 1): # Get the media box of the page, and see # if we have a matching watermark in the cache mbox = tuple(float(x) for x in page.MediaBox) odd = pagenum & 1 key = mbox, odd wmark = wmark_cache.get(key) if wmark is None: # Create and cache a new watermark object. wmark = wmark_cache[key] = PageMerge().add(wmark_page)[0] # The math is more complete than it probably needs to be, # because the origin of all pages is almost always (0, 0). # Nonetheless, we illustrate all the values and their names. page_x, page_y, page_x1, page_y1 = mbox page_w = page_x1 - page_x page_h = page_y1 - page_y # For illustration, not used # Scale the watermark if it is too wide for the page # (Could do the same for height instead if needed) if wmark.w > page_w: wmark.scale(1.0 * page_w / wmark.w) # Always put watermark at the top of the page # (but see horizontal positioning for other ideas) wmark.y += page_y1 - wmark.h # For odd pages, put it at the left of the page, # and for even pages, put it on the right of the page. if odd: wmark.x = page_x else: wmark.x += page_x1 - wmark.w # Optimize the case where the watermark is same width # as page. if page_w == wmark.w: wmark_cache[mbox, not odd] = wmark # Add the watermark to the page PageMerge(page).add(wmark, prepend=self.underneath).render() # Write out the destination file PdfWriter(output_filename, trailer=trailer).write() if self.method is 'pypdf3': return pypdf3() else: return pdfrw()
python
def add(self, document, watermark): """Add watermark to PDF by merging original PDF and watermark file.""" # 5a. Create output PDF file name output_filename = self.output_filename def pypdf3(): """Much slower than PyPDF3 method.""" # 5b. Get our files ready document_reader = PdfFileReader(document) output_file = PdfFileWriter() # Number of pages in input document page_count = document_reader.getNumPages() # Watermark objects watermark_reader = PdfFileReader(watermark) wtrmrk_page = watermark_reader.getPage(0) wtrmrk_width = (wtrmrk_page.mediaBox.getWidth() / 2) + 0 wtrmrk_height = (wtrmrk_page.mediaBox.getHeight() / 2) + 80 wtrmrk_rotate = -int(Info(watermark_reader).rotate) if Info(watermark_reader).rotate is not None else 0 # 5c. Go through all the input file pages to add a watermark to them for page_number in range(page_count): # Merge the watermark with the page if not self.underneath: input_page = document_reader.getPage(page_number) if wtrmrk_rotate is not 0: input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height) else: wtrmrk_width = 0 wtrmrk_height = 0 input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height) else: size = Info(document_reader).dimensions input_page = PageObject().createBlankPage(document_reader, size['w'], size['h']) if wtrmrk_rotate is not 0: input_page.mergeRotatedTranslatedPage(wtrmrk_page, wtrmrk_rotate, wtrmrk_width, wtrmrk_height) else: wtrmrk_width = 0 wtrmrk_height = 0 input_page.mergeTranslatedPage(wtrmrk_page, wtrmrk_width, wtrmrk_height) input_page.mergePage(document_reader.getPage(page_number)) # Add page from input file to output document output_file.addPage(input_page) # 5d. finally, write "output" to PDF with open(output_filename, "wb") as outputStream: output_file.write(outputStream) return output_filename def pdfrw(): """Faster than PyPDF3 method by as much as 15x.""" # TODO: Fix issue where watermark is improperly placed on large pagesize PDFs # print(Info(document).size) # print(Info(watermark).size) # print('\n') # Open both the source files wmark_trailer = PdfReader(watermark) trailer = PdfReader(document) # Handle different sized pages in same document with # a memoization cache, so we don't create more watermark # objects than we need to (typically only one per document). wmark_page = wmark_trailer.pages[0] wmark_cache = {} # Process every page for pagenum, page in enumerate(trailer.pages, 1): # Get the media box of the page, and see # if we have a matching watermark in the cache mbox = tuple(float(x) for x in page.MediaBox) odd = pagenum & 1 key = mbox, odd wmark = wmark_cache.get(key) if wmark is None: # Create and cache a new watermark object. wmark = wmark_cache[key] = PageMerge().add(wmark_page)[0] # The math is more complete than it probably needs to be, # because the origin of all pages is almost always (0, 0). # Nonetheless, we illustrate all the values and their names. page_x, page_y, page_x1, page_y1 = mbox page_w = page_x1 - page_x page_h = page_y1 - page_y # For illustration, not used # Scale the watermark if it is too wide for the page # (Could do the same for height instead if needed) if wmark.w > page_w: wmark.scale(1.0 * page_w / wmark.w) # Always put watermark at the top of the page # (but see horizontal positioning for other ideas) wmark.y += page_y1 - wmark.h # For odd pages, put it at the left of the page, # and for even pages, put it on the right of the page. if odd: wmark.x = page_x else: wmark.x += page_x1 - wmark.w # Optimize the case where the watermark is same width # as page. if page_w == wmark.w: wmark_cache[mbox, not odd] = wmark # Add the watermark to the page PageMerge(page).add(wmark, prepend=self.underneath).render() # Write out the destination file PdfWriter(output_filename, trailer=trailer).write() if self.method is 'pypdf3': return pypdf3() else: return pdfrw()
[ "def", "add", "(", "self", ",", "document", ",", "watermark", ")", ":", "# 5a. Create output PDF file name", "output_filename", "=", "self", ".", "output_filename", "def", "pypdf3", "(", ")", ":", "\"\"\"Much slower than PyPDF3 method.\"\"\"", "# 5b. Get our files ready",...
Add watermark to PDF by merging original PDF and watermark file.
[ "Add", "watermark", "to", "PDF", "by", "merging", "original", "PDF", "and", "watermark", "file", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/conduit/watermark/add.py#L141-L262
train
33,643
mrstephenneal/pdfconduit
sandbox/img_opacity.py
img_opacity
def img_opacity(image, opacity): """ Reduce the opacity of a PNG image. Inspiration: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 :param image: PNG image file :param opacity: float representing opacity percentage :return: Path to modified PNG """ # Validate parameters assert 0 <= opacity <= 1, 'Opacity must be a float between 0 and 1' assert os.path.isfile(image), 'Image is not a file' # Open image in RGBA mode if not already in RGBA im = Image.open(image) if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() # Adjust opacity alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) # Save modified image file dst = _add_suffix(image, str(str(int(opacity * 100)) + '%'), ext='.png') im.save(dst) return dst
python
def img_opacity(image, opacity): """ Reduce the opacity of a PNG image. Inspiration: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 :param image: PNG image file :param opacity: float representing opacity percentage :return: Path to modified PNG """ # Validate parameters assert 0 <= opacity <= 1, 'Opacity must be a float between 0 and 1' assert os.path.isfile(image), 'Image is not a file' # Open image in RGBA mode if not already in RGBA im = Image.open(image) if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() # Adjust opacity alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alpha) # Save modified image file dst = _add_suffix(image, str(str(int(opacity * 100)) + '%'), ext='.png') im.save(dst) return dst
[ "def", "img_opacity", "(", "image", ",", "opacity", ")", ":", "# Validate parameters", "assert", "0", "<=", "opacity", "<=", "1", ",", "'Opacity must be a float between 0 and 1'", "assert", "os", ".", "path", ".", "isfile", "(", "image", ")", ",", "'Image is not...
Reduce the opacity of a PNG image. Inspiration: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879 :param image: PNG image file :param opacity: float representing opacity percentage :return: Path to modified PNG
[ "Reduce", "the", "opacity", "of", "a", "PNG", "image", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/sandbox/img_opacity.py#L18-L47
train
33,644
mrstephenneal/pdfconduit
pdf/convert/img2pdf.py
IMG2PDF._image_loop
def _image_loop(self): """Retrieve an iterable of images either with, or without a progress bar.""" if self.progress_bar and 'tqdm' in self.progress_bar.lower(): return tqdm(self.imgs, desc='Saving PNGs as flat PDFs', total=len(self.imgs), unit='PDFs') else: return self.imgs
python
def _image_loop(self): """Retrieve an iterable of images either with, or without a progress bar.""" if self.progress_bar and 'tqdm' in self.progress_bar.lower(): return tqdm(self.imgs, desc='Saving PNGs as flat PDFs', total=len(self.imgs), unit='PDFs') else: return self.imgs
[ "def", "_image_loop", "(", "self", ")", ":", "if", "self", ".", "progress_bar", "and", "'tqdm'", "in", "self", ".", "progress_bar", ".", "lower", "(", ")", ":", "return", "tqdm", "(", "self", ".", "imgs", ",", "desc", "=", "'Saving PNGs as flat PDFs'", "...
Retrieve an iterable of images either with, or without a progress bar.
[ "Retrieve", "an", "iterable", "of", "images", "either", "with", "or", "without", "a", "progress", "bar", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/convert/img2pdf.py#L40-L45
train
33,645
mrstephenneal/pdfconduit
pdf/convert/img2pdf.py
IMG2PDF._convert
def _convert(self, image, output=None): """Private method for converting a single PNG image to a PDF.""" with Image.open(image) as im: width, height = im.size co = CanvasObjects() co.add(CanvasImg(image, 1.0, w=width, h=height)) return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)
python
def _convert(self, image, output=None): """Private method for converting a single PNG image to a PDF.""" with Image.open(image) as im: width, height = im.size co = CanvasObjects() co.add(CanvasImg(image, 1.0, w=width, h=height)) return WatermarkDraw(co, tempdir=self.tempdir, pagesize=(width, height)).write(output)
[ "def", "_convert", "(", "self", ",", "image", ",", "output", "=", "None", ")", ":", "with", "Image", ".", "open", "(", "image", ")", "as", "im", ":", "width", ",", "height", "=", "im", ".", "size", "co", "=", "CanvasObjects", "(", ")", "co", ".",...
Private method for converting a single PNG image to a PDF.
[ "Private", "method", "for", "converting", "a", "single", "PNG", "image", "to", "a", "PDF", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/convert/img2pdf.py#L47-L55
train
33,646
mrstephenneal/pdfconduit
pdf/convert/img2pdf.py
IMG2PDF.convert
def convert(self, image, output=None): """ Convert an image to a PDF. :param image: Image file path :param output: Output name, same as image name with .pdf extension by default :return: PDF file path """ return self._convert(image, image.replace(Path(image).suffix, '.pdf') if not output else output)
python
def convert(self, image, output=None): """ Convert an image to a PDF. :param image: Image file path :param output: Output name, same as image name with .pdf extension by default :return: PDF file path """ return self._convert(image, image.replace(Path(image).suffix, '.pdf') if not output else output)
[ "def", "convert", "(", "self", ",", "image", ",", "output", "=", "None", ")", ":", "return", "self", ".", "_convert", "(", "image", ",", "image", ".", "replace", "(", "Path", "(", "image", ")", ".", "suffix", ",", "'.pdf'", ")", "if", "not", "outpu...
Convert an image to a PDF. :param image: Image file path :param output: Output name, same as image name with .pdf extension by default :return: PDF file path
[ "Convert", "an", "image", "to", "a", "PDF", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/convert/img2pdf.py#L57-L65
train
33,647
mrstephenneal/pdfconduit
pdf/gui/config/images.py
add
def add(image_path, file_name=None): """Add an image to the GUI img library.""" if file_name is not None: dst_path = os.path.join(IMG_DIR, str(Path(file_name).stem + Path(image_path).suffix)) else: dst_path = IMG_DIR if os.path.isfile(image_path): shutil.copy2(image_path, dst_path)
python
def add(image_path, file_name=None): """Add an image to the GUI img library.""" if file_name is not None: dst_path = os.path.join(IMG_DIR, str(Path(file_name).stem + Path(image_path).suffix)) else: dst_path = IMG_DIR if os.path.isfile(image_path): shutil.copy2(image_path, dst_path)
[ "def", "add", "(", "image_path", ",", "file_name", "=", "None", ")", ":", "if", "file_name", "is", "not", "None", ":", "dst_path", "=", "os", ".", "path", ".", "join", "(", "IMG_DIR", ",", "str", "(", "Path", "(", "file_name", ")", ".", "stem", "+"...
Add an image to the GUI img library.
[ "Add", "an", "image", "to", "the", "GUI", "img", "library", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/gui/config/images.py#L14-L22
train
33,648
mrstephenneal/pdfconduit
pdf/gui/config/images.py
remove
def remove(image): """Remove an image to the GUI img library.""" path = os.path.join(IMG_DIR, image) if os.path.isfile(path): os.remove(path)
python
def remove(image): """Remove an image to the GUI img library.""" path = os.path.join(IMG_DIR, image) if os.path.isfile(path): os.remove(path)
[ "def", "remove", "(", "image", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "IMG_DIR", ",", "image", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os", ".", "remove", "(", "path", ")" ]
Remove an image to the GUI img library.
[ "Remove", "an", "image", "to", "the", "GUI", "img", "library", "." ]
993421cc087eefefe01ff09afabd893bcc2718ec
https://github.com/mrstephenneal/pdfconduit/blob/993421cc087eefefe01ff09afabd893bcc2718ec/pdf/gui/config/images.py#L25-L29
train
33,649
staugur/Flask-PluginKit
flask_pluginkit/web.py
pluginkit_beforerequest
def pluginkit_beforerequest(): """blueprint access auth""" authMethod = current_app.config.get("PLUGINKIT_AUTHMETHOD") authResult = dict(msg=None, code=1, method=authMethod) def authTipmsg(authResult, code=403): """make response message""" return "%s Authentication failed [%s]: %s [%s]" % (code, authResult["method"], authResult["msg"], authResult["code"]) if authMethod == "BOOL": """Boolean Auth""" PLUGINKIT_AUTHFIELD = current_app.config.get("PLUGINKIT_AUTHFIELD") if PLUGINKIT_AUTHFIELD: if PLUGINKIT_AUTHFIELD is True: authResult.update(code=0) else: if hasattr(g, "signin") and g.signin is True: authResult.update(code=0) authResult.update(code=10000, msg="Invalid authentication field") elif authMethod == "BASIC": """HTTP Basic Auth""" #: the realm parameter is reserved for defining protection spaces and #: it's used by the authentication schemes to indicate a scope of protection. #: #: .. versionadded:: 1.2.0 authRealm = current_app.config.get("PLUGINKIT_AUTHREALM") or "Flask-PluginKit Login Required" #: User and password configuration, format {user:pass, user:pass}, #: if format error, all authentication failure by default. #: #: .. versionadded:: 1.2.0 authUsers = current_app.config.get("PLUGINKIT_AUTHUSERS") def verify_auth(username, password): """Check the user and password""" if isinstance(authUsers, dict) and username in authUsers: return password == authUsers[username] return False def not_authenticated(): """Sends a 401 response that enables basic auth""" return Response(authTipmsg(authResult, 401), 401, {'WWW-Authenticate': 'Basic realm="%s"' % authRealm}) #: Intercepts authentication and denies access if it fails auth = request.authorization if not auth or not verify_auth(auth.username, auth.password): authResult.update(code=10001, msg="Invalid username or password") return not_authenticated() else: authResult.update(code=0) else: authResult.update(code=0, msg="No authentication required", method=None) #: return response if code != 0 if authResult["code"] != 0: return make_response(authTipmsg(authResult)), 403 #: get all plugins based flask-pluginkit if hasattr(current_app, "extensions") and "pluginkit" in current_app.extensions: g.plugin_manager = current_app.extensions["pluginkit"] g.plugins = g.plugin_manager.get_all_plugins
python
def pluginkit_beforerequest(): """blueprint access auth""" authMethod = current_app.config.get("PLUGINKIT_AUTHMETHOD") authResult = dict(msg=None, code=1, method=authMethod) def authTipmsg(authResult, code=403): """make response message""" return "%s Authentication failed [%s]: %s [%s]" % (code, authResult["method"], authResult["msg"], authResult["code"]) if authMethod == "BOOL": """Boolean Auth""" PLUGINKIT_AUTHFIELD = current_app.config.get("PLUGINKIT_AUTHFIELD") if PLUGINKIT_AUTHFIELD: if PLUGINKIT_AUTHFIELD is True: authResult.update(code=0) else: if hasattr(g, "signin") and g.signin is True: authResult.update(code=0) authResult.update(code=10000, msg="Invalid authentication field") elif authMethod == "BASIC": """HTTP Basic Auth""" #: the realm parameter is reserved for defining protection spaces and #: it's used by the authentication schemes to indicate a scope of protection. #: #: .. versionadded:: 1.2.0 authRealm = current_app.config.get("PLUGINKIT_AUTHREALM") or "Flask-PluginKit Login Required" #: User and password configuration, format {user:pass, user:pass}, #: if format error, all authentication failure by default. #: #: .. versionadded:: 1.2.0 authUsers = current_app.config.get("PLUGINKIT_AUTHUSERS") def verify_auth(username, password): """Check the user and password""" if isinstance(authUsers, dict) and username in authUsers: return password == authUsers[username] return False def not_authenticated(): """Sends a 401 response that enables basic auth""" return Response(authTipmsg(authResult, 401), 401, {'WWW-Authenticate': 'Basic realm="%s"' % authRealm}) #: Intercepts authentication and denies access if it fails auth = request.authorization if not auth or not verify_auth(auth.username, auth.password): authResult.update(code=10001, msg="Invalid username or password") return not_authenticated() else: authResult.update(code=0) else: authResult.update(code=0, msg="No authentication required", method=None) #: return response if code != 0 if authResult["code"] != 0: return make_response(authTipmsg(authResult)), 403 #: get all plugins based flask-pluginkit if hasattr(current_app, "extensions") and "pluginkit" in current_app.extensions: g.plugin_manager = current_app.extensions["pluginkit"] g.plugins = g.plugin_manager.get_all_plugins
[ "def", "pluginkit_beforerequest", "(", ")", ":", "authMethod", "=", "current_app", ".", "config", ".", "get", "(", "\"PLUGINKIT_AUTHMETHOD\"", ")", "authResult", "=", "dict", "(", "msg", "=", "None", ",", "code", "=", "1", ",", "method", "=", "authMethod", ...
blueprint access auth
[ "blueprint", "access", "auth" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/web.py#L29-L93
train
33,650
staugur/Flask-PluginKit
flask_pluginkit/flask_pluginkit.py
PluginManager.__scanPlugins
def __scanPlugins(self): """Scanning local plugin directories and third-party plugin packages. :returns: No return, but self.__plugins will be updated :raises: PluginError: raises an exception, maybe CSSLoadError, VersionError, based PluginError """ self.logger.info("Initialization Plugins Start, local plugins path: %s, third party plugins: %s" % (self.plugins_abspath, self.plugin_packages)) #: Load third-party plugins if self.plugin_packages and isinstance(self.plugin_packages, (list, tuple)): for package_name in self.plugin_packages: try: plugin = __import__(package_name) except ImportError as e: raise PluginError("ImportError for %s, detail is %s" %(package_name, e)) else: plugin_abspath = os.path.dirname(os.path.abspath(plugin.__file__)) self.__loadPlugin(plugin, plugin_abspath, package_name) #: Load local plug-in directory if os.path.isdir(self.plugins_abspath) and os.path.isfile(os.path.join(self.plugins_abspath, "__init__.py")): for package_name in os.listdir(self.plugins_abspath): package_abspath = os.path.join(self.plugins_abspath, package_name) if os.path.isdir(package_abspath) and os.path.isfile(os.path.join(package_abspath, "__init__.py")): self.logger.info("find plugin package: %s" % package_name) #: Dynamic load module (plugins.package): you can query custom information and get the plugin's class definition through getPluginClass plugin = __import__("{0}.{1}".format(self.plugins_folder, package_name), fromlist=[self.plugins_folder, ]) self.__loadPlugin(plugin, package_abspath, package_name)
python
def __scanPlugins(self): """Scanning local plugin directories and third-party plugin packages. :returns: No return, but self.__plugins will be updated :raises: PluginError: raises an exception, maybe CSSLoadError, VersionError, based PluginError """ self.logger.info("Initialization Plugins Start, local plugins path: %s, third party plugins: %s" % (self.plugins_abspath, self.plugin_packages)) #: Load third-party plugins if self.plugin_packages and isinstance(self.plugin_packages, (list, tuple)): for package_name in self.plugin_packages: try: plugin = __import__(package_name) except ImportError as e: raise PluginError("ImportError for %s, detail is %s" %(package_name, e)) else: plugin_abspath = os.path.dirname(os.path.abspath(plugin.__file__)) self.__loadPlugin(plugin, plugin_abspath, package_name) #: Load local plug-in directory if os.path.isdir(self.plugins_abspath) and os.path.isfile(os.path.join(self.plugins_abspath, "__init__.py")): for package_name in os.listdir(self.plugins_abspath): package_abspath = os.path.join(self.plugins_abspath, package_name) if os.path.isdir(package_abspath) and os.path.isfile(os.path.join(package_abspath, "__init__.py")): self.logger.info("find plugin package: %s" % package_name) #: Dynamic load module (plugins.package): you can query custom information and get the plugin's class definition through getPluginClass plugin = __import__("{0}.{1}".format(self.plugins_folder, package_name), fromlist=[self.plugins_folder, ]) self.__loadPlugin(plugin, package_abspath, package_name)
[ "def", "__scanPlugins", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Initialization Plugins Start, local plugins path: %s, third party plugins: %s\"", "%", "(", "self", ".", "plugins_abspath", ",", "self", ".", "plugin_packages", ")", ")", "#: Lo...
Scanning local plugin directories and third-party plugin packages. :returns: No return, but self.__plugins will be updated :raises: PluginError: raises an exception, maybe CSSLoadError, VersionError, based PluginError
[ "Scanning", "local", "plugin", "directories", "and", "third", "-", "party", "plugin", "packages", "." ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L245-L273
train
33,651
staugur/Flask-PluginKit
flask_pluginkit/flask_pluginkit.py
PluginManager.__getPluginInfo
def __getPluginInfo(self, plugin, package_abspath, package_name): """ Organize plugin information. :returns: dict: plugin info """ if not isValidSemver(plugin.__version__): raise VersionError("The plugin version does not conform to the standard named %s" % package_name) try: url = plugin.__url__ except AttributeError: url = None try: license = plugin.__license__ except AttributeError: license = None try: license_file = plugin.__license_file__ except AttributeError: license_file = None try: readme_file = plugin.__readme_file__ except AttributeError: readme_file = None try: plugin_state = plugin.__state__ except AttributeError: plugin_state = "enabled" # 插件状态首先读取`__state`状态值,优先级低于状态文件,ENABLED文件优先级低于DISABLED文件 if os.path.isfile(os.path.join(package_abspath, "ENABLED")): plugin_state = "enabled" if os.path.isfile(os.path.join(package_abspath, "DISABLED")): plugin_state = "disabled" return { "plugin_name": plugin.__plugin_name__, "plugin_package_name": package_name, "plugin_package_abspath": package_abspath, "plugin_description": plugin.__description__, "plugin_version": plugin.__version__, "plugin_author": plugin.__author__, "plugin_url": url, "plugin_license": license, "plugin_license_file": license_file, "plugin_readme_file": readme_file, "plugin_state": plugin_state, "plugin_tpl_path": os.path.join(package_abspath, "templates"), "plugin_ats_path": os.path.join(package_abspath, "static"), "plugin_tep": {}, "plugin_hep": {}, "plugin_bep": {}, "plugin_yep": {} }
python
def __getPluginInfo(self, plugin, package_abspath, package_name): """ Organize plugin information. :returns: dict: plugin info """ if not isValidSemver(plugin.__version__): raise VersionError("The plugin version does not conform to the standard named %s" % package_name) try: url = plugin.__url__ except AttributeError: url = None try: license = plugin.__license__ except AttributeError: license = None try: license_file = plugin.__license_file__ except AttributeError: license_file = None try: readme_file = plugin.__readme_file__ except AttributeError: readme_file = None try: plugin_state = plugin.__state__ except AttributeError: plugin_state = "enabled" # 插件状态首先读取`__state`状态值,优先级低于状态文件,ENABLED文件优先级低于DISABLED文件 if os.path.isfile(os.path.join(package_abspath, "ENABLED")): plugin_state = "enabled" if os.path.isfile(os.path.join(package_abspath, "DISABLED")): plugin_state = "disabled" return { "plugin_name": plugin.__plugin_name__, "plugin_package_name": package_name, "plugin_package_abspath": package_abspath, "plugin_description": plugin.__description__, "plugin_version": plugin.__version__, "plugin_author": plugin.__author__, "plugin_url": url, "plugin_license": license, "plugin_license_file": license_file, "plugin_readme_file": readme_file, "plugin_state": plugin_state, "plugin_tpl_path": os.path.join(package_abspath, "templates"), "plugin_ats_path": os.path.join(package_abspath, "static"), "plugin_tep": {}, "plugin_hep": {}, "plugin_bep": {}, "plugin_yep": {} }
[ "def", "__getPluginInfo", "(", "self", ",", "plugin", ",", "package_abspath", ",", "package_name", ")", ":", "if", "not", "isValidSemver", "(", "plugin", ".", "__version__", ")", ":", "raise", "VersionError", "(", "\"The plugin version does not conform to the standard...
Organize plugin information. :returns: dict: plugin info
[ "Organize", "plugin", "information", "." ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L411-L467
train
33,652
staugur/Flask-PluginKit
flask_pluginkit/flask_pluginkit.py
PluginManager.get_plugin_info
def get_plugin_info(self, plugin_name): """Get plugin information""" if plugin_name: for i in self.get_all_plugins: if i["plugin_name"] == plugin_name: return i
python
def get_plugin_info(self, plugin_name): """Get plugin information""" if plugin_name: for i in self.get_all_plugins: if i["plugin_name"] == plugin_name: return i
[ "def", "get_plugin_info", "(", "self", ",", "plugin_name", ")", ":", "if", "plugin_name", ":", "for", "i", "in", "self", ".", "get_all_plugins", ":", "if", "i", "[", "\"plugin_name\"", "]", "==", "plugin_name", ":", "return", "i" ]
Get plugin information
[ "Get", "plugin", "information" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L474-L479
train
33,653
staugur/Flask-PluginKit
flask_pluginkit/flask_pluginkit.py
PluginManager.get_all_tep
def get_all_tep(self): """Template extension point :returns: dict: {tep: dict(HTMLFile=[], HTMLString=[]), tep...} """ teps = {} for p in self.get_enabled_plugins: for e, v in p["plugin_tep"].items(): tep = teps.get(e, dict()) tepHF = tep.get("HTMLFile", []) tepHS = tep.get("HTMLString", []) tepHF += [s for f, s in v.items() if f == "HTMLFile"] tepHS += [s for f, s in v.items() if f == "HTMLString"] teps[e] = dict(HTMLFile=tepHF, HTMLString=tepHS) return teps
python
def get_all_tep(self): """Template extension point :returns: dict: {tep: dict(HTMLFile=[], HTMLString=[]), tep...} """ teps = {} for p in self.get_enabled_plugins: for e, v in p["plugin_tep"].items(): tep = teps.get(e, dict()) tepHF = tep.get("HTMLFile", []) tepHS = tep.get("HTMLString", []) tepHF += [s for f, s in v.items() if f == "HTMLFile"] tepHS += [s for f, s in v.items() if f == "HTMLString"] teps[e] = dict(HTMLFile=tepHF, HTMLString=tepHS) return teps
[ "def", "get_all_tep", "(", "self", ")", ":", "teps", "=", "{", "}", "for", "p", "in", "self", ".", "get_enabled_plugins", ":", "for", "e", ",", "v", "in", "p", "[", "\"plugin_tep\"", "]", ".", "items", "(", ")", ":", "tep", "=", "teps", ".", "get...
Template extension point :returns: dict: {tep: dict(HTMLFile=[], HTMLString=[]), tep...}
[ "Template", "extension", "point" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L510-L524
train
33,654
staugur/Flask-PluginKit
flask_pluginkit/flask_pluginkit.py
PluginManager.get_all_hep
def get_all_hep(self): """Hook extension point. * before_request_hook, Before request (intercept requests are allowed) * before_request_top_hook, Before top request (Put it first) * after_request_hook, After request (no exception before return) * teardown_request_hook, After request (before return, with or without exception) """ return dict( before_request_hook=[plugin["plugin_hep"]["before_request_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("before_request_hook")], before_request_top_hook=[plugin["plugin_hep"]["before_request_top_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("before_request_top_hook")], after_request_hook=[plugin["plugin_hep"]["after_request_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("after_request_hook")], teardown_request_hook=[plugin["plugin_hep"]["teardown_request_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("teardown_request_hook")], )
python
def get_all_hep(self): """Hook extension point. * before_request_hook, Before request (intercept requests are allowed) * before_request_top_hook, Before top request (Put it first) * after_request_hook, After request (no exception before return) * teardown_request_hook, After request (before return, with or without exception) """ return dict( before_request_hook=[plugin["plugin_hep"]["before_request_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("before_request_hook")], before_request_top_hook=[plugin["plugin_hep"]["before_request_top_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("before_request_top_hook")], after_request_hook=[plugin["plugin_hep"]["after_request_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("after_request_hook")], teardown_request_hook=[plugin["plugin_hep"]["teardown_request_hook"] for plugin in self.get_enabled_plugins if plugin["plugin_hep"].get("teardown_request_hook")], )
[ "def", "get_all_hep", "(", "self", ")", ":", "return", "dict", "(", "before_request_hook", "=", "[", "plugin", "[", "\"plugin_hep\"", "]", "[", "\"before_request_hook\"", "]", "for", "plugin", "in", "self", ".", "get_enabled_plugins", "if", "plugin", "[", "\"p...
Hook extension point. * before_request_hook, Before request (intercept requests are allowed) * before_request_top_hook, Before top request (Put it first) * after_request_hook, After request (no exception before return) * teardown_request_hook, After request (before return, with or without exception)
[ "Hook", "extension", "point", "." ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L527-L543
train
33,655
staugur/Flask-PluginKit
flask_pluginkit/flask_pluginkit.py
PluginManager.push_dcp
def push_dcp(self, event, callback, position="right"): """Connect a dcp, push a function. :param event: str,unicode: A unique identifier name for dcp. :param callback: callable: Corresponding to the event to perform a function. :param position: The position of the insertion function, right(default) and left. :raises: DCPError,NotCallableError: raises an exception .. versionadded:: 2.1.0 """ if event and isinstance(event, string_types) and callable(callback) and position in ("left", "right"): if event in self._dcp_funcs: if position == "right": self._dcp_funcs[event].append(callback) else: self._dcp_funcs[event].appendleft(callback) else: self._dcp_funcs[event] = deque([callback]) else: if not callable(callback): raise NotCallableError("The event %s cannot be called back" % event) raise DCPError("Invalid parameter")
python
def push_dcp(self, event, callback, position="right"): """Connect a dcp, push a function. :param event: str,unicode: A unique identifier name for dcp. :param callback: callable: Corresponding to the event to perform a function. :param position: The position of the insertion function, right(default) and left. :raises: DCPError,NotCallableError: raises an exception .. versionadded:: 2.1.0 """ if event and isinstance(event, string_types) and callable(callback) and position in ("left", "right"): if event in self._dcp_funcs: if position == "right": self._dcp_funcs[event].append(callback) else: self._dcp_funcs[event].appendleft(callback) else: self._dcp_funcs[event] = deque([callback]) else: if not callable(callback): raise NotCallableError("The event %s cannot be called back" % event) raise DCPError("Invalid parameter")
[ "def", "push_dcp", "(", "self", ",", "event", ",", "callback", ",", "position", "=", "\"right\"", ")", ":", "if", "event", "and", "isinstance", "(", "event", ",", "string_types", ")", "and", "callable", "(", "callback", ")", "and", "position", "in", "(",...
Connect a dcp, push a function. :param event: str,unicode: A unique identifier name for dcp. :param callback: callable: Corresponding to the event to perform a function. :param position: The position of the insertion function, right(default) and left. :raises: DCPError,NotCallableError: raises an exception .. versionadded:: 2.1.0
[ "Connect", "a", "dcp", "push", "a", "function", "." ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L649-L673
train
33,656
staugur/Flask-PluginKit
flask_pluginkit/flask_pluginkit.py
PluginManager.push_func
def push_func(self, cuin, callback): """Push a function for dfp. :param cuin: str,unicode: Callback Unique Identifier Name. :param callback: callable: Corresponding to the cuin to perform a function. :raises: DFPError,NotCallableError: raises an exception .. versionadded:: 2.3.0 """ if cuin and isinstance(cuin, string_types) and callable(callback): if cuin in self._dfp_funcs: raise DFPError("The cuin already exists") else: self._dfp_funcs[cuin] = callback else: if not callable(callback): raise NotCallableError("The cuin %s cannot be called back" % cuin) raise DFPError("Invalid parameter")
python
def push_func(self, cuin, callback): """Push a function for dfp. :param cuin: str,unicode: Callback Unique Identifier Name. :param callback: callable: Corresponding to the cuin to perform a function. :raises: DFPError,NotCallableError: raises an exception .. versionadded:: 2.3.0 """ if cuin and isinstance(cuin, string_types) and callable(callback): if cuin in self._dfp_funcs: raise DFPError("The cuin already exists") else: self._dfp_funcs[cuin] = callback else: if not callable(callback): raise NotCallableError("The cuin %s cannot be called back" % cuin) raise DFPError("Invalid parameter")
[ "def", "push_func", "(", "self", ",", "cuin", ",", "callback", ")", ":", "if", "cuin", "and", "isinstance", "(", "cuin", ",", "string_types", ")", "and", "callable", "(", "callback", ")", ":", "if", "cuin", "in", "self", ".", "_dfp_funcs", ":", "raise"...
Push a function for dfp. :param cuin: str,unicode: Callback Unique Identifier Name. :param callback: callable: Corresponding to the cuin to perform a function. :raises: DFPError,NotCallableError: raises an exception .. versionadded:: 2.3.0
[ "Push", "a", "function", "for", "dfp", "." ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/flask_pluginkit.py#L697-L716
train
33,657
staugur/Flask-PluginKit
setup.py
PublishCommand.finalize_options
def finalize_options(self): """Post-process options.""" if self.test: print("V%s will publish to the test.pypi.org" % version) elif self.release: print("V%s will publish to the pypi.org" % version)
python
def finalize_options(self): """Post-process options.""" if self.test: print("V%s will publish to the test.pypi.org" % version) elif self.release: print("V%s will publish to the pypi.org" % version)
[ "def", "finalize_options", "(", "self", ")", ":", "if", "self", ".", "test", ":", "print", "(", "\"V%s will publish to the test.pypi.org\"", "%", "version", ")", "elif", "self", ".", "release", ":", "print", "(", "\"V%s will publish to the pypi.org\"", "%", "versi...
Post-process options.
[ "Post", "-", "process", "options", "." ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/setup.py#L57-L62
train
33,658
staugur/Flask-PluginKit
example/plugins/jwt/utils.py
JWTUtil.signatureJWT
def signatureJWT(self, message): """ Python generate HMAC-SHA-256 from string """ return hmac.new( key=self.secretkey, msg=message, digestmod=hashlib.sha256 ).hexdigest()
python
def signatureJWT(self, message): """ Python generate HMAC-SHA-256 from string """ return hmac.new( key=self.secretkey, msg=message, digestmod=hashlib.sha256 ).hexdigest()
[ "def", "signatureJWT", "(", "self", ",", "message", ")", ":", "return", "hmac", ".", "new", "(", "key", "=", "self", ".", "secretkey", ",", "msg", "=", "message", ",", "digestmod", "=", "hashlib", ".", "sha256", ")", ".", "hexdigest", "(", ")" ]
Python generate HMAC-SHA-256 from string
[ "Python", "generate", "HMAC", "-", "SHA", "-", "256", "from", "string" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/example/plugins/jwt/utils.py#L77-L83
train
33,659
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller.__isValidTGZ
def __isValidTGZ(self, suffix): """To determine whether the suffix `.tar.gz` or `.tgz` format""" if suffix and isinstance(suffix, string_types): if suffix.endswith(".tar.gz") or suffix.endswith(".tgz"): return True return False
python
def __isValidTGZ(self, suffix): """To determine whether the suffix `.tar.gz` or `.tgz` format""" if suffix and isinstance(suffix, string_types): if suffix.endswith(".tar.gz") or suffix.endswith(".tgz"): return True return False
[ "def", "__isValidTGZ", "(", "self", ",", "suffix", ")", ":", "if", "suffix", "and", "isinstance", "(", "suffix", ",", "string_types", ")", ":", "if", "suffix", ".", "endswith", "(", "\".tar.gz\"", ")", "or", "suffix", ".", "endswith", "(", "\".tgz\"", ")...
To determine whether the suffix `.tar.gz` or `.tgz` format
[ "To", "determine", "whether", "the", "suffix", ".", "tar", ".", "gz", "or", ".", "tgz", "format" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L67-L72
train
33,660
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller.__isValidZIP
def __isValidZIP(self, suffix): """Determine if the suffix is `.zip` format""" if suffix and isinstance(suffix, string_types): if suffix.endswith(".zip"): return True return False
python
def __isValidZIP(self, suffix): """Determine if the suffix is `.zip` format""" if suffix and isinstance(suffix, string_types): if suffix.endswith(".zip"): return True return False
[ "def", "__isValidZIP", "(", "self", ",", "suffix", ")", ":", "if", "suffix", "and", "isinstance", "(", "suffix", ",", "string_types", ")", ":", "if", "suffix", ".", "endswith", "(", "\".zip\"", ")", ":", "return", "True", "return", "False" ]
Determine if the suffix is `.zip` format
[ "Determine", "if", "the", "suffix", "is", ".", "zip", "format" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L74-L79
train
33,661
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller.__isValidFilename
def __isValidFilename(self, filename): """Determine whether filename is valid""" if filename and isinstance(filename, string_types): if re.match(r'^[\w\d\_\-\.]+$', filename, re.I): if self.__isValidTGZ(filename) or self.__isValidZIP(filename): return True return False
python
def __isValidFilename(self, filename): """Determine whether filename is valid""" if filename and isinstance(filename, string_types): if re.match(r'^[\w\d\_\-\.]+$', filename, re.I): if self.__isValidTGZ(filename) or self.__isValidZIP(filename): return True return False
[ "def", "__isValidFilename", "(", "self", ",", "filename", ")", ":", "if", "filename", "and", "isinstance", "(", "filename", ",", "string_types", ")", ":", "if", "re", ".", "match", "(", "r'^[\\w\\d\\_\\-\\.]+$'", ",", "filename", ",", "re", ".", "I", ")", ...
Determine whether filename is valid
[ "Determine", "whether", "filename", "is", "valid" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L81-L87
train
33,662
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller.__getFilename
def __getFilename(self, data, scene=1): """To get the data from different scenarios in the filename, scene value see `remote_download` in 1, 2, 3, 4""" try: filename = None if scene == 1: plugin_filename = [i for i in parse_qs(urlsplit(data).query).get("plugin_filename") or [] if i] if plugin_filename and len(plugin_filename) == 1: filename = plugin_filename[0] elif scene == 2: filename = basename(urlsplit(data).path) elif scene == 3: if PY2: cd = data.headers.getheader("Content-Disposition", "") else: cd = data.getheader("Content-Disposition", "") filename = parse_header(cd)[-1].get("filename") elif scene == 4: if PY2: cd = data.info().subtype else: cd = data.info().get_content_subtype() mt = {'zip': 'zip', 'x-compressed-tar': 'tar.gz', 'x-gzip': 'tar.gz'} subtype = mt.get(cd) if subtype: filename = "." + subtype except Exception as e: self.logger.warning(e) else: if self.__isValidFilename(filename): return filename
python
def __getFilename(self, data, scene=1): """To get the data from different scenarios in the filename, scene value see `remote_download` in 1, 2, 3, 4""" try: filename = None if scene == 1: plugin_filename = [i for i in parse_qs(urlsplit(data).query).get("plugin_filename") or [] if i] if plugin_filename and len(plugin_filename) == 1: filename = plugin_filename[0] elif scene == 2: filename = basename(urlsplit(data).path) elif scene == 3: if PY2: cd = data.headers.getheader("Content-Disposition", "") else: cd = data.getheader("Content-Disposition", "") filename = parse_header(cd)[-1].get("filename") elif scene == 4: if PY2: cd = data.info().subtype else: cd = data.info().get_content_subtype() mt = {'zip': 'zip', 'x-compressed-tar': 'tar.gz', 'x-gzip': 'tar.gz'} subtype = mt.get(cd) if subtype: filename = "." + subtype except Exception as e: self.logger.warning(e) else: if self.__isValidFilename(filename): return filename
[ "def", "__getFilename", "(", "self", ",", "data", ",", "scene", "=", "1", ")", ":", "try", ":", "filename", "=", "None", "if", "scene", "==", "1", ":", "plugin_filename", "=", "[", "i", "for", "i", "in", "parse_qs", "(", "urlsplit", "(", "data", ")...
To get the data from different scenarios in the filename, scene value see `remote_download` in 1, 2, 3, 4
[ "To", "get", "the", "data", "from", "different", "scenarios", "in", "the", "filename", "scene", "value", "see", "remote_download", "in", "1", "2", "3", "4" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L89-L118
train
33,663
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller.__getFilenameSuffix
def __getFilenameSuffix(self, filename): """Gets the filename suffix""" if filename and isinstance(filename, string_types): if self.__isValidTGZ(filename): return ".tar.gz" elif filename.endswith(".zip"): return ".zip"
python
def __getFilenameSuffix(self, filename): """Gets the filename suffix""" if filename and isinstance(filename, string_types): if self.__isValidTGZ(filename): return ".tar.gz" elif filename.endswith(".zip"): return ".zip"
[ "def", "__getFilenameSuffix", "(", "self", ",", "filename", ")", ":", "if", "filename", "and", "isinstance", "(", "filename", ",", "string_types", ")", ":", "if", "self", ".", "__isValidTGZ", "(", "filename", ")", ":", "return", "\".tar.gz\"", "elif", "filen...
Gets the filename suffix
[ "Gets", "the", "filename", "suffix" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L120-L126
train
33,664
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller.__unpack_tgz
def __unpack_tgz(self, filename): """Unpack the `tar.gz`, `tgz` compressed file format""" if isinstance(filename, string_types) and self.__isValidTGZ(filename) and tarfile.is_tarfile(filename): with tarfile.open(filename, mode='r:gz') as t: for name in t.getnames(): t.extract(name, self.plugin_abspath) else: raise TarError("Invalid Plugin Compressed File")
python
def __unpack_tgz(self, filename): """Unpack the `tar.gz`, `tgz` compressed file format""" if isinstance(filename, string_types) and self.__isValidTGZ(filename) and tarfile.is_tarfile(filename): with tarfile.open(filename, mode='r:gz') as t: for name in t.getnames(): t.extract(name, self.plugin_abspath) else: raise TarError("Invalid Plugin Compressed File")
[ "def", "__unpack_tgz", "(", "self", ",", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "string_types", ")", "and", "self", ".", "__isValidTGZ", "(", "filename", ")", "and", "tarfile", ".", "is_tarfile", "(", "filename", ")", ":", "with", ...
Unpack the `tar.gz`, `tgz` compressed file format
[ "Unpack", "the", "tar", ".", "gz", "tgz", "compressed", "file", "format" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L128-L135
train
33,665
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller.__unpack_zip
def __unpack_zip(self, filename): """Unpack the `zip` compressed file format""" if isinstance(filename, string_types) and self.__isValidZIP(filename) and zipfile.is_zipfile(filename): with zipfile.ZipFile(filename) as z: for name in z.namelist(): z.extract(name, self.plugin_abspath) else: raise ZipError("Invalid Plugin Compressed File")
python
def __unpack_zip(self, filename): """Unpack the `zip` compressed file format""" if isinstance(filename, string_types) and self.__isValidZIP(filename) and zipfile.is_zipfile(filename): with zipfile.ZipFile(filename) as z: for name in z.namelist(): z.extract(name, self.plugin_abspath) else: raise ZipError("Invalid Plugin Compressed File")
[ "def", "__unpack_zip", "(", "self", ",", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "string_types", ")", "and", "self", ".", "__isValidZIP", "(", "filename", ")", "and", "zipfile", ".", "is_zipfile", "(", "filename", ")", ":", "with", ...
Unpack the `zip` compressed file format
[ "Unpack", "the", "zip", "compressed", "file", "format" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L137-L144
train
33,666
staugur/Flask-PluginKit
flask_pluginkit/installer.py
PluginInstaller._local_upload
def _local_upload(self, filepath, remove=False): """Local plugin package processing""" if os.path.isfile(filepath): filename = os.path.basename(os.path.abspath(filepath)) if filename and self.__isValidFilename(filename): suffix = self.__getFilenameSuffix(filename) try: self.__unpack_tgz(os.path.abspath(filepath)) if self.__isValidTGZ(suffix) else self.__unpack_zip(os.path.abspath(filepath)) finally: if remove is True: os.remove(filepath) else: raise InstallError("Invalid Filename") else: raise InstallError("Invalid Filepath")
python
def _local_upload(self, filepath, remove=False): """Local plugin package processing""" if os.path.isfile(filepath): filename = os.path.basename(os.path.abspath(filepath)) if filename and self.__isValidFilename(filename): suffix = self.__getFilenameSuffix(filename) try: self.__unpack_tgz(os.path.abspath(filepath)) if self.__isValidTGZ(suffix) else self.__unpack_zip(os.path.abspath(filepath)) finally: if remove is True: os.remove(filepath) else: raise InstallError("Invalid Filename") else: raise InstallError("Invalid Filepath")
[ "def", "_local_upload", "(", "self", ",", "filepath", ",", "remove", "=", "False", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filepath", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "os", ".", "path", ".", "abspa...
Local plugin package processing
[ "Local", "plugin", "package", "processing" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/installer.py#L190-L204
train
33,667
staugur/Flask-PluginKit
flask_pluginkit/utils.py
sortedSemver
def sortedSemver(versions, sort="asc"): """Semantically sort the list of version Numbers""" if versions and isinstance(versions, (list, tuple)): if PY2: return sorted(versions, cmp=semver.compare, reverse=True if sort.upper() == "DESC" else False) else: from functools import cmp_to_key return sorted(versions, key=cmp_to_key(semver.compare), reverse=True if sort.upper() == "DESC" else False) else: raise TypeError("Invaild Versions, a list or tuple is right.")
python
def sortedSemver(versions, sort="asc"): """Semantically sort the list of version Numbers""" if versions and isinstance(versions, (list, tuple)): if PY2: return sorted(versions, cmp=semver.compare, reverse=True if sort.upper() == "DESC" else False) else: from functools import cmp_to_key return sorted(versions, key=cmp_to_key(semver.compare), reverse=True if sort.upper() == "DESC" else False) else: raise TypeError("Invaild Versions, a list or tuple is right.")
[ "def", "sortedSemver", "(", "versions", ",", "sort", "=", "\"asc\"", ")", ":", "if", "versions", "and", "isinstance", "(", "versions", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "PY2", ":", "return", "sorted", "(", "versions", ",", "cmp", "...
Semantically sort the list of version Numbers
[ "Semantically", "sort", "the", "list", "of", "version", "Numbers" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/utils.py#L141-L150
train
33,668
staugur/Flask-PluginKit
flask_pluginkit/utils.py
LocalStorage.set
def set(self, key, value): """Set persistent data with shelve. :param key: string: Index key :param value: All supported data types in python :raises: :returns: """ db = self.open() try: db[key] = value finally: db.close()
python
def set(self, key, value): """Set persistent data with shelve. :param key: string: Index key :param value: All supported data types in python :raises: :returns: """ db = self.open() try: db[key] = value finally: db.close()
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "db", "=", "self", ".", "open", "(", ")", "try", ":", "db", "[", "key", "]", "=", "value", "finally", ":", "db", ".", "close", "(", ")" ]
Set persistent data with shelve. :param key: string: Index key :param value: All supported data types in python :raises: :returns:
[ "Set", "persistent", "data", "with", "shelve", "." ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/utils.py#L49-L64
train
33,669
staugur/Flask-PluginKit
flask_pluginkit/utils.py
RedisStorage.set
def set(self, key, value): """set key data""" if self._db: self._db.hset(self.index, key, value)
python
def set(self, key, value): """set key data""" if self._db: self._db.hset(self.index, key, value)
[ "def", "set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_db", ":", "self", ".", "_db", ".", "hset", "(", "self", ".", "index", ",", "key", ",", "value", ")" ]
set key data
[ "set", "key", "data" ]
512aabf87fa13f4dc1082abd08d1d1dcf3b03f16
https://github.com/staugur/Flask-PluginKit/blob/512aabf87fa13f4dc1082abd08d1d1dcf3b03f16/flask_pluginkit/utils.py#L114-L117
train
33,670
wright-group/WrightTools
WrightTools/kit/_list.py
flatten_list
def flatten_list(items, seqtypes=(list, tuple), in_place=True): """Flatten an irregular sequence. Works generally but may be slower than it could be if you can make assumptions about your list. `Source`__ __ https://stackoverflow.com/a/10824086 Parameters ---------- items : iterable The irregular sequence to flatten. seqtypes : iterable of types (optional) Types to flatten. Default is (list, tuple). in_place : boolean (optional) Toggle in_place flattening. Default is True. Returns ------- list Flattened list. Examples -------- >>> l = [[[1, 2, 3], [4, 5]], 6] >>> wt.kit.flatten_list(l) [1, 2, 3, 4, 5, 6] """ if not in_place: items = items[:] for i, _ in enumerate(items): while i < len(items) and isinstance(items[i], seqtypes): items[i : i + 1] = items[i] return items
python
def flatten_list(items, seqtypes=(list, tuple), in_place=True): """Flatten an irregular sequence. Works generally but may be slower than it could be if you can make assumptions about your list. `Source`__ __ https://stackoverflow.com/a/10824086 Parameters ---------- items : iterable The irregular sequence to flatten. seqtypes : iterable of types (optional) Types to flatten. Default is (list, tuple). in_place : boolean (optional) Toggle in_place flattening. Default is True. Returns ------- list Flattened list. Examples -------- >>> l = [[[1, 2, 3], [4, 5]], 6] >>> wt.kit.flatten_list(l) [1, 2, 3, 4, 5, 6] """ if not in_place: items = items[:] for i, _ in enumerate(items): while i < len(items) and isinstance(items[i], seqtypes): items[i : i + 1] = items[i] return items
[ "def", "flatten_list", "(", "items", ",", "seqtypes", "=", "(", "list", ",", "tuple", ")", ",", "in_place", "=", "True", ")", ":", "if", "not", "in_place", ":", "items", "=", "items", "[", ":", "]", "for", "i", ",", "_", "in", "enumerate", "(", "...
Flatten an irregular sequence. Works generally but may be slower than it could be if you can make assumptions about your list. `Source`__ __ https://stackoverflow.com/a/10824086 Parameters ---------- items : iterable The irregular sequence to flatten. seqtypes : iterable of types (optional) Types to flatten. Default is (list, tuple). in_place : boolean (optional) Toggle in_place flattening. Default is True. Returns ------- list Flattened list. Examples -------- >>> l = [[[1, 2, 3], [4, 5]], 6] >>> wt.kit.flatten_list(l) [1, 2, 3, 4, 5, 6]
[ "Flatten", "an", "irregular", "sequence", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_list.py#L17-L52
train
33,671
wright-group/WrightTools
WrightTools/kit/_list.py
intersperse
def intersperse(lis, value): """Put value between each existing item in list. Parameters ---------- lis : list List to intersperse. value : object Value to insert. Returns ------- list interspersed list """ out = [value] * (len(lis) * 2 - 1) out[0::2] = lis return out
python
def intersperse(lis, value): """Put value between each existing item in list. Parameters ---------- lis : list List to intersperse. value : object Value to insert. Returns ------- list interspersed list """ out = [value] * (len(lis) * 2 - 1) out[0::2] = lis return out
[ "def", "intersperse", "(", "lis", ",", "value", ")", ":", "out", "=", "[", "value", "]", "*", "(", "len", "(", "lis", ")", "*", "2", "-", "1", ")", "out", "[", "0", ":", ":", "2", "]", "=", "lis", "return", "out" ]
Put value between each existing item in list. Parameters ---------- lis : list List to intersperse. value : object Value to insert. Returns ------- list interspersed list
[ "Put", "value", "between", "each", "existing", "item", "in", "list", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_list.py#L55-L72
train
33,672
wright-group/WrightTools
WrightTools/kit/_list.py
get_index
def get_index(lis, argument): """Find the index of an item, given either the item or index as an argument. Particularly useful as a wrapper for arguments like channel or axis. Parameters ---------- lis : list List to parse. argument : int or object Argument. Returns ------- int Index of chosen object. """ # get channel if isinstance(argument, int): if -len(lis) <= argument < len(lis): return argument else: raise IndexError("index {0} incompatible with length {1}".format(argument, len(lis))) else: return lis.index(argument)
python
def get_index(lis, argument): """Find the index of an item, given either the item or index as an argument. Particularly useful as a wrapper for arguments like channel or axis. Parameters ---------- lis : list List to parse. argument : int or object Argument. Returns ------- int Index of chosen object. """ # get channel if isinstance(argument, int): if -len(lis) <= argument < len(lis): return argument else: raise IndexError("index {0} incompatible with length {1}".format(argument, len(lis))) else: return lis.index(argument)
[ "def", "get_index", "(", "lis", ",", "argument", ")", ":", "# get channel", "if", "isinstance", "(", "argument", ",", "int", ")", ":", "if", "-", "len", "(", "lis", ")", "<=", "argument", "<", "len", "(", "lis", ")", ":", "return", "argument", "else"...
Find the index of an item, given either the item or index as an argument. Particularly useful as a wrapper for arguments like channel or axis. Parameters ---------- lis : list List to parse. argument : int or object Argument. Returns ------- int Index of chosen object.
[ "Find", "the", "index", "of", "an", "item", "given", "either", "the", "item", "or", "index", "as", "an", "argument", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/kit/_list.py#L75-L99
train
33,673
wright-group/WrightTools
WrightTools/artists/_helpers.py
_title
def _title(fig, title, subtitle="", *, margin=1, fontsize=20, subfontsize=18): """Add a title to a figure. Parameters ---------- fig : matplotlib Figure Figure. title : string Title. subtitle : string Subtitle. margin : number (optional) Distance from top of plot, in inches. Default is 1. fontsize : number (optional) Title fontsize. Default is 20. subfontsize : number (optional) Subtitle fontsize. Default is 18. """ fig.suptitle(title, fontsize=fontsize) height = fig.get_figheight() # inches distance = margin / 2. # distance from top of plot, in inches ratio = 1 - distance / height fig.text(0.5, ratio, subtitle, fontsize=subfontsize, ha="center", va="top")
python
def _title(fig, title, subtitle="", *, margin=1, fontsize=20, subfontsize=18): """Add a title to a figure. Parameters ---------- fig : matplotlib Figure Figure. title : string Title. subtitle : string Subtitle. margin : number (optional) Distance from top of plot, in inches. Default is 1. fontsize : number (optional) Title fontsize. Default is 20. subfontsize : number (optional) Subtitle fontsize. Default is 18. """ fig.suptitle(title, fontsize=fontsize) height = fig.get_figheight() # inches distance = margin / 2. # distance from top of plot, in inches ratio = 1 - distance / height fig.text(0.5, ratio, subtitle, fontsize=subfontsize, ha="center", va="top")
[ "def", "_title", "(", "fig", ",", "title", ",", "subtitle", "=", "\"\"", ",", "*", ",", "margin", "=", "1", ",", "fontsize", "=", "20", ",", "subfontsize", "=", "18", ")", ":", "fig", ".", "suptitle", "(", "title", ",", "fontsize", "=", "fontsize",...
Add a title to a figure. Parameters ---------- fig : matplotlib Figure Figure. title : string Title. subtitle : string Subtitle. margin : number (optional) Distance from top of plot, in inches. Default is 1. fontsize : number (optional) Title fontsize. Default is 20. subfontsize : number (optional) Subtitle fontsize. Default is 18.
[ "Add", "a", "title", "to", "a", "figure", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L53-L75
train
33,674
wright-group/WrightTools
WrightTools/artists/_helpers.py
add_sideplot
def add_sideplot( ax, along, pad=0., *, grid=True, zero_line=True, arrs_to_bin=None, normalize_bin=True, ymin=0, ymax=1.1, height=0.75, c="C0" ): """Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib AxesSubplot object The axis to add a sideplot along. along : {'x', 'y'} The dimension to add a sideplot along. pad : number (optional) Distance between axis and sideplot. Default is 0. grid : bool (optional) Toggle for plotting grid on sideplot. Default is True. zero_line : bool (optional) Toggle for plotting black line at zero signal. Default is True. arrs_to_bin : list [xi, yi, zi] (optional) Bins are plotted if arrays are supplied. Default is None. normalize_bin : bool (optional) Normalize bin by max value. Default is True. ymin : number (optional) Bin minimum extent. Default is 0. ymax : number (optional) Bin maximum extent. Default is 1.1 c : string (optional) Line color. Default is C0. Returns ------- axCorr AxesSubplot object """ # divider should only be created once if hasattr(ax, "WrightTools_sideplot_divider"): divider = ax.WrightTools_sideplot_divider else: divider = make_axes_locatable(ax) setattr(ax, "WrightTools_sideplot_divider", divider) # create sideplot axis if along == "x": axCorr = divider.append_axes("top", height, pad=pad, sharex=ax) elif along == "y": axCorr = divider.append_axes("right", height, pad=pad, sharey=ax) axCorr.autoscale(False) axCorr.set_adjustable("box") # bin if arrs_to_bin is not None: xi, yi, zi = arrs_to_bin if along == "x": b = np.nansum(zi, axis=0) * len(yi) if normalize_bin: b /= np.nanmax(b) axCorr.plot(xi, b, c=c, lw=2) elif along == "y": b = np.nansum(zi, axis=1) * len(xi) if normalize_bin: b /= np.nanmax(b) axCorr.plot(b, yi, c=c, lw=2) # beautify if along == "x": axCorr.set_ylim(ymin, ymax) axCorr.tick_params(axis="x", which="both", length=0) elif along == "y": axCorr.set_xlim(ymin, ymax) axCorr.tick_params(axis="y", which="both", length=0) plt.grid(grid) if zero_line: if along == "x": plt.axhline(0, c="k", lw=1) elif along == "y": plt.axvline(0, c="k", lw=1) plt.setp(axCorr.get_xticklabels(), visible=False) plt.setp(axCorr.get_yticklabels(), visible=False) return axCorr
python
def add_sideplot( ax, along, pad=0., *, grid=True, zero_line=True, arrs_to_bin=None, normalize_bin=True, ymin=0, ymax=1.1, height=0.75, c="C0" ): """Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib AxesSubplot object The axis to add a sideplot along. along : {'x', 'y'} The dimension to add a sideplot along. pad : number (optional) Distance between axis and sideplot. Default is 0. grid : bool (optional) Toggle for plotting grid on sideplot. Default is True. zero_line : bool (optional) Toggle for plotting black line at zero signal. Default is True. arrs_to_bin : list [xi, yi, zi] (optional) Bins are plotted if arrays are supplied. Default is None. normalize_bin : bool (optional) Normalize bin by max value. Default is True. ymin : number (optional) Bin minimum extent. Default is 0. ymax : number (optional) Bin maximum extent. Default is 1.1 c : string (optional) Line color. Default is C0. Returns ------- axCorr AxesSubplot object """ # divider should only be created once if hasattr(ax, "WrightTools_sideplot_divider"): divider = ax.WrightTools_sideplot_divider else: divider = make_axes_locatable(ax) setattr(ax, "WrightTools_sideplot_divider", divider) # create sideplot axis if along == "x": axCorr = divider.append_axes("top", height, pad=pad, sharex=ax) elif along == "y": axCorr = divider.append_axes("right", height, pad=pad, sharey=ax) axCorr.autoscale(False) axCorr.set_adjustable("box") # bin if arrs_to_bin is not None: xi, yi, zi = arrs_to_bin if along == "x": b = np.nansum(zi, axis=0) * len(yi) if normalize_bin: b /= np.nanmax(b) axCorr.plot(xi, b, c=c, lw=2) elif along == "y": b = np.nansum(zi, axis=1) * len(xi) if normalize_bin: b /= np.nanmax(b) axCorr.plot(b, yi, c=c, lw=2) # beautify if along == "x": axCorr.set_ylim(ymin, ymax) axCorr.tick_params(axis="x", which="both", length=0) elif along == "y": axCorr.set_xlim(ymin, ymax) axCorr.tick_params(axis="y", which="both", length=0) plt.grid(grid) if zero_line: if along == "x": plt.axhline(0, c="k", lw=1) elif along == "y": plt.axvline(0, c="k", lw=1) plt.setp(axCorr.get_xticklabels(), visible=False) plt.setp(axCorr.get_yticklabels(), visible=False) return axCorr
[ "def", "add_sideplot", "(", "ax", ",", "along", ",", "pad", "=", "0.", ",", "*", ",", "grid", "=", "True", ",", "zero_line", "=", "True", ",", "arrs_to_bin", "=", "None", ",", "normalize_bin", "=", "True", ",", "ymin", "=", "0", ",", "ymax", "=", ...
Add a sideplot to an axis. Sideplots share their corresponding axis. Parameters ---------- ax : matplotlib AxesSubplot object The axis to add a sideplot along. along : {'x', 'y'} The dimension to add a sideplot along. pad : number (optional) Distance between axis and sideplot. Default is 0. grid : bool (optional) Toggle for plotting grid on sideplot. Default is True. zero_line : bool (optional) Toggle for plotting black line at zero signal. Default is True. arrs_to_bin : list [xi, yi, zi] (optional) Bins are plotted if arrays are supplied. Default is None. normalize_bin : bool (optional) Normalize bin by max value. Default is True. ymin : number (optional) Bin minimum extent. Default is 0. ymax : number (optional) Bin maximum extent. Default is 1.1 c : string (optional) Line color. Default is C0. Returns ------- axCorr AxesSubplot object
[ "Add", "a", "sideplot", "to", "an", "axis", ".", "Sideplots", "share", "their", "corresponding", "axis", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L78-L163
train
33,675
wright-group/WrightTools
WrightTools/artists/_helpers.py
corner_text
def corner_text( text, distance=0.075, *, ax=None, corner="UL", factor=200, bbox=True, fontsize=18, background_alpha=1, edgecolor=None ): """Place some text in the corner of the figure. Parameters ---------- text : str The text to use. distance : number (optional) Distance from the corner. Default is 0.05. ax : axis (optional) The axis object to label. If None, uses current axis. Default is None. corner : {'UL', 'LL', 'UR', 'LR'} (optional) The corner to label. Upper left, Lower left etc. Default is UL. factor : number (optional) Scaling factor. Default is 200. bbox : boolean (optional) Toggle bounding box. Default is True. fontsize : number (optional) Text fontsize. If None, uses the matplotlib default. Default is 18. background_alpha : number (optional) Opacity of background bounding box. Default is 1. edgecolor : string (optional) Frame edgecolor. Default is None (inherits from legend.edgecolor rcparam). Returns ------- text The matplotlib text object. """ # get axis if ax is None: ax = plt.gca() [h_scaled, v_scaled], [va, ha] = get_scaled_bounds( ax, corner, distance=distance, factor=factor ) # get edgecolor if edgecolor is None: edgecolor = matplotlib.rcParams["legend.edgecolor"] # apply text props = dict(boxstyle="square", facecolor="white", alpha=background_alpha, edgecolor=edgecolor) args = [v_scaled, h_scaled, text] kwargs = {} kwargs["fontsize"] = fontsize kwargs["verticalalignment"] = va kwargs["horizontalalignment"] = ha if bbox: kwargs["bbox"] = props else: kwargs["path_effects"] = [PathEffects.withStroke(linewidth=3, foreground="w")] kwargs["transform"] = ax.transAxes if "zlabel" in ax.properties().keys(): # axis is 3D projection out = ax.text2D(*args, **kwargs) else: out = ax.text(*args, **kwargs) return out
python
def corner_text( text, distance=0.075, *, ax=None, corner="UL", factor=200, bbox=True, fontsize=18, background_alpha=1, edgecolor=None ): """Place some text in the corner of the figure. Parameters ---------- text : str The text to use. distance : number (optional) Distance from the corner. Default is 0.05. ax : axis (optional) The axis object to label. If None, uses current axis. Default is None. corner : {'UL', 'LL', 'UR', 'LR'} (optional) The corner to label. Upper left, Lower left etc. Default is UL. factor : number (optional) Scaling factor. Default is 200. bbox : boolean (optional) Toggle bounding box. Default is True. fontsize : number (optional) Text fontsize. If None, uses the matplotlib default. Default is 18. background_alpha : number (optional) Opacity of background bounding box. Default is 1. edgecolor : string (optional) Frame edgecolor. Default is None (inherits from legend.edgecolor rcparam). Returns ------- text The matplotlib text object. """ # get axis if ax is None: ax = plt.gca() [h_scaled, v_scaled], [va, ha] = get_scaled_bounds( ax, corner, distance=distance, factor=factor ) # get edgecolor if edgecolor is None: edgecolor = matplotlib.rcParams["legend.edgecolor"] # apply text props = dict(boxstyle="square", facecolor="white", alpha=background_alpha, edgecolor=edgecolor) args = [v_scaled, h_scaled, text] kwargs = {} kwargs["fontsize"] = fontsize kwargs["verticalalignment"] = va kwargs["horizontalalignment"] = ha if bbox: kwargs["bbox"] = props else: kwargs["path_effects"] = [PathEffects.withStroke(linewidth=3, foreground="w")] kwargs["transform"] = ax.transAxes if "zlabel" in ax.properties().keys(): # axis is 3D projection out = ax.text2D(*args, **kwargs) else: out = ax.text(*args, **kwargs) return out
[ "def", "corner_text", "(", "text", ",", "distance", "=", "0.075", ",", "*", ",", "ax", "=", "None", ",", "corner", "=", "\"UL\"", ",", "factor", "=", "200", ",", "bbox", "=", "True", ",", "fontsize", "=", "18", ",", "background_alpha", "=", "1", ",...
Place some text in the corner of the figure. Parameters ---------- text : str The text to use. distance : number (optional) Distance from the corner. Default is 0.05. ax : axis (optional) The axis object to label. If None, uses current axis. Default is None. corner : {'UL', 'LL', 'UR', 'LR'} (optional) The corner to label. Upper left, Lower left etc. Default is UL. factor : number (optional) Scaling factor. Default is 200. bbox : boolean (optional) Toggle bounding box. Default is True. fontsize : number (optional) Text fontsize. If None, uses the matplotlib default. Default is 18. background_alpha : number (optional) Opacity of background bounding box. Default is 1. edgecolor : string (optional) Frame edgecolor. Default is None (inherits from legend.edgecolor rcparam). Returns ------- text The matplotlib text object.
[ "Place", "some", "text", "in", "the", "corner", "of", "the", "figure", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L166-L232
train
33,676
wright-group/WrightTools
WrightTools/artists/_helpers.py
create_figure
def create_figure( *, width="single", nrows=1, cols=[1], margin=1., hspace=0.25, wspace=0.25, cbar_width=0.25, aspects=[], default_aspect=1 ): """Re-parameterization of matplotlib figure creation tools, exposing convenient variables. Figures are defined primarily by their width. Height is defined by the aspect ratios of the subplots contained within. hspace, wspace, and cbar_width are defined in inches, making it easier to make consistent plots. Margins are enforced to be equal around the entire plot, starting from the edges of the subplots. Parameters ---------- width : {'single', 'double', 'dissertation'} or float (optional) The total width of the generated figure. Can be given in inches directly, or can be specified using keys. Default is 'single' (6.5 inches). nrows : int (optional) The number of subplot rows in the figure. Default is 1. cols : list (optional) A list of numbers, defining the number and width-ratios of the figure columns. May also contain the special string 'cbar', defining a column as a colorbar-containing column. Default is [1]. margin : float (optional) Margin in inches. Margin is applied evenly around the figure, starting from the subplot boundaries (so that ticks and labels appear in the margin). Default is 1. hspace : float (optional) The 'height space' (space seperating two subplots vertically), in inches. Default is 0.25. wspace : float (optional) The 'width space' (space seperating two subplots horizontally), in inches. Default is 0.25. cbar_width : float (optional) The width of the colorbar in inches. Default is 0.25. aspects : list of lists (optional) Define the aspect ratio of individual subplots. List of lists, each sub-ist having the format [[row, col], aspect]. The figure will expand vertically to acomidate the defined aspect ratio. Aspects are V/H so aspects larger than 1 will be taller than wide and vice-versa for aspects smaller than 1. You may only define the aspect for one subplot in each row. If no aspect is defined for a particular row, the leftmost subplot will have an aspect of ``default_aspect``. Default is given by default_aspect kwarg. default_aspect : number (optional) Default aspect of left-most column, if no aspect is defined for a given row. Returns ------- tuple (WrightTools.artists.Figure, WrightTools.artists.GridSpec). GridSpec contains SubplotSpec objects that can have axes placed into them. The SubplotSpec objects can be accessed through indexing: [row, col]. Slicing works, for example ``cax = plt.subplot(gs[:, -1])``. See matplotlib gridspec__ documentation for more information. __ http://matplotlib.org/users/gridspec.html#gridspec-and-subplotspec Notes ----- To ensure the margins work as expected, save the fig with the same margins (``pad_inches``) as specified in this function. Common savefig call: ``plt.savefig(plt.savefig(output_path, dpi=300, transparent=True, pad_inches=1))`` See Also -------- wt.artists.plot_margins Plot lines to visualize the figure edges, margins, and centers. For debug and design purposes. wt.artists.subplots_adjust Enforce margins for figure generated elsewhere. """ # get width if width == "double": figure_width = 14. elif width == "single": figure_width = 6.5 elif width == "dissertation": figure_width = 13. else: figure_width = float(width) # check if aspect constraints are valid rows_in_aspects = [item[0][0] for item in aspects] if not len(rows_in_aspects) == len(set(rows_in_aspects)): raise Exception("can only specify aspect for one plot in each row") # get width avalible to subplots (not including colorbars) total_subplot_width = figure_width - 2 * margin total_subplot_width -= (len(cols) - 1) * wspace # whitespace in width total_subplot_width -= cols.count("cbar") * cbar_width # colorbar width # converters def in_to_mpl(inches, total, n): return (inches * n) / (total - inches * n + inches) def mpl_to_in(mpl, total, n): return (total / (n + mpl * (n - 1))) * mpl # calculate column widths, width_ratio subplot_ratios = np.array([i for i in cols if not i == "cbar"], dtype=np.float) subplot_ratios /= sum(subplot_ratios) subplot_widths = total_subplot_width * subplot_ratios width_ratios = [] cols_idxs = [] i = 0 for col in cols: if not col == "cbar": width_ratios.append(subplot_widths[i]) cols_idxs.append(i) i += 1 else: width_ratios.append(cbar_width) cols_idxs.append(np.nan) # calculate figure height, height_ratios, figure height subplot_heights = [] for row_index in range(nrows): if row_index in rows_in_aspects: aspect = aspects[rows_in_aspects.index(row_index)][1] col_index = aspects[rows_in_aspects.index(row_index)][0][1] height = subplot_widths[col_index] * aspect subplot_heights.append(height) else: # make the leftmost (zero indexed) plot square as default subplot_heights.append(subplot_widths[0] * default_aspect) height_ratios = subplot_heights figure_height = sum(subplot_heights) figure_height += (nrows - 1) * hspace figure_height += 2 * margin # make figure fig = plt.figure(figsize=[figure_width, figure_height], FigureClass=Figure) # get hspace, wspace in relative units hspace = in_to_mpl(hspace, figure_height - 2 * margin, nrows) wspace = in_to_mpl(wspace, figure_width - 2 * margin, len(cols)) # make gridpsec gs = GridSpec( nrows, len(cols), hspace=hspace, wspace=wspace, width_ratios=width_ratios, height_ratios=height_ratios, ) # finish subplots_adjust(fig, inches=margin) return fig, gs
python
def create_figure( *, width="single", nrows=1, cols=[1], margin=1., hspace=0.25, wspace=0.25, cbar_width=0.25, aspects=[], default_aspect=1 ): """Re-parameterization of matplotlib figure creation tools, exposing convenient variables. Figures are defined primarily by their width. Height is defined by the aspect ratios of the subplots contained within. hspace, wspace, and cbar_width are defined in inches, making it easier to make consistent plots. Margins are enforced to be equal around the entire plot, starting from the edges of the subplots. Parameters ---------- width : {'single', 'double', 'dissertation'} or float (optional) The total width of the generated figure. Can be given in inches directly, or can be specified using keys. Default is 'single' (6.5 inches). nrows : int (optional) The number of subplot rows in the figure. Default is 1. cols : list (optional) A list of numbers, defining the number and width-ratios of the figure columns. May also contain the special string 'cbar', defining a column as a colorbar-containing column. Default is [1]. margin : float (optional) Margin in inches. Margin is applied evenly around the figure, starting from the subplot boundaries (so that ticks and labels appear in the margin). Default is 1. hspace : float (optional) The 'height space' (space seperating two subplots vertically), in inches. Default is 0.25. wspace : float (optional) The 'width space' (space seperating two subplots horizontally), in inches. Default is 0.25. cbar_width : float (optional) The width of the colorbar in inches. Default is 0.25. aspects : list of lists (optional) Define the aspect ratio of individual subplots. List of lists, each sub-ist having the format [[row, col], aspect]. The figure will expand vertically to acomidate the defined aspect ratio. Aspects are V/H so aspects larger than 1 will be taller than wide and vice-versa for aspects smaller than 1. You may only define the aspect for one subplot in each row. If no aspect is defined for a particular row, the leftmost subplot will have an aspect of ``default_aspect``. Default is given by default_aspect kwarg. default_aspect : number (optional) Default aspect of left-most column, if no aspect is defined for a given row. Returns ------- tuple (WrightTools.artists.Figure, WrightTools.artists.GridSpec). GridSpec contains SubplotSpec objects that can have axes placed into them. The SubplotSpec objects can be accessed through indexing: [row, col]. Slicing works, for example ``cax = plt.subplot(gs[:, -1])``. See matplotlib gridspec__ documentation for more information. __ http://matplotlib.org/users/gridspec.html#gridspec-and-subplotspec Notes ----- To ensure the margins work as expected, save the fig with the same margins (``pad_inches``) as specified in this function. Common savefig call: ``plt.savefig(plt.savefig(output_path, dpi=300, transparent=True, pad_inches=1))`` See Also -------- wt.artists.plot_margins Plot lines to visualize the figure edges, margins, and centers. For debug and design purposes. wt.artists.subplots_adjust Enforce margins for figure generated elsewhere. """ # get width if width == "double": figure_width = 14. elif width == "single": figure_width = 6.5 elif width == "dissertation": figure_width = 13. else: figure_width = float(width) # check if aspect constraints are valid rows_in_aspects = [item[0][0] for item in aspects] if not len(rows_in_aspects) == len(set(rows_in_aspects)): raise Exception("can only specify aspect for one plot in each row") # get width avalible to subplots (not including colorbars) total_subplot_width = figure_width - 2 * margin total_subplot_width -= (len(cols) - 1) * wspace # whitespace in width total_subplot_width -= cols.count("cbar") * cbar_width # colorbar width # converters def in_to_mpl(inches, total, n): return (inches * n) / (total - inches * n + inches) def mpl_to_in(mpl, total, n): return (total / (n + mpl * (n - 1))) * mpl # calculate column widths, width_ratio subplot_ratios = np.array([i for i in cols if not i == "cbar"], dtype=np.float) subplot_ratios /= sum(subplot_ratios) subplot_widths = total_subplot_width * subplot_ratios width_ratios = [] cols_idxs = [] i = 0 for col in cols: if not col == "cbar": width_ratios.append(subplot_widths[i]) cols_idxs.append(i) i += 1 else: width_ratios.append(cbar_width) cols_idxs.append(np.nan) # calculate figure height, height_ratios, figure height subplot_heights = [] for row_index in range(nrows): if row_index in rows_in_aspects: aspect = aspects[rows_in_aspects.index(row_index)][1] col_index = aspects[rows_in_aspects.index(row_index)][0][1] height = subplot_widths[col_index] * aspect subplot_heights.append(height) else: # make the leftmost (zero indexed) plot square as default subplot_heights.append(subplot_widths[0] * default_aspect) height_ratios = subplot_heights figure_height = sum(subplot_heights) figure_height += (nrows - 1) * hspace figure_height += 2 * margin # make figure fig = plt.figure(figsize=[figure_width, figure_height], FigureClass=Figure) # get hspace, wspace in relative units hspace = in_to_mpl(hspace, figure_height - 2 * margin, nrows) wspace = in_to_mpl(wspace, figure_width - 2 * margin, len(cols)) # make gridpsec gs = GridSpec( nrows, len(cols), hspace=hspace, wspace=wspace, width_ratios=width_ratios, height_ratios=height_ratios, ) # finish subplots_adjust(fig, inches=margin) return fig, gs
[ "def", "create_figure", "(", "*", ",", "width", "=", "\"single\"", ",", "nrows", "=", "1", ",", "cols", "=", "[", "1", "]", ",", "margin", "=", "1.", ",", "hspace", "=", "0.25", ",", "wspace", "=", "0.25", ",", "cbar_width", "=", "0.25", ",", "as...
Re-parameterization of matplotlib figure creation tools, exposing convenient variables. Figures are defined primarily by their width. Height is defined by the aspect ratios of the subplots contained within. hspace, wspace, and cbar_width are defined in inches, making it easier to make consistent plots. Margins are enforced to be equal around the entire plot, starting from the edges of the subplots. Parameters ---------- width : {'single', 'double', 'dissertation'} or float (optional) The total width of the generated figure. Can be given in inches directly, or can be specified using keys. Default is 'single' (6.5 inches). nrows : int (optional) The number of subplot rows in the figure. Default is 1. cols : list (optional) A list of numbers, defining the number and width-ratios of the figure columns. May also contain the special string 'cbar', defining a column as a colorbar-containing column. Default is [1]. margin : float (optional) Margin in inches. Margin is applied evenly around the figure, starting from the subplot boundaries (so that ticks and labels appear in the margin). Default is 1. hspace : float (optional) The 'height space' (space seperating two subplots vertically), in inches. Default is 0.25. wspace : float (optional) The 'width space' (space seperating two subplots horizontally), in inches. Default is 0.25. cbar_width : float (optional) The width of the colorbar in inches. Default is 0.25. aspects : list of lists (optional) Define the aspect ratio of individual subplots. List of lists, each sub-ist having the format [[row, col], aspect]. The figure will expand vertically to acomidate the defined aspect ratio. Aspects are V/H so aspects larger than 1 will be taller than wide and vice-versa for aspects smaller than 1. You may only define the aspect for one subplot in each row. If no aspect is defined for a particular row, the leftmost subplot will have an aspect of ``default_aspect``. Default is given by default_aspect kwarg. default_aspect : number (optional) Default aspect of left-most column, if no aspect is defined for a given row. Returns ------- tuple (WrightTools.artists.Figure, WrightTools.artists.GridSpec). GridSpec contains SubplotSpec objects that can have axes placed into them. The SubplotSpec objects can be accessed through indexing: [row, col]. Slicing works, for example ``cax = plt.subplot(gs[:, -1])``. See matplotlib gridspec__ documentation for more information. __ http://matplotlib.org/users/gridspec.html#gridspec-and-subplotspec Notes ----- To ensure the margins work as expected, save the fig with the same margins (``pad_inches``) as specified in this function. Common savefig call: ``plt.savefig(plt.savefig(output_path, dpi=300, transparent=True, pad_inches=1))`` See Also -------- wt.artists.plot_margins Plot lines to visualize the figure edges, margins, and centers. For debug and design purposes. wt.artists.subplots_adjust Enforce margins for figure generated elsewhere.
[ "Re", "-", "parameterization", "of", "matplotlib", "figure", "creation", "tools", "exposing", "convenient", "variables", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L235-L392
train
33,677
wright-group/WrightTools
WrightTools/artists/_helpers.py
diagonal_line
def diagonal_line(xi=None, yi=None, *, ax=None, c=None, ls=None, lw=None, zorder=3): """Plot a diagonal line. Parameters ---------- xi : 1D array-like (optional) The x axis points. If None, taken from axis limits. Default is None. yi : 1D array-like The y axis points. If None, taken from axis limits. Default is None. ax : axis (optional) Axis to plot on. If none is supplied, the current axis is used. c : string (optional) Line color. Default derives from rcParams grid color. ls : string (optional) Line style. Default derives from rcParams linestyle. lw : float (optional) Line width. Default derives from rcParams linewidth. zorder : number (optional) Matplotlib zorder. Default is 3. Returns ------- matplotlib.lines.Line2D object The plotted line. """ if ax is None: ax = plt.gca() # parse xi, yi if xi is None: xi = ax.get_xlim() if yi is None: yi = ax.get_ylim() # parse style if c is None: c = matplotlib.rcParams["grid.color"] if ls is None: ls = matplotlib.rcParams["grid.linestyle"] if lw is None: lw = matplotlib.rcParams["grid.linewidth"] # get axis if ax is None: ax = plt.gca() # make plot diag_min = max(min(xi), min(yi)) diag_max = min(max(xi), max(yi)) line = ax.plot([diag_min, diag_max], [diag_min, diag_max], c=c, ls=ls, lw=lw, zorder=zorder) return line
python
def diagonal_line(xi=None, yi=None, *, ax=None, c=None, ls=None, lw=None, zorder=3): """Plot a diagonal line. Parameters ---------- xi : 1D array-like (optional) The x axis points. If None, taken from axis limits. Default is None. yi : 1D array-like The y axis points. If None, taken from axis limits. Default is None. ax : axis (optional) Axis to plot on. If none is supplied, the current axis is used. c : string (optional) Line color. Default derives from rcParams grid color. ls : string (optional) Line style. Default derives from rcParams linestyle. lw : float (optional) Line width. Default derives from rcParams linewidth. zorder : number (optional) Matplotlib zorder. Default is 3. Returns ------- matplotlib.lines.Line2D object The plotted line. """ if ax is None: ax = plt.gca() # parse xi, yi if xi is None: xi = ax.get_xlim() if yi is None: yi = ax.get_ylim() # parse style if c is None: c = matplotlib.rcParams["grid.color"] if ls is None: ls = matplotlib.rcParams["grid.linestyle"] if lw is None: lw = matplotlib.rcParams["grid.linewidth"] # get axis if ax is None: ax = plt.gca() # make plot diag_min = max(min(xi), min(yi)) diag_max = min(max(xi), max(yi)) line = ax.plot([diag_min, diag_max], [diag_min, diag_max], c=c, ls=ls, lw=lw, zorder=zorder) return line
[ "def", "diagonal_line", "(", "xi", "=", "None", ",", "yi", "=", "None", ",", "*", ",", "ax", "=", "None", ",", "c", "=", "None", ",", "ls", "=", "None", ",", "lw", "=", "None", ",", "zorder", "=", "3", ")", ":", "if", "ax", "is", "None", ":...
Plot a diagonal line. Parameters ---------- xi : 1D array-like (optional) The x axis points. If None, taken from axis limits. Default is None. yi : 1D array-like The y axis points. If None, taken from axis limits. Default is None. ax : axis (optional) Axis to plot on. If none is supplied, the current axis is used. c : string (optional) Line color. Default derives from rcParams grid color. ls : string (optional) Line style. Default derives from rcParams linestyle. lw : float (optional) Line width. Default derives from rcParams linewidth. zorder : number (optional) Matplotlib zorder. Default is 3. Returns ------- matplotlib.lines.Line2D object The plotted line.
[ "Plot", "a", "diagonal", "line", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L395-L441
train
33,678
wright-group/WrightTools
WrightTools/artists/_helpers.py
get_scaled_bounds
def get_scaled_bounds(ax, position, *, distance=0.1, factor=200): """Get scaled bounds. Parameters ---------- ax : Axes object Axes object. position : {'UL', 'LL', 'UR', 'LR'} Position. distance : number (optional) Distance. Default is 0.1. factor : number (optional) Factor. Default is 200. Returns ------- ([h_scaled, v_scaled], [va, ha]) """ # get bounds x0, y0, width, height = ax.bbox.bounds width_scaled = width / factor height_scaled = height / factor # get scaled postions if position == "UL": v_scaled = distance / width_scaled h_scaled = 1 - (distance / height_scaled) va = "top" ha = "left" elif position == "LL": v_scaled = distance / width_scaled h_scaled = distance / height_scaled va = "bottom" ha = "left" elif position == "UR": v_scaled = 1 - (distance / width_scaled) h_scaled = 1 - (distance / height_scaled) va = "top" ha = "right" elif position == "LR": v_scaled = 1 - (distance / width_scaled) h_scaled = distance / height_scaled va = "bottom" ha = "right" else: print("corner not recognized") v_scaled = h_scaled = 1. va = "center" ha = "center" return [h_scaled, v_scaled], [va, ha]
python
def get_scaled_bounds(ax, position, *, distance=0.1, factor=200): """Get scaled bounds. Parameters ---------- ax : Axes object Axes object. position : {'UL', 'LL', 'UR', 'LR'} Position. distance : number (optional) Distance. Default is 0.1. factor : number (optional) Factor. Default is 200. Returns ------- ([h_scaled, v_scaled], [va, ha]) """ # get bounds x0, y0, width, height = ax.bbox.bounds width_scaled = width / factor height_scaled = height / factor # get scaled postions if position == "UL": v_scaled = distance / width_scaled h_scaled = 1 - (distance / height_scaled) va = "top" ha = "left" elif position == "LL": v_scaled = distance / width_scaled h_scaled = distance / height_scaled va = "bottom" ha = "left" elif position == "UR": v_scaled = 1 - (distance / width_scaled) h_scaled = 1 - (distance / height_scaled) va = "top" ha = "right" elif position == "LR": v_scaled = 1 - (distance / width_scaled) h_scaled = distance / height_scaled va = "bottom" ha = "right" else: print("corner not recognized") v_scaled = h_scaled = 1. va = "center" ha = "center" return [h_scaled, v_scaled], [va, ha]
[ "def", "get_scaled_bounds", "(", "ax", ",", "position", ",", "*", ",", "distance", "=", "0.1", ",", "factor", "=", "200", ")", ":", "# get bounds", "x0", ",", "y0", ",", "width", ",", "height", "=", "ax", ".", "bbox", ".", "bounds", "width_scaled", "...
Get scaled bounds. Parameters ---------- ax : Axes object Axes object. position : {'UL', 'LL', 'UR', 'LR'} Position. distance : number (optional) Distance. Default is 0.1. factor : number (optional) Factor. Default is 200. Returns ------- ([h_scaled, v_scaled], [va, ha])
[ "Get", "scaled", "bounds", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L444-L492
train
33,679
wright-group/WrightTools
WrightTools/artists/_helpers.py
pcolor_helper
def pcolor_helper(xi, yi, zi=None): """Prepare a set of arrays for plotting using `pcolor`. The return values are suitable for feeding directly into ``matplotlib.pcolor`` such that the pixels are properly centered. Parameters ---------- xi : 1D or 2D array-like Array of X-coordinates. yi : 1D or 2D array-like Array of Y-coordinates. zi : 2D array (optional, deprecated) If zi is not None, it is returned unchanged in the output. Returns ------- X : 2D ndarray X dimension for pcolor Y : 2D ndarray Y dimension for pcolor zi : 2D ndarray if zi parameter is not None, returns zi parameter unchanged """ xi = xi.copy() yi = yi.copy() if xi.ndim == 1: xi.shape = (xi.size, 1) if yi.ndim == 1: yi.shape = (1, yi.size) shape = wt_kit.joint_shape(xi, yi) # full def full(arr): for i in range(arr.ndim): if arr.shape[i] == 1: arr = np.repeat(arr, shape[i], axis=i) return arr xi = full(xi) yi = full(yi) # pad x = np.arange(shape[1]) y = np.arange(shape[0]) f_xi = interp2d(x, y, xi) f_yi = interp2d(x, y, yi) x_new = np.arange(-1, shape[1] + 1) y_new = np.arange(-1, shape[0] + 1) xi = f_xi(x_new, y_new) yi = f_yi(x_new, y_new) # fill X = np.empty([s - 1 for s in xi.shape]) Y = np.empty([s - 1 for s in yi.shape]) for orig, out in [[xi, X], [yi, Y]]: for idx in np.ndindex(out.shape): ul = orig[idx[0] + 1, idx[1] + 0] ur = orig[idx[0] + 1, idx[1] + 1] ll = orig[idx[0] + 0, idx[1] + 0] lr = orig[idx[0] + 0, idx[1] + 1] out[idx] = np.mean([ul, ur, ll, lr]) if zi is not None: warnings.warn( "zi argument is not used in pcolor_helper and is not required", wt_exceptions.VisibleDeprecationWarning, ) return X, Y, zi.copy() else: return X, Y
python
def pcolor_helper(xi, yi, zi=None): """Prepare a set of arrays for plotting using `pcolor`. The return values are suitable for feeding directly into ``matplotlib.pcolor`` such that the pixels are properly centered. Parameters ---------- xi : 1D or 2D array-like Array of X-coordinates. yi : 1D or 2D array-like Array of Y-coordinates. zi : 2D array (optional, deprecated) If zi is not None, it is returned unchanged in the output. Returns ------- X : 2D ndarray X dimension for pcolor Y : 2D ndarray Y dimension for pcolor zi : 2D ndarray if zi parameter is not None, returns zi parameter unchanged """ xi = xi.copy() yi = yi.copy() if xi.ndim == 1: xi.shape = (xi.size, 1) if yi.ndim == 1: yi.shape = (1, yi.size) shape = wt_kit.joint_shape(xi, yi) # full def full(arr): for i in range(arr.ndim): if arr.shape[i] == 1: arr = np.repeat(arr, shape[i], axis=i) return arr xi = full(xi) yi = full(yi) # pad x = np.arange(shape[1]) y = np.arange(shape[0]) f_xi = interp2d(x, y, xi) f_yi = interp2d(x, y, yi) x_new = np.arange(-1, shape[1] + 1) y_new = np.arange(-1, shape[0] + 1) xi = f_xi(x_new, y_new) yi = f_yi(x_new, y_new) # fill X = np.empty([s - 1 for s in xi.shape]) Y = np.empty([s - 1 for s in yi.shape]) for orig, out in [[xi, X], [yi, Y]]: for idx in np.ndindex(out.shape): ul = orig[idx[0] + 1, idx[1] + 0] ur = orig[idx[0] + 1, idx[1] + 1] ll = orig[idx[0] + 0, idx[1] + 0] lr = orig[idx[0] + 0, idx[1] + 1] out[idx] = np.mean([ul, ur, ll, lr]) if zi is not None: warnings.warn( "zi argument is not used in pcolor_helper and is not required", wt_exceptions.VisibleDeprecationWarning, ) return X, Y, zi.copy() else: return X, Y
[ "def", "pcolor_helper", "(", "xi", ",", "yi", ",", "zi", "=", "None", ")", ":", "xi", "=", "xi", ".", "copy", "(", ")", "yi", "=", "yi", ".", "copy", "(", ")", "if", "xi", ".", "ndim", "==", "1", ":", "xi", ".", "shape", "=", "(", "xi", "...
Prepare a set of arrays for plotting using `pcolor`. The return values are suitable for feeding directly into ``matplotlib.pcolor`` such that the pixels are properly centered. Parameters ---------- xi : 1D or 2D array-like Array of X-coordinates. yi : 1D or 2D array-like Array of Y-coordinates. zi : 2D array (optional, deprecated) If zi is not None, it is returned unchanged in the output. Returns ------- X : 2D ndarray X dimension for pcolor Y : 2D ndarray Y dimension for pcolor zi : 2D ndarray if zi parameter is not None, returns zi parameter unchanged
[ "Prepare", "a", "set", "of", "arrays", "for", "plotting", "using", "pcolor", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L495-L562
train
33,680
wright-group/WrightTools
WrightTools/artists/_helpers.py
plot_colorbar
def plot_colorbar( cax=None, cmap="default", ticks=None, clim=None, vlim=None, label=None, tick_fontsize=14, label_fontsize=18, decimals=None, orientation="vertical", ticklocation="auto", extend="neither", extendfrac=None, extendrect=False, ): """Easily add a colormap to an axis. Parameters ---------- cax : matplotlib axis (optional) The axis to plot the colorbar on. Finds the current axis if none is given. cmap : string or LinearSegmentedColormap (optional) The colormap to fill the colorbar with. Strings map as keys to the WrightTools colormaps dictionary. Default is `default`. ticks : 1D array-like (optional) Ticks. Default is None. clim : two element list (optional) The true limits of the colorbar, in the same units as ticks. If None, streaches the colorbar over the limits of ticks. Default is None. vlim : two element list-like (optional) The limits of the displayed colorbar, in the same units as ticks. If None, displays over clim. Default is None. label : str (optional) Label. Default is None. tick_fontsize : number (optional) Fontsize. Default is 14. label_fontsize : number (optional) Label fontsize. Default is 18. decimals : integer (optional) Number of decimals to appear in tick labels. Default is None (best guess). orientation : {'vertical', 'horizontal'} (optional) Colorbar orientation. Default is vertical. ticklocation : {'auto', 'left', 'right', 'top', 'bottom'} (optional) Tick location. Default is auto. extend : {‘neither’, ‘both’, ‘min’, ‘max’} (optional) If not ‘neither’, make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. extendfrac : {None, ‘auto’, length, lengths} (optional) If set to None, both the minimum and maximum triangular colorbar extensions have a length of 5% of the interior colorbar length (this is the default setting). If set to ‘auto’, makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to ‘uniform’) or the same lengths as the respective adjacent interior boxes (when spacing is set to ‘proportional’). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length. extendrect : bool (optional) If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. Returns ------- matplotlib.colorbar.ColorbarBase object The created colorbar. """ # parse cax if cax is None: cax = plt.gca() # parse cmap if isinstance(cmap, str): cmap = colormaps[cmap] # parse ticks if ticks is None: ticks = np.linspace(0, 1, 11) # parse clim if clim is None: clim = [min(ticks), max(ticks)] # parse clim if vlim is None: vlim = clim if max(vlim) == min(vlim): vlim[-1] += 1e-1 # parse format if isinstance(decimals, int): format = "%.{0}f".format(decimals) else: magnitude = int(np.log10(max(vlim) - min(vlim)) - 0.99) if 1 > magnitude > -3: format = "%.{0}f".format(-magnitude + 1) elif magnitude in (1, 2, 3): format = "%i" else: # scientific notation def fmt(x, _): return "%.1f" % (x / float(10 ** magnitude)) format = matplotlib.ticker.FuncFormatter(fmt) magnitude_label = r" $\mathsf{\times 10^{%d}}$" % magnitude if label is None: label = magnitude_label else: label = " ".join([label, magnitude_label]) # make cbar norm = matplotlib.colors.Normalize(vmin=vlim[0], vmax=vlim[1]) cbar = matplotlib.colorbar.ColorbarBase( ax=cax, cmap=cmap, norm=norm, ticks=ticks, orientation=orientation, ticklocation=ticklocation, format=format, extend=extend, extendfrac=extendfrac, extendrect=extendrect, ) # coerce properties cbar.set_clim(clim[0], clim[1]) cbar.ax.tick_params(labelsize=tick_fontsize) if label: cbar.set_label(label, fontsize=label_fontsize) # finish return cbar
python
def plot_colorbar( cax=None, cmap="default", ticks=None, clim=None, vlim=None, label=None, tick_fontsize=14, label_fontsize=18, decimals=None, orientation="vertical", ticklocation="auto", extend="neither", extendfrac=None, extendrect=False, ): """Easily add a colormap to an axis. Parameters ---------- cax : matplotlib axis (optional) The axis to plot the colorbar on. Finds the current axis if none is given. cmap : string or LinearSegmentedColormap (optional) The colormap to fill the colorbar with. Strings map as keys to the WrightTools colormaps dictionary. Default is `default`. ticks : 1D array-like (optional) Ticks. Default is None. clim : two element list (optional) The true limits of the colorbar, in the same units as ticks. If None, streaches the colorbar over the limits of ticks. Default is None. vlim : two element list-like (optional) The limits of the displayed colorbar, in the same units as ticks. If None, displays over clim. Default is None. label : str (optional) Label. Default is None. tick_fontsize : number (optional) Fontsize. Default is 14. label_fontsize : number (optional) Label fontsize. Default is 18. decimals : integer (optional) Number of decimals to appear in tick labels. Default is None (best guess). orientation : {'vertical', 'horizontal'} (optional) Colorbar orientation. Default is vertical. ticklocation : {'auto', 'left', 'right', 'top', 'bottom'} (optional) Tick location. Default is auto. extend : {‘neither’, ‘both’, ‘min’, ‘max’} (optional) If not ‘neither’, make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. extendfrac : {None, ‘auto’, length, lengths} (optional) If set to None, both the minimum and maximum triangular colorbar extensions have a length of 5% of the interior colorbar length (this is the default setting). If set to ‘auto’, makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to ‘uniform’) or the same lengths as the respective adjacent interior boxes (when spacing is set to ‘proportional’). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length. extendrect : bool (optional) If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. Returns ------- matplotlib.colorbar.ColorbarBase object The created colorbar. """ # parse cax if cax is None: cax = plt.gca() # parse cmap if isinstance(cmap, str): cmap = colormaps[cmap] # parse ticks if ticks is None: ticks = np.linspace(0, 1, 11) # parse clim if clim is None: clim = [min(ticks), max(ticks)] # parse clim if vlim is None: vlim = clim if max(vlim) == min(vlim): vlim[-1] += 1e-1 # parse format if isinstance(decimals, int): format = "%.{0}f".format(decimals) else: magnitude = int(np.log10(max(vlim) - min(vlim)) - 0.99) if 1 > magnitude > -3: format = "%.{0}f".format(-magnitude + 1) elif magnitude in (1, 2, 3): format = "%i" else: # scientific notation def fmt(x, _): return "%.1f" % (x / float(10 ** magnitude)) format = matplotlib.ticker.FuncFormatter(fmt) magnitude_label = r" $\mathsf{\times 10^{%d}}$" % magnitude if label is None: label = magnitude_label else: label = " ".join([label, magnitude_label]) # make cbar norm = matplotlib.colors.Normalize(vmin=vlim[0], vmax=vlim[1]) cbar = matplotlib.colorbar.ColorbarBase( ax=cax, cmap=cmap, norm=norm, ticks=ticks, orientation=orientation, ticklocation=ticklocation, format=format, extend=extend, extendfrac=extendfrac, extendrect=extendrect, ) # coerce properties cbar.set_clim(clim[0], clim[1]) cbar.ax.tick_params(labelsize=tick_fontsize) if label: cbar.set_label(label, fontsize=label_fontsize) # finish return cbar
[ "def", "plot_colorbar", "(", "cax", "=", "None", ",", "cmap", "=", "\"default\"", ",", "ticks", "=", "None", ",", "clim", "=", "None", ",", "vlim", "=", "None", ",", "label", "=", "None", ",", "tick_fontsize", "=", "14", ",", "label_fontsize", "=", "...
Easily add a colormap to an axis. Parameters ---------- cax : matplotlib axis (optional) The axis to plot the colorbar on. Finds the current axis if none is given. cmap : string or LinearSegmentedColormap (optional) The colormap to fill the colorbar with. Strings map as keys to the WrightTools colormaps dictionary. Default is `default`. ticks : 1D array-like (optional) Ticks. Default is None. clim : two element list (optional) The true limits of the colorbar, in the same units as ticks. If None, streaches the colorbar over the limits of ticks. Default is None. vlim : two element list-like (optional) The limits of the displayed colorbar, in the same units as ticks. If None, displays over clim. Default is None. label : str (optional) Label. Default is None. tick_fontsize : number (optional) Fontsize. Default is 14. label_fontsize : number (optional) Label fontsize. Default is 18. decimals : integer (optional) Number of decimals to appear in tick labels. Default is None (best guess). orientation : {'vertical', 'horizontal'} (optional) Colorbar orientation. Default is vertical. ticklocation : {'auto', 'left', 'right', 'top', 'bottom'} (optional) Tick location. Default is auto. extend : {‘neither’, ‘both’, ‘min’, ‘max’} (optional) If not ‘neither’, make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. extendfrac : {None, ‘auto’, length, lengths} (optional) If set to None, both the minimum and maximum triangular colorbar extensions have a length of 5% of the interior colorbar length (this is the default setting). If set to ‘auto’, makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to ‘uniform’) or the same lengths as the respective adjacent interior boxes (when spacing is set to ‘proportional’). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length. extendrect : bool (optional) If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. Returns ------- matplotlib.colorbar.ColorbarBase object The created colorbar.
[ "Easily", "add", "a", "colormap", "to", "an", "axis", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L565-L692
train
33,681
wright-group/WrightTools
WrightTools/artists/_helpers.py
plot_margins
def plot_margins(*, fig=None, inches=1., centers=True, edges=True): """Add lines onto a figure indicating the margins, centers, and edges. Useful for ensuring your figure design scripts work as intended, and for laying out figures. Parameters ---------- fig : matplotlib.figure.Figure object (optional) The figure to plot onto. If None, gets current figure. Default is None. inches : float (optional) The size of the figure margin, in inches. Default is 1. centers : bool (optional) Toggle for plotting lines indicating the figure center. Default is True. edges : bool (optional) Toggle for plotting lines indicating the figure edges. Default is True. """ if fig is None: fig = plt.gcf() size = fig.get_size_inches() # [H, V] trans_vert = inches / size[0] left = matplotlib.lines.Line2D( [trans_vert, trans_vert], [0, 1], transform=fig.transFigure, figure=fig ) right = matplotlib.lines.Line2D( [1 - trans_vert, 1 - trans_vert], [0, 1], transform=fig.transFigure, figure=fig ) trans_horz = inches / size[1] bottom = matplotlib.lines.Line2D( [0, 1], [trans_horz, trans_horz], transform=fig.transFigure, figure=fig ) top = matplotlib.lines.Line2D( [0, 1], [1 - trans_horz, 1 - trans_horz], transform=fig.transFigure, figure=fig ) fig.lines.extend([left, right, bottom, top]) if centers: vert = matplotlib.lines.Line2D( [0.5, 0.5], [0, 1], transform=fig.transFigure, figure=fig, c="r" ) horiz = matplotlib.lines.Line2D( [0, 1], [0.5, 0.5], transform=fig.transFigure, figure=fig, c="r" ) fig.lines.extend([vert, horiz]) if edges: left = matplotlib.lines.Line2D( [0, 0], [0, 1], transform=fig.transFigure, figure=fig, c="k" ) right = matplotlib.lines.Line2D( [1, 1], [0, 1], transform=fig.transFigure, figure=fig, c="k" ) bottom = matplotlib.lines.Line2D( [0, 1], [0, 0], transform=fig.transFigure, figure=fig, c="k" ) top = matplotlib.lines.Line2D([0, 1], [1, 1], transform=fig.transFigure, figure=fig, c="k") fig.lines.extend([left, right, bottom, top])
python
def plot_margins(*, fig=None, inches=1., centers=True, edges=True): """Add lines onto a figure indicating the margins, centers, and edges. Useful for ensuring your figure design scripts work as intended, and for laying out figures. Parameters ---------- fig : matplotlib.figure.Figure object (optional) The figure to plot onto. If None, gets current figure. Default is None. inches : float (optional) The size of the figure margin, in inches. Default is 1. centers : bool (optional) Toggle for plotting lines indicating the figure center. Default is True. edges : bool (optional) Toggle for plotting lines indicating the figure edges. Default is True. """ if fig is None: fig = plt.gcf() size = fig.get_size_inches() # [H, V] trans_vert = inches / size[0] left = matplotlib.lines.Line2D( [trans_vert, trans_vert], [0, 1], transform=fig.transFigure, figure=fig ) right = matplotlib.lines.Line2D( [1 - trans_vert, 1 - trans_vert], [0, 1], transform=fig.transFigure, figure=fig ) trans_horz = inches / size[1] bottom = matplotlib.lines.Line2D( [0, 1], [trans_horz, trans_horz], transform=fig.transFigure, figure=fig ) top = matplotlib.lines.Line2D( [0, 1], [1 - trans_horz, 1 - trans_horz], transform=fig.transFigure, figure=fig ) fig.lines.extend([left, right, bottom, top]) if centers: vert = matplotlib.lines.Line2D( [0.5, 0.5], [0, 1], transform=fig.transFigure, figure=fig, c="r" ) horiz = matplotlib.lines.Line2D( [0, 1], [0.5, 0.5], transform=fig.transFigure, figure=fig, c="r" ) fig.lines.extend([vert, horiz]) if edges: left = matplotlib.lines.Line2D( [0, 0], [0, 1], transform=fig.transFigure, figure=fig, c="k" ) right = matplotlib.lines.Line2D( [1, 1], [0, 1], transform=fig.transFigure, figure=fig, c="k" ) bottom = matplotlib.lines.Line2D( [0, 1], [0, 0], transform=fig.transFigure, figure=fig, c="k" ) top = matplotlib.lines.Line2D([0, 1], [1, 1], transform=fig.transFigure, figure=fig, c="k") fig.lines.extend([left, right, bottom, top])
[ "def", "plot_margins", "(", "*", ",", "fig", "=", "None", ",", "inches", "=", "1.", ",", "centers", "=", "True", ",", "edges", "=", "True", ")", ":", "if", "fig", "is", "None", ":", "fig", "=", "plt", ".", "gcf", "(", ")", "size", "=", "fig", ...
Add lines onto a figure indicating the margins, centers, and edges. Useful for ensuring your figure design scripts work as intended, and for laying out figures. Parameters ---------- fig : matplotlib.figure.Figure object (optional) The figure to plot onto. If None, gets current figure. Default is None. inches : float (optional) The size of the figure margin, in inches. Default is 1. centers : bool (optional) Toggle for plotting lines indicating the figure center. Default is True. edges : bool (optional) Toggle for plotting lines indicating the figure edges. Default is True.
[ "Add", "lines", "onto", "a", "figure", "indicating", "the", "margins", "centers", "and", "edges", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L695-L750
train
33,682
wright-group/WrightTools
WrightTools/artists/_helpers.py
plot_gridlines
def plot_gridlines(ax=None, c="grey", lw=1, diagonal=False, zorder=2, makegrid=True): """Plot dotted gridlines onto an axis. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to add gridlines to. If None, uses current axis. Default is None. c : matplotlib color argument (optional) Gridline color. Default is grey. lw : number (optional) Gridline linewidth. Default is 1. diagonal : boolean (optional) Toggle inclusion of diagonal gridline. Default is False. zorder : number (optional) zorder of plotted grid. Default is 2. """ # get ax if ax is None: ax = plt.gca() ax.grid() # get dashes ls = ":" dashes = (lw / 2, lw) # grid # ax.grid(True) lines = ax.xaxis.get_gridlines() + ax.yaxis.get_gridlines() for line in lines.copy(): line.set_linestyle(":") line.set_color(c) line.set_linewidth(lw) line.set_zorder(zorder) line.set_dashes(dashes) ax.add_line(line) # diagonal if diagonal: min_xi, max_xi = ax.get_xlim() min_yi, max_yi = ax.get_ylim() diag_min = max(min_xi, min_yi) diag_max = min(max_xi, max_yi) ax.plot( [diag_min, diag_max], [diag_min, diag_max], c=c, ls=ls, lw=lw, zorder=zorder, dashes=dashes, ) # Plot resets xlim and ylim sometimes for unknown reasons. # This is here to ensure that the xlim and ylim are unchanged # after adding a diagonal, whose limits are calculated so # as to not change the xlim and ylim. # -- KFS 2017-09-26 ax.set_ylim(min_yi, max_yi) ax.set_xlim(min_xi, max_xi)
python
def plot_gridlines(ax=None, c="grey", lw=1, diagonal=False, zorder=2, makegrid=True): """Plot dotted gridlines onto an axis. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to add gridlines to. If None, uses current axis. Default is None. c : matplotlib color argument (optional) Gridline color. Default is grey. lw : number (optional) Gridline linewidth. Default is 1. diagonal : boolean (optional) Toggle inclusion of diagonal gridline. Default is False. zorder : number (optional) zorder of plotted grid. Default is 2. """ # get ax if ax is None: ax = plt.gca() ax.grid() # get dashes ls = ":" dashes = (lw / 2, lw) # grid # ax.grid(True) lines = ax.xaxis.get_gridlines() + ax.yaxis.get_gridlines() for line in lines.copy(): line.set_linestyle(":") line.set_color(c) line.set_linewidth(lw) line.set_zorder(zorder) line.set_dashes(dashes) ax.add_line(line) # diagonal if diagonal: min_xi, max_xi = ax.get_xlim() min_yi, max_yi = ax.get_ylim() diag_min = max(min_xi, min_yi) diag_max = min(max_xi, max_yi) ax.plot( [diag_min, diag_max], [diag_min, diag_max], c=c, ls=ls, lw=lw, zorder=zorder, dashes=dashes, ) # Plot resets xlim and ylim sometimes for unknown reasons. # This is here to ensure that the xlim and ylim are unchanged # after adding a diagonal, whose limits are calculated so # as to not change the xlim and ylim. # -- KFS 2017-09-26 ax.set_ylim(min_yi, max_yi) ax.set_xlim(min_xi, max_xi)
[ "def", "plot_gridlines", "(", "ax", "=", "None", ",", "c", "=", "\"grey\"", ",", "lw", "=", "1", ",", "diagonal", "=", "False", ",", "zorder", "=", "2", ",", "makegrid", "=", "True", ")", ":", "# get ax", "if", "ax", "is", "None", ":", "ax", "=",...
Plot dotted gridlines onto an axis. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to add gridlines to. If None, uses current axis. Default is None. c : matplotlib color argument (optional) Gridline color. Default is grey. lw : number (optional) Gridline linewidth. Default is 1. diagonal : boolean (optional) Toggle inclusion of diagonal gridline. Default is False. zorder : number (optional) zorder of plotted grid. Default is 2.
[ "Plot", "dotted", "gridlines", "onto", "an", "axis", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L753-L808
train
33,683
wright-group/WrightTools
WrightTools/artists/_helpers.py
savefig
def savefig(path, fig=None, close=True, *, dpi=300): """Save a figure. Parameters ---------- path : str Path to save figure at. fig : matplotlib.figure.Figure object (optional) The figure to plot onto. If None, gets current figure. Default is None. close : bool (optional) Toggle closing of figure after saving. Default is True. Returns ------- str The full path where the figure was saved. """ # get fig if fig is None: fig = plt.gcf() # get full path path = os.path.abspath(path) # save plt.savefig(path, dpi=dpi, transparent=False, pad_inches=1, facecolor="none") # close if close: plt.close(fig) # finish return path
python
def savefig(path, fig=None, close=True, *, dpi=300): """Save a figure. Parameters ---------- path : str Path to save figure at. fig : matplotlib.figure.Figure object (optional) The figure to plot onto. If None, gets current figure. Default is None. close : bool (optional) Toggle closing of figure after saving. Default is True. Returns ------- str The full path where the figure was saved. """ # get fig if fig is None: fig = plt.gcf() # get full path path = os.path.abspath(path) # save plt.savefig(path, dpi=dpi, transparent=False, pad_inches=1, facecolor="none") # close if close: plt.close(fig) # finish return path
[ "def", "savefig", "(", "path", ",", "fig", "=", "None", ",", "close", "=", "True", ",", "*", ",", "dpi", "=", "300", ")", ":", "# get fig", "if", "fig", "is", "None", ":", "fig", "=", "plt", ".", "gcf", "(", ")", "# get full path", "path", "=", ...
Save a figure. Parameters ---------- path : str Path to save figure at. fig : matplotlib.figure.Figure object (optional) The figure to plot onto. If None, gets current figure. Default is None. close : bool (optional) Toggle closing of figure after saving. Default is True. Returns ------- str The full path where the figure was saved.
[ "Save", "a", "figure", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L811-L839
train
33,684
wright-group/WrightTools
WrightTools/artists/_helpers.py
set_ax_labels
def set_ax_labels(ax=None, xlabel=None, ylabel=None, xticks=None, yticks=None, label_fontsize=18): """Set all axis labels properties easily. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to set. If None, uses current axis. Default is None. xlabel : None or string (optional) x axis label. Default is None. ylabel : None or string (optional) y axis label. Default is None. xticks : None or False or list of numbers xticks. If False, ticks are hidden. Default is None. yticks : None or False or list of numbers yticks. If False, ticks are hidden. Default is None. label_fontsize : number Fontsize of label. Default is 18. See Also -------- set_fig_labels """ # get ax if ax is None: ax = plt.gca() # x if xlabel is not None: ax.set_xlabel(xlabel, fontsize=label_fontsize) if xticks is not None: if isinstance(xticks, bool): plt.setp(ax.get_xticklabels(), visible=xticks) if not xticks: ax.tick_params(axis="x", which="both", length=0) else: ax.set_xticks(xticks) # y if ylabel is not None: ax.set_ylabel(ylabel, fontsize=label_fontsize) if yticks is not None: if isinstance(yticks, bool): plt.setp(ax.get_yticklabels(), visible=yticks) if not yticks: ax.tick_params(axis="y", which="both", length=0) else: ax.set_yticks(yticks)
python
def set_ax_labels(ax=None, xlabel=None, ylabel=None, xticks=None, yticks=None, label_fontsize=18): """Set all axis labels properties easily. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to set. If None, uses current axis. Default is None. xlabel : None or string (optional) x axis label. Default is None. ylabel : None or string (optional) y axis label. Default is None. xticks : None or False or list of numbers xticks. If False, ticks are hidden. Default is None. yticks : None or False or list of numbers yticks. If False, ticks are hidden. Default is None. label_fontsize : number Fontsize of label. Default is 18. See Also -------- set_fig_labels """ # get ax if ax is None: ax = plt.gca() # x if xlabel is not None: ax.set_xlabel(xlabel, fontsize=label_fontsize) if xticks is not None: if isinstance(xticks, bool): plt.setp(ax.get_xticklabels(), visible=xticks) if not xticks: ax.tick_params(axis="x", which="both", length=0) else: ax.set_xticks(xticks) # y if ylabel is not None: ax.set_ylabel(ylabel, fontsize=label_fontsize) if yticks is not None: if isinstance(yticks, bool): plt.setp(ax.get_yticklabels(), visible=yticks) if not yticks: ax.tick_params(axis="y", which="both", length=0) else: ax.set_yticks(yticks)
[ "def", "set_ax_labels", "(", "ax", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "xticks", "=", "None", ",", "yticks", "=", "None", ",", "label_fontsize", "=", "18", ")", ":", "# get ax", "if", "ax", "is", "None", ":", "...
Set all axis labels properties easily. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to set. If None, uses current axis. Default is None. xlabel : None or string (optional) x axis label. Default is None. ylabel : None or string (optional) y axis label. Default is None. xticks : None or False or list of numbers xticks. If False, ticks are hidden. Default is None. yticks : None or False or list of numbers yticks. If False, ticks are hidden. Default is None. label_fontsize : number Fontsize of label. Default is 18. See Also -------- set_fig_labels
[ "Set", "all", "axis", "labels", "properties", "easily", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L842-L886
train
33,685
wright-group/WrightTools
WrightTools/artists/_helpers.py
set_ax_spines
def set_ax_spines(ax=None, *, c="k", lw=3, zorder=10): """Easily set the properties of all four axis spines. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to set. If None, uses current axis. Default is None. c : any matplotlib color argument (optional) Spine color. Default is k. lw : number (optional) Spine linewidth. Default is 3. zorder : number (optional) Spine zorder. Default is 10. """ # get ax if ax is None: ax = plt.gca() # apply for key in ["bottom", "top", "right", "left"]: ax.spines[key].set_color(c) ax.spines[key].set_linewidth(lw) ax.spines[key].zorder = zorder
python
def set_ax_spines(ax=None, *, c="k", lw=3, zorder=10): """Easily set the properties of all four axis spines. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to set. If None, uses current axis. Default is None. c : any matplotlib color argument (optional) Spine color. Default is k. lw : number (optional) Spine linewidth. Default is 3. zorder : number (optional) Spine zorder. Default is 10. """ # get ax if ax is None: ax = plt.gca() # apply for key in ["bottom", "top", "right", "left"]: ax.spines[key].set_color(c) ax.spines[key].set_linewidth(lw) ax.spines[key].zorder = zorder
[ "def", "set_ax_spines", "(", "ax", "=", "None", ",", "*", ",", "c", "=", "\"k\"", ",", "lw", "=", "3", ",", "zorder", "=", "10", ")", ":", "# get ax", "if", "ax", "is", "None", ":", "ax", "=", "plt", ".", "gca", "(", ")", "# apply", "for", "k...
Easily set the properties of all four axis spines. Parameters ---------- ax : matplotlib AxesSubplot object (optional) Axis to set. If None, uses current axis. Default is None. c : any matplotlib color argument (optional) Spine color. Default is k. lw : number (optional) Spine linewidth. Default is 3. zorder : number (optional) Spine zorder. Default is 10.
[ "Easily", "set", "the", "properties", "of", "all", "four", "axis", "spines", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L889-L910
train
33,686
wright-group/WrightTools
WrightTools/artists/_helpers.py
set_fig_labels
def set_fig_labels( fig=None, xlabel=None, ylabel=None, xticks=None, yticks=None, title=None, row=-1, col=0, label_fontsize=18, title_fontsize=20, ): """Set all axis labels of a figure simultaniously. Only plots ticks and labels for edge axes. Parameters ---------- fig : matplotlib.figure.Figure object (optional) Figure to set labels of. If None, uses current figure. Default is None. xlabel : None or string (optional) x axis label. Default is None. ylabel : None or string (optional) y axis label. Default is None. xticks : None or False or list of numbers (optional) xticks. If False, ticks are hidden. Default is None. yticks : None or False or list of numbers (optional) yticks. If False, ticks are hidden. Default is None. title : None or string (optional) Title of figure. Default is None. row : integer or slice (optional) Row to label. Default is -1. If slice, step is ignored. col : integer or slice (optional) col to label. Default is 0. If slice, step is ignored. label_fontsize : number (optional) Fontsize of label. Default is 18. title_fontsize : number (optional) Fontsize of title. Default is 20. See Also -------- set_ax_labels """ # get fig if fig is None: fig = plt.gcf() # interpret row numRows = fig.axes[0].numRows if isinstance(row, int): row %= numRows row = slice(0, row) row_start, row_stop, _ = row.indices(numRows) # interpret col numCols = fig.axes[0].numCols if isinstance(col, int): col %= numCols col = slice(col, -1) col_start, col_stop, _ = col.indices(numCols) # axes for ax in fig.axes: if ax.is_sideplot: continue if row_start <= ax.rowNum <= row_stop and col_start <= ax.colNum <= col_stop: if ax.colNum == col_start: set_ax_labels(ax=ax, ylabel=ylabel, yticks=yticks, label_fontsize=label_fontsize) else: set_ax_labels(ax=ax, ylabel="", yticks=False) if ax.rowNum == row_stop: set_ax_labels(ax=ax, xlabel=xlabel, xticks=xticks, label_fontsize=label_fontsize) else: set_ax_labels(ax=ax, xlabel="", xticks=False) # title if title is not None: fig.suptitle(title, fontsize=title_fontsize)
python
def set_fig_labels( fig=None, xlabel=None, ylabel=None, xticks=None, yticks=None, title=None, row=-1, col=0, label_fontsize=18, title_fontsize=20, ): """Set all axis labels of a figure simultaniously. Only plots ticks and labels for edge axes. Parameters ---------- fig : matplotlib.figure.Figure object (optional) Figure to set labels of. If None, uses current figure. Default is None. xlabel : None or string (optional) x axis label. Default is None. ylabel : None or string (optional) y axis label. Default is None. xticks : None or False or list of numbers (optional) xticks. If False, ticks are hidden. Default is None. yticks : None or False or list of numbers (optional) yticks. If False, ticks are hidden. Default is None. title : None or string (optional) Title of figure. Default is None. row : integer or slice (optional) Row to label. Default is -1. If slice, step is ignored. col : integer or slice (optional) col to label. Default is 0. If slice, step is ignored. label_fontsize : number (optional) Fontsize of label. Default is 18. title_fontsize : number (optional) Fontsize of title. Default is 20. See Also -------- set_ax_labels """ # get fig if fig is None: fig = plt.gcf() # interpret row numRows = fig.axes[0].numRows if isinstance(row, int): row %= numRows row = slice(0, row) row_start, row_stop, _ = row.indices(numRows) # interpret col numCols = fig.axes[0].numCols if isinstance(col, int): col %= numCols col = slice(col, -1) col_start, col_stop, _ = col.indices(numCols) # axes for ax in fig.axes: if ax.is_sideplot: continue if row_start <= ax.rowNum <= row_stop and col_start <= ax.colNum <= col_stop: if ax.colNum == col_start: set_ax_labels(ax=ax, ylabel=ylabel, yticks=yticks, label_fontsize=label_fontsize) else: set_ax_labels(ax=ax, ylabel="", yticks=False) if ax.rowNum == row_stop: set_ax_labels(ax=ax, xlabel=xlabel, xticks=xticks, label_fontsize=label_fontsize) else: set_ax_labels(ax=ax, xlabel="", xticks=False) # title if title is not None: fig.suptitle(title, fontsize=title_fontsize)
[ "def", "set_fig_labels", "(", "fig", "=", "None", ",", "xlabel", "=", "None", ",", "ylabel", "=", "None", ",", "xticks", "=", "None", ",", "yticks", "=", "None", ",", "title", "=", "None", ",", "row", "=", "-", "1", ",", "col", "=", "0", ",", "...
Set all axis labels of a figure simultaniously. Only plots ticks and labels for edge axes. Parameters ---------- fig : matplotlib.figure.Figure object (optional) Figure to set labels of. If None, uses current figure. Default is None. xlabel : None or string (optional) x axis label. Default is None. ylabel : None or string (optional) y axis label. Default is None. xticks : None or False or list of numbers (optional) xticks. If False, ticks are hidden. Default is None. yticks : None or False or list of numbers (optional) yticks. If False, ticks are hidden. Default is None. title : None or string (optional) Title of figure. Default is None. row : integer or slice (optional) Row to label. Default is -1. If slice, step is ignored. col : integer or slice (optional) col to label. Default is 0. If slice, step is ignored. label_fontsize : number (optional) Fontsize of label. Default is 18. title_fontsize : number (optional) Fontsize of title. Default is 20. See Also -------- set_ax_labels
[ "Set", "all", "axis", "labels", "of", "a", "figure", "simultaniously", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L913-L986
train
33,687
wright-group/WrightTools
WrightTools/artists/_helpers.py
subplots_adjust
def subplots_adjust(fig=None, inches=1): """Enforce margin to be equal around figure, starting at subplots. .. note:: You probably should be using wt.artists.create_figure instead. See Also -------- wt.artists.plot_margins Visualize margins, for debugging / layout. wt.artists.create_figure Convinience method for creating well-behaved figures. """ if fig is None: fig = plt.gcf() size = fig.get_size_inches() vert = inches / size[0] horz = inches / size[1] fig.subplots_adjust(vert, horz, 1 - vert, 1 - horz)
python
def subplots_adjust(fig=None, inches=1): """Enforce margin to be equal around figure, starting at subplots. .. note:: You probably should be using wt.artists.create_figure instead. See Also -------- wt.artists.plot_margins Visualize margins, for debugging / layout. wt.artists.create_figure Convinience method for creating well-behaved figures. """ if fig is None: fig = plt.gcf() size = fig.get_size_inches() vert = inches / size[0] horz = inches / size[1] fig.subplots_adjust(vert, horz, 1 - vert, 1 - horz)
[ "def", "subplots_adjust", "(", "fig", "=", "None", ",", "inches", "=", "1", ")", ":", "if", "fig", "is", "None", ":", "fig", "=", "plt", ".", "gcf", "(", ")", "size", "=", "fig", ".", "get_size_inches", "(", ")", "vert", "=", "inches", "/", "size...
Enforce margin to be equal around figure, starting at subplots. .. note:: You probably should be using wt.artists.create_figure instead. See Also -------- wt.artists.plot_margins Visualize margins, for debugging / layout. wt.artists.create_figure Convinience method for creating well-behaved figures.
[ "Enforce", "margin", "to", "be", "equal", "around", "figure", "starting", "at", "subplots", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L989-L1007
train
33,688
wright-group/WrightTools
WrightTools/artists/_helpers.py
stitch_to_animation
def stitch_to_animation(images, outpath=None, *, duration=0.5, palettesize=256, verbose=True): """Stitch a series of images into an animation. Currently supports animated gifs, other formats coming as needed. Parameters ---------- images : list of strings Filepaths to the images to stitch together, in order of apperence. outpath : string (optional) Path of output, including extension. If None, bases output path on path of first path in `images`. Default is None. duration : number or list of numbers (optional) Duration of (each) frame in seconds. Default is 0.5. palettesize : int (optional) The number of colors in the resulting animation. Input is rounded to the nearest power of 2. Default is 1024. verbose : bool (optional) Toggle talkback. Default is True. """ # parse filename if outpath is None: outpath = os.path.splitext(images[0])[0] + ".gif" # write t = wt_kit.Timer(verbose=False) with t, imageio.get_writer( outpath, mode="I", duration=duration, palettesize=palettesize ) as writer: for p in images: image = imageio.imread(p) writer.append_data(image) # finish if verbose: interval = np.round(t.interval, 2) print("gif generated in {0} seconds - saved at {1}".format(interval, outpath)) return outpath
python
def stitch_to_animation(images, outpath=None, *, duration=0.5, palettesize=256, verbose=True): """Stitch a series of images into an animation. Currently supports animated gifs, other formats coming as needed. Parameters ---------- images : list of strings Filepaths to the images to stitch together, in order of apperence. outpath : string (optional) Path of output, including extension. If None, bases output path on path of first path in `images`. Default is None. duration : number or list of numbers (optional) Duration of (each) frame in seconds. Default is 0.5. palettesize : int (optional) The number of colors in the resulting animation. Input is rounded to the nearest power of 2. Default is 1024. verbose : bool (optional) Toggle talkback. Default is True. """ # parse filename if outpath is None: outpath = os.path.splitext(images[0])[0] + ".gif" # write t = wt_kit.Timer(verbose=False) with t, imageio.get_writer( outpath, mode="I", duration=duration, palettesize=palettesize ) as writer: for p in images: image = imageio.imread(p) writer.append_data(image) # finish if verbose: interval = np.round(t.interval, 2) print("gif generated in {0} seconds - saved at {1}".format(interval, outpath)) return outpath
[ "def", "stitch_to_animation", "(", "images", ",", "outpath", "=", "None", ",", "*", ",", "duration", "=", "0.5", ",", "palettesize", "=", "256", ",", "verbose", "=", "True", ")", ":", "# parse filename", "if", "outpath", "is", "None", ":", "outpath", "="...
Stitch a series of images into an animation. Currently supports animated gifs, other formats coming as needed. Parameters ---------- images : list of strings Filepaths to the images to stitch together, in order of apperence. outpath : string (optional) Path of output, including extension. If None, bases output path on path of first path in `images`. Default is None. duration : number or list of numbers (optional) Duration of (each) frame in seconds. Default is 0.5. palettesize : int (optional) The number of colors in the resulting animation. Input is rounded to the nearest power of 2. Default is 1024. verbose : bool (optional) Toggle talkback. Default is True.
[ "Stitch", "a", "series", "of", "images", "into", "an", "animation", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_helpers.py#L1010-L1045
train
33,689
wright-group/WrightTools
WrightTools/_group.py
Group.item_names
def item_names(self): """Item names.""" if "item_names" not in self.attrs.keys(): self.attrs["item_names"] = np.array([], dtype="S") return tuple(n.decode() for n in self.attrs["item_names"])
python
def item_names(self): """Item names.""" if "item_names" not in self.attrs.keys(): self.attrs["item_names"] = np.array([], dtype="S") return tuple(n.decode() for n in self.attrs["item_names"])
[ "def", "item_names", "(", "self", ")", ":", "if", "\"item_names\"", "not", "in", "self", ".", "attrs", ".", "keys", "(", ")", ":", "self", ".", "attrs", "[", "\"item_names\"", "]", "=", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "\"S\"",...
Item names.
[ "Item", "names", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_group.py#L226-L230
train
33,690
wright-group/WrightTools
WrightTools/_group.py
Group.natural_name
def natural_name(self): """Natural name.""" try: assert self._natural_name is not None except (AssertionError, AttributeError): self._natural_name = self.attrs["name"] finally: return self._natural_name
python
def natural_name(self): """Natural name.""" try: assert self._natural_name is not None except (AssertionError, AttributeError): self._natural_name = self.attrs["name"] finally: return self._natural_name
[ "def", "natural_name", "(", "self", ")", ":", "try", ":", "assert", "self", ".", "_natural_name", "is", "not", "None", "except", "(", "AssertionError", ",", "AttributeError", ")", ":", "self", ".", "_natural_name", "=", "self", ".", "attrs", "[", "\"name\"...
Natural name.
[ "Natural", "name", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_group.py#L233-L240
train
33,691
wright-group/WrightTools
WrightTools/_group.py
Group.natural_name
def natural_name(self, value): """Set natural name.""" if value is None: value = "" if hasattr(self, "_natural_name") and self.name != "/": keys = [k for k in self._instances.keys() if k.startswith(self.fullpath)] dskeys = [k for k in Dataset._instances.keys() if k.startswith(self.fullpath)] self.parent.move(self._natural_name, value) for k in keys: obj = self._instances.pop(k) self._instances[obj.fullpath] = obj for k in dskeys: obj = Dataset._instances.pop(k) Dataset._instances[obj.fullpath] = obj self._natural_name = self.attrs["name"] = value
python
def natural_name(self, value): """Set natural name.""" if value is None: value = "" if hasattr(self, "_natural_name") and self.name != "/": keys = [k for k in self._instances.keys() if k.startswith(self.fullpath)] dskeys = [k for k in Dataset._instances.keys() if k.startswith(self.fullpath)] self.parent.move(self._natural_name, value) for k in keys: obj = self._instances.pop(k) self._instances[obj.fullpath] = obj for k in dskeys: obj = Dataset._instances.pop(k) Dataset._instances[obj.fullpath] = obj self._natural_name = self.attrs["name"] = value
[ "def", "natural_name", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "value", "=", "\"\"", "if", "hasattr", "(", "self", ",", "\"_natural_name\"", ")", "and", "self", ".", "name", "!=", "\"/\"", ":", "keys", "=", "[", "k", ...
Set natural name.
[ "Set", "natural", "name", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_group.py#L243-L257
train
33,692
wright-group/WrightTools
WrightTools/_group.py
Group.close
def close(self): """Close the file that contains the Group. All groups which are in the file will be closed and removed from the _instances dictionaries. Tempfiles, if they exist, will be removed """ from .collection import Collection from .data._data import Channel, Data, Variable path = os.path.abspath(self.filepath) + "::" for key in list(Group._instances.keys()): if key.startswith(path): Group._instances.pop(key, None) if self.fid.valid > 0: # for some reason, the following file operations sometimes fail # this stops execution of the method, meaning that the tempfile is never removed # the following try case ensures that the tempfile code is always executed # ---Blaise 2018-01-08 try: self.file.flush() try: # Obtaining the file descriptor must be done prior to closing fd = self.fid.get_vfd_handle() except (NotImplementedError, ValueError): # only available with certain h5py drivers # not needed if not available pass self.file.close() try: if fd: os.close(fd) except OSError: # File already closed, e.g. pass except SystemError as e: warnings.warn("SystemError: {0}".format(e)) finally: if hasattr(self, "_tmpfile"): os.close(self._tmpfile[0]) os.remove(self._tmpfile[1])
python
def close(self): """Close the file that contains the Group. All groups which are in the file will be closed and removed from the _instances dictionaries. Tempfiles, if they exist, will be removed """ from .collection import Collection from .data._data import Channel, Data, Variable path = os.path.abspath(self.filepath) + "::" for key in list(Group._instances.keys()): if key.startswith(path): Group._instances.pop(key, None) if self.fid.valid > 0: # for some reason, the following file operations sometimes fail # this stops execution of the method, meaning that the tempfile is never removed # the following try case ensures that the tempfile code is always executed # ---Blaise 2018-01-08 try: self.file.flush() try: # Obtaining the file descriptor must be done prior to closing fd = self.fid.get_vfd_handle() except (NotImplementedError, ValueError): # only available with certain h5py drivers # not needed if not available pass self.file.close() try: if fd: os.close(fd) except OSError: # File already closed, e.g. pass except SystemError as e: warnings.warn("SystemError: {0}".format(e)) finally: if hasattr(self, "_tmpfile"): os.close(self._tmpfile[0]) os.remove(self._tmpfile[1])
[ "def", "close", "(", "self", ")", ":", "from", ".", "collection", "import", "Collection", "from", ".", "data", ".", "_data", "import", "Channel", ",", "Data", ",", "Variable", "path", "=", "os", ".", "path", ".", "abspath", "(", "self", ".", "filepath"...
Close the file that contains the Group. All groups which are in the file will be closed and removed from the _instances dictionaries. Tempfiles, if they exist, will be removed
[ "Close", "the", "file", "that", "contains", "the", "Group", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_group.py#L272-L314
train
33,693
wright-group/WrightTools
WrightTools/_group.py
Group.copy
def copy(self, parent=None, name=None, verbose=True): """Create a copy under parent. All children are copied as well. Parameters ---------- parent : WrightTools Collection (optional) Parent to copy within. If None, copy is created in root of new tempfile. Default is None. name : string (optional) Name of new copy at destination. If None, the current natural name is used. Default is None. verbose : boolean (optional) Toggle talkback. Default is True. Returns ------- Group Created copy. """ if name is None: name = self.natural_name if parent is None: from ._open import open as wt_open # circular import new = Group() # root of new tempfile # attrs new.attrs.update(self.attrs) new.natural_name = name # children for k, v in self.items(): super().copy(v, new, name=v.natural_name) new.flush() p = new.filepath new = wt_open(p) else: # copy self.file.copy(self.name, parent, name=name) new = parent[name] # finish if verbose: print("{0} copied to {1}".format(self.fullpath, new.fullpath)) return new
python
def copy(self, parent=None, name=None, verbose=True): """Create a copy under parent. All children are copied as well. Parameters ---------- parent : WrightTools Collection (optional) Parent to copy within. If None, copy is created in root of new tempfile. Default is None. name : string (optional) Name of new copy at destination. If None, the current natural name is used. Default is None. verbose : boolean (optional) Toggle talkback. Default is True. Returns ------- Group Created copy. """ if name is None: name = self.natural_name if parent is None: from ._open import open as wt_open # circular import new = Group() # root of new tempfile # attrs new.attrs.update(self.attrs) new.natural_name = name # children for k, v in self.items(): super().copy(v, new, name=v.natural_name) new.flush() p = new.filepath new = wt_open(p) else: # copy self.file.copy(self.name, parent, name=name) new = parent[name] # finish if verbose: print("{0} copied to {1}".format(self.fullpath, new.fullpath)) return new
[ "def", "copy", "(", "self", ",", "parent", "=", "None", ",", "name", "=", "None", ",", "verbose", "=", "True", ")", ":", "if", "name", "is", "None", ":", "name", "=", "self", ".", "natural_name", "if", "parent", "is", "None", ":", "from", ".", "_...
Create a copy under parent. All children are copied as well. Parameters ---------- parent : WrightTools Collection (optional) Parent to copy within. If None, copy is created in root of new tempfile. Default is None. name : string (optional) Name of new copy at destination. If None, the current natural name is used. Default is None. verbose : boolean (optional) Toggle talkback. Default is True. Returns ------- Group Created copy.
[ "Create", "a", "copy", "under", "parent", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_group.py#L316-L359
train
33,694
wright-group/WrightTools
WrightTools/_group.py
Group.save
def save(self, filepath=None, overwrite=False, verbose=True): """Save as root of a new file. Parameters ---------- filepath : Path-like object (optional) Filepath to write. If None, file is created using natural_name. overwrite : boolean (optional) Toggle overwrite behavior. Default is False. verbose : boolean (optional) Toggle talkback. Default is True Returns ------- str Written filepath. """ if filepath is None: filepath = pathlib.Path(".") / self.natural_name else: filepath = pathlib.Path(filepath) filepath = filepath.with_suffix(".wt5") filepath = filepath.absolute().expanduser() if filepath.exists(): if overwrite: filepath.unlink() else: raise wt_exceptions.FileExistsError(filepath) # copy to new file h5py.File(filepath) new = Group(filepath=filepath, edit_local=True) # attrs for k, v in self.attrs.items(): new.attrs[k] = v # children for k, v in self.items(): super().copy(v, new, name=v.natural_name) # finish new.flush() new.close() del new if verbose: print("file saved at", filepath) return str(filepath)
python
def save(self, filepath=None, overwrite=False, verbose=True): """Save as root of a new file. Parameters ---------- filepath : Path-like object (optional) Filepath to write. If None, file is created using natural_name. overwrite : boolean (optional) Toggle overwrite behavior. Default is False. verbose : boolean (optional) Toggle talkback. Default is True Returns ------- str Written filepath. """ if filepath is None: filepath = pathlib.Path(".") / self.natural_name else: filepath = pathlib.Path(filepath) filepath = filepath.with_suffix(".wt5") filepath = filepath.absolute().expanduser() if filepath.exists(): if overwrite: filepath.unlink() else: raise wt_exceptions.FileExistsError(filepath) # copy to new file h5py.File(filepath) new = Group(filepath=filepath, edit_local=True) # attrs for k, v in self.attrs.items(): new.attrs[k] = v # children for k, v in self.items(): super().copy(v, new, name=v.natural_name) # finish new.flush() new.close() del new if verbose: print("file saved at", filepath) return str(filepath)
[ "def", "save", "(", "self", ",", "filepath", "=", "None", ",", "overwrite", "=", "False", ",", "verbose", "=", "True", ")", ":", "if", "filepath", "is", "None", ":", "filepath", "=", "pathlib", ".", "Path", "(", "\".\"", ")", "/", "self", ".", "nat...
Save as root of a new file. Parameters ---------- filepath : Path-like object (optional) Filepath to write. If None, file is created using natural_name. overwrite : boolean (optional) Toggle overwrite behavior. Default is False. verbose : boolean (optional) Toggle talkback. Default is True Returns ------- str Written filepath.
[ "Save", "as", "root", "of", "a", "new", "file", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/_group.py#L365-L409
train
33,695
wright-group/WrightTools
WrightTools/data/_jasco.py
from_JASCO
def from_JASCO(filepath, name=None, parent=None, verbose=True) -> Data: """Create a data object from JASCO UV-Vis spectrometers. Parameters ---------- filepath : path-like Path to .txt file. Can be either a local or remote file (http/ftp). Can be compressed with gz/bz2, decompression based on file name. name : string (optional) Name to give to the created data object. If None, filename is used. Default is None. parent : WrightTools.Collection (optional) Collection to place new data object within. Default is None. verbose : boolean (optional) Toggle talkback. Default is True. Returns ------- data New data object(s). """ # parse filepath filestr = os.fspath(filepath) filepath = pathlib.Path(filepath) if not ".txt" in filepath.suffixes: wt_exceptions.WrongFileTypeWarning.warn(filepath, ".txt") # parse name if not name: name = filepath.name.split(".")[0] # create data kwargs = {"name": name, "kind": "JASCO", "source": filestr} if parent is None: data = Data(**kwargs) else: data = parent.create_data(**kwargs) # array ds = np.DataSource(None) f = ds.open(filestr, "rt") arr = np.genfromtxt(f, skip_header=18).T f.close() # chew through all scans data.create_variable(name="energy", values=arr[0], units="nm") data.create_channel(name="signal", values=arr[1]) data.transform("energy") # finish if verbose: print("data created at {0}".format(data.fullpath)) print(" range: {0} to {1} (nm)".format(data.energy[0], data.energy[-1])) print(" size: {0}".format(data.size)) return data
python
def from_JASCO(filepath, name=None, parent=None, verbose=True) -> Data: """Create a data object from JASCO UV-Vis spectrometers. Parameters ---------- filepath : path-like Path to .txt file. Can be either a local or remote file (http/ftp). Can be compressed with gz/bz2, decompression based on file name. name : string (optional) Name to give to the created data object. If None, filename is used. Default is None. parent : WrightTools.Collection (optional) Collection to place new data object within. Default is None. verbose : boolean (optional) Toggle talkback. Default is True. Returns ------- data New data object(s). """ # parse filepath filestr = os.fspath(filepath) filepath = pathlib.Path(filepath) if not ".txt" in filepath.suffixes: wt_exceptions.WrongFileTypeWarning.warn(filepath, ".txt") # parse name if not name: name = filepath.name.split(".")[0] # create data kwargs = {"name": name, "kind": "JASCO", "source": filestr} if parent is None: data = Data(**kwargs) else: data = parent.create_data(**kwargs) # array ds = np.DataSource(None) f = ds.open(filestr, "rt") arr = np.genfromtxt(f, skip_header=18).T f.close() # chew through all scans data.create_variable(name="energy", values=arr[0], units="nm") data.create_channel(name="signal", values=arr[1]) data.transform("energy") # finish if verbose: print("data created at {0}".format(data.fullpath)) print(" range: {0} to {1} (nm)".format(data.energy[0], data.energy[-1])) print(" size: {0}".format(data.size)) return data
[ "def", "from_JASCO", "(", "filepath", ",", "name", "=", "None", ",", "parent", "=", "None", ",", "verbose", "=", "True", ")", "->", "Data", ":", "# parse filepath", "filestr", "=", "os", ".", "fspath", "(", "filepath", ")", "filepath", "=", "pathlib", ...
Create a data object from JASCO UV-Vis spectrometers. Parameters ---------- filepath : path-like Path to .txt file. Can be either a local or remote file (http/ftp). Can be compressed with gz/bz2, decompression based on file name. name : string (optional) Name to give to the created data object. If None, filename is used. Default is None. parent : WrightTools.Collection (optional) Collection to place new data object within. Default is None. verbose : boolean (optional) Toggle talkback. Default is True. Returns ------- data New data object(s).
[ "Create", "a", "data", "object", "from", "JASCO", "UV", "-", "Vis", "spectrometers", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/data/_jasco.py#L25-L77
train
33,696
wright-group/WrightTools
WrightTools/artists/_colors.py
make_cubehelix
def make_cubehelix(name="WrightTools", gamma=0.5, s=0.25, r=-1, h=1.3, reverse=False, darkest=0.7): """Define cubehelix type colorbars. Look `here`__ for more information. __ http://arxiv.org/abs/1108.5083 Parameters ---------- name : string (optional) Name of new cmap. Default is WrightTools. gamma : number (optional) Intensity factor. Default is 0.5 s : number (optional) Start color factor. Default is 0.25 r : number (optional) Number and direction of rotations. Default is -1 h : number (option) Hue factor. Default is 1.3 reverse : boolean (optional) Toggle reversal of output colormap. By default (Reverse = False), colormap goes from light to dark. darkest : number (optional) Default is 0.7 Returns ------- matplotlib.colors.LinearSegmentedColormap See Also -------- plot_colormap_components Displays RGB components of colormaps. """ rr = .213 / .30 rg = .715 / .99 rb = .072 / .11 def get_color_function(p0, p1): def color(x): # Calculate amplitude and angle of deviation from the black to # white diagonal in the plane of constant perceived intensity. xg = darkest * x ** gamma lum = 1 - xg # starts at 1 if reverse: lum = lum[::-1] a = lum.copy() a[lum < 0.5] = h * lum[lum < 0.5] / 2. a[lum >= 0.5] = h * (1 - lum[lum >= 0.5]) / 2. phi = 2 * np.pi * (s / 3 + r * x) out = lum + a * (p0 * np.cos(phi) + p1 * np.sin(phi)) return out return color rgb_dict = { "red": get_color_function(-0.14861 * rr, 1.78277 * rr), "green": get_color_function(-0.29227 * rg, -0.90649 * rg), "blue": get_color_function(1.97294 * rb, 0.0), } cmap = matplotlib.colors.LinearSegmentedColormap(name, rgb_dict) return cmap
python
def make_cubehelix(name="WrightTools", gamma=0.5, s=0.25, r=-1, h=1.3, reverse=False, darkest=0.7): """Define cubehelix type colorbars. Look `here`__ for more information. __ http://arxiv.org/abs/1108.5083 Parameters ---------- name : string (optional) Name of new cmap. Default is WrightTools. gamma : number (optional) Intensity factor. Default is 0.5 s : number (optional) Start color factor. Default is 0.25 r : number (optional) Number and direction of rotations. Default is -1 h : number (option) Hue factor. Default is 1.3 reverse : boolean (optional) Toggle reversal of output colormap. By default (Reverse = False), colormap goes from light to dark. darkest : number (optional) Default is 0.7 Returns ------- matplotlib.colors.LinearSegmentedColormap See Also -------- plot_colormap_components Displays RGB components of colormaps. """ rr = .213 / .30 rg = .715 / .99 rb = .072 / .11 def get_color_function(p0, p1): def color(x): # Calculate amplitude and angle of deviation from the black to # white diagonal in the plane of constant perceived intensity. xg = darkest * x ** gamma lum = 1 - xg # starts at 1 if reverse: lum = lum[::-1] a = lum.copy() a[lum < 0.5] = h * lum[lum < 0.5] / 2. a[lum >= 0.5] = h * (1 - lum[lum >= 0.5]) / 2. phi = 2 * np.pi * (s / 3 + r * x) out = lum + a * (p0 * np.cos(phi) + p1 * np.sin(phi)) return out return color rgb_dict = { "red": get_color_function(-0.14861 * rr, 1.78277 * rr), "green": get_color_function(-0.29227 * rg, -0.90649 * rg), "blue": get_color_function(1.97294 * rb, 0.0), } cmap = matplotlib.colors.LinearSegmentedColormap(name, rgb_dict) return cmap
[ "def", "make_cubehelix", "(", "name", "=", "\"WrightTools\"", ",", "gamma", "=", "0.5", ",", "s", "=", "0.25", ",", "r", "=", "-", "1", ",", "h", "=", "1.3", ",", "reverse", "=", "False", ",", "darkest", "=", "0.7", ")", ":", "rr", "=", ".213", ...
Define cubehelix type colorbars. Look `here`__ for more information. __ http://arxiv.org/abs/1108.5083 Parameters ---------- name : string (optional) Name of new cmap. Default is WrightTools. gamma : number (optional) Intensity factor. Default is 0.5 s : number (optional) Start color factor. Default is 0.25 r : number (optional) Number and direction of rotations. Default is -1 h : number (option) Hue factor. Default is 1.3 reverse : boolean (optional) Toggle reversal of output colormap. By default (Reverse = False), colormap goes from light to dark. darkest : number (optional) Default is 0.7 Returns ------- matplotlib.colors.LinearSegmentedColormap See Also -------- plot_colormap_components Displays RGB components of colormaps.
[ "Define", "cubehelix", "type", "colorbars", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_colors.py#L32-L94
train
33,697
wright-group/WrightTools
WrightTools/artists/_colors.py
make_colormap
def make_colormap(seq, name="CustomMap", plot=False): """Generate a LinearSegmentedColormap. Parameters ---------- seq : list of tuples A sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). name : string (optional) A name for the colormap plot : boolean (optional) Use to generate a plot of the colormap (Default is False). Returns ------- matplotlib.colors.LinearSegmentedColormap `Source`__ __ http://nbviewer.ipython.org/gist/anonymous/a4fa0adb08f9e9ea4f94 """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {"red": [], "green": [], "blue": []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict["red"].append([item, r1, r2]) cdict["green"].append([item, g1, g2]) cdict["blue"].append([item, b1, b2]) cmap = mplcolors.LinearSegmentedColormap(name, cdict) if plot: plot_colormap_components(cmap) return cmap
python
def make_colormap(seq, name="CustomMap", plot=False): """Generate a LinearSegmentedColormap. Parameters ---------- seq : list of tuples A sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). name : string (optional) A name for the colormap plot : boolean (optional) Use to generate a plot of the colormap (Default is False). Returns ------- matplotlib.colors.LinearSegmentedColormap `Source`__ __ http://nbviewer.ipython.org/gist/anonymous/a4fa0adb08f9e9ea4f94 """ seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3] cdict = {"red": [], "green": [], "blue": []} for i, item in enumerate(seq): if isinstance(item, float): r1, g1, b1 = seq[i - 1] r2, g2, b2 = seq[i + 1] cdict["red"].append([item, r1, r2]) cdict["green"].append([item, g1, g2]) cdict["blue"].append([item, b1, b2]) cmap = mplcolors.LinearSegmentedColormap(name, cdict) if plot: plot_colormap_components(cmap) return cmap
[ "def", "make_colormap", "(", "seq", ",", "name", "=", "\"CustomMap\"", ",", "plot", "=", "False", ")", ":", "seq", "=", "[", "(", "None", ",", ")", "*", "3", ",", "0.0", "]", "+", "list", "(", "seq", ")", "+", "[", "1.0", ",", "(", "None", ",...
Generate a LinearSegmentedColormap. Parameters ---------- seq : list of tuples A sequence of floats and RGB-tuples. The floats should be increasing and in the interval (0,1). name : string (optional) A name for the colormap plot : boolean (optional) Use to generate a plot of the colormap (Default is False). Returns ------- matplotlib.colors.LinearSegmentedColormap `Source`__ __ http://nbviewer.ipython.org/gist/anonymous/a4fa0adb08f9e9ea4f94
[ "Generate", "a", "LinearSegmentedColormap", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_colors.py#L97-L131
train
33,698
wright-group/WrightTools
WrightTools/artists/_colors.py
plot_colormap_components
def plot_colormap_components(cmap): """Plot the components of a given colormap.""" from ._helpers import set_ax_labels # recursive import protection plt.figure(figsize=[8, 4]) gs = grd.GridSpec(3, 1, height_ratios=[1, 10, 1], hspace=0.05) # colorbar ax = plt.subplot(gs[0]) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.) ax.set_title(cmap.name, fontsize=20) ax.set_axis_off() # components ax = plt.subplot(gs[1]) x = np.arange(cmap.N) colors = cmap(x) r = colors[:, 0] g = colors[:, 1] b = colors[:, 2] RGB_weight = [0.299, 0.587, 0.114] k = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight)) r.clip(0, 1, out=r) g.clip(0, 1, out=g) b.clip(0, 1, out=b) xi = np.linspace(0, 1, x.size) plt.plot(xi, r, "r", linewidth=5, alpha=0.6) plt.plot(xi, g, "g", linewidth=5, alpha=0.6) plt.plot(xi, b, "b", linewidth=5, alpha=0.6) plt.plot(xi, k, "k", linewidth=5, alpha=0.6) ax.set_xlim(0, 1) ax.set_ylim(-0.1, 1.1) set_ax_labels(ax=ax, xlabel=None, xticks=False, ylabel="intensity") # grayified colorbar cmap = grayify_cmap(cmap) ax = plt.subplot(gs[2]) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.) ax.set_axis_off()
python
def plot_colormap_components(cmap): """Plot the components of a given colormap.""" from ._helpers import set_ax_labels # recursive import protection plt.figure(figsize=[8, 4]) gs = grd.GridSpec(3, 1, height_ratios=[1, 10, 1], hspace=0.05) # colorbar ax = plt.subplot(gs[0]) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.) ax.set_title(cmap.name, fontsize=20) ax.set_axis_off() # components ax = plt.subplot(gs[1]) x = np.arange(cmap.N) colors = cmap(x) r = colors[:, 0] g = colors[:, 1] b = colors[:, 2] RGB_weight = [0.299, 0.587, 0.114] k = np.sqrt(np.dot(colors[:, :3] ** 2, RGB_weight)) r.clip(0, 1, out=r) g.clip(0, 1, out=g) b.clip(0, 1, out=b) xi = np.linspace(0, 1, x.size) plt.plot(xi, r, "r", linewidth=5, alpha=0.6) plt.plot(xi, g, "g", linewidth=5, alpha=0.6) plt.plot(xi, b, "b", linewidth=5, alpha=0.6) plt.plot(xi, k, "k", linewidth=5, alpha=0.6) ax.set_xlim(0, 1) ax.set_ylim(-0.1, 1.1) set_ax_labels(ax=ax, xlabel=None, xticks=False, ylabel="intensity") # grayified colorbar cmap = grayify_cmap(cmap) ax = plt.subplot(gs[2]) gradient = np.linspace(0, 1, 256) gradient = np.vstack((gradient, gradient)) ax.imshow(gradient, aspect="auto", cmap=cmap, vmin=0., vmax=1.) ax.set_axis_off()
[ "def", "plot_colormap_components", "(", "cmap", ")", ":", "from", ".", "_helpers", "import", "set_ax_labels", "# recursive import protection", "plt", ".", "figure", "(", "figsize", "=", "[", "8", ",", "4", "]", ")", "gs", "=", "grd", ".", "GridSpec", "(", ...
Plot the components of a given colormap.
[ "Plot", "the", "components", "of", "a", "given", "colormap", "." ]
80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb
https://github.com/wright-group/WrightTools/blob/80d3ddd5074d8d5c1bc03fd5a0e0f10d4b424aeb/WrightTools/artists/_colors.py#L194-L233
train
33,699