예제 #1
0
    def execute(self, report, options):
        template_name = options.get('template_name')
        if not template_name:
            return
        base_query = Template.domain_query(report.reported_domain)
        template = Template.get_by_name(base_query, template_name)
        if not template:
            return

        subject = render_template_string(template.subject, report=report)
        body = render_template_string(template.text, report=report)

        response = EmailResponse(responder=ISTHISLEGIT_SVC,
                                 sender=template.sender,
                                 content=body,
                                 subject=subject)
        try:
            response_key = response.put()
            report.responses.append(response_key)
            if not report.date_responded:
                report.date_responded = datetime.now()

            event_key = EventReportResponded(response=response,
                                             report=report).put()
            report.events.append(event_key)
            report.put()

            email_provider.send(to=report.reported_by,
                                sender=response.sender,
                                subject=subject,
                                body=body)
        except Exception as e:
            return
예제 #2
0
    def on_using_template_button_clicked(self, *args, **kwargs):
        template_path, filter = QFileDialog.getOpenFileName(
            self, _("Select template file."), ".", "Template files (*.svg)")

        with open(template_path, 'rb') as template_file:
            template = Template()
            template.load_from_file(template_file=template_file)
            self.ui.preview_scene.template = template
            self.on_generate_button_clicked()
    def __init__(self, parent, *args, **kwargs):
        super(ComposerGraphicScene, self).__init__(parent, *args, **kwargs)

        self.__template = Template()
        self.__background_item = None

        self._rubber_band = None
        self._rubber_band_origin = QPoint(0, 0)

        self.__template_layer_item_map = {}
        self.__grid_items = []
예제 #4
0
    def create_template(self, name, filename, path, source):
        """ Creates a new template and writes it to
            appropriate location.

        Args:
            name (string): Name of the template
            filename (string): File name of the template
            path (string): Path of the template in file system
            source (string): Source code of the template

        Raises:
            InvalidValueError: Raised if name, file name or path is invalid
            FileExistsError: Raised if template with given name exists

        Returns:
            Template: created template
        """

        if not name:
            raise InvalidValueError('Invalid name')
        if not filename:
            raise InvalidValueError('Invalid filename')
        if not path:
            raise InvalidValueError('Invalid path')

        if template_store.exists(name):
            raise FileExistsError

        template = Template(name, filename, path)
        template_store.create(template, source)
        return template
예제 #5
0
    def test__model__template__create(self):
        actual_result = Template.create()

        self.assertRegex(actual_result.uuid,
                         r"[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}")
        mock.wrapper.session.add.assert_called_with(actual_result)
        mock.wrapper.session.commit.assert_called_with()
예제 #6
0
    def test_create_creates_file(self):
        template = Template('test_template', 'test_template.tex',
                            '~/.texviper/templates')
        template_store.create(template, '')

        self.assertTrue(
            Path('~/.texviper/templates/test_template.tex').expanduser().
            exists())
예제 #7
0
    def test_delete_removes_file(self):
        template = Template('test_template', 'test_template.tex',
                            '~/.texviper/templates')
        template_store.create(template, '')

        template_store.delete_one(template.template_id)
        self.assertFalse(
            file_system.file_exists(
                Path('~/.texviper/templates/test_template.tex').expanduser()))
예제 #8
0
    def find_one(self, conditions):
        query = f'''
            select * from Templates
            where {conditions}
        '''

        database.execute(query)
        template = database.fetch_one()
        return Template(template[1], template[2], template[3], template[0])
예제 #9
0
    def test__model__template__serialize(self):
        wallet = Template(uuid="some-uuid")

        expected_result = {"uuid": "some-uuid"}
        serialized = wallet.serialize

        self.assertEqual(expected_result, serialized)

        serialized["uuid"] = "other-uuid"
        self.assertEqual(expected_result, wallet.serialize)
예제 #10
0
    def test_create_inserts_to_database(self):
        template = Template('test_template', 'test_template.tex',
                            '~/.texviper/templates')
        template_store.create(template, '')

        database.execute(
            '''select * from Templates where name="test_template"''')
        result = database.fetch_one()

        self.assertEqual(len(result), 4)
예제 #11
0
def template(template_id):
    """
    Returns an existing template
    
    Args:
        template_id - int - The ID of the Template
    """
    template = Template.get_by_id(template_id)
    if not template or template.owner_domain != g.domain:
        return json_error(404, 'Template not found', {})
    return jsonify(template.to_dict())
예제 #12
0
def delete_template(template_id):
    '''
    Deletes and existing template

    Args:
        template_id - int - the ID of the Template
    '''
    template = Template.get_by_id(template_id)
    if not template or template.owner_domain != g.domain:
        return json_error(404, 'Template not found', {})
    template.key.delete()
    return jsonify({'success': True, 'error': None, 'data': {}})
예제 #13
0
    def validate(self):
        """ Validate the form """
        data_validation = super(TemplateForm, self).validate()
        if not data_validation:
            return False
        template = Template.query(Template.name == self.name.data,
                                  Template.owner_domain == self.domain).get()

        if template and (not self.template_id or
                         template.key.id() != self.template_id):
            self.name.errors.append('already in use')
            return False
        return True
예제 #14
0
    def find_all(self):
        """ Returns all templates

            Returns:
                templates: List of existing templates
        """

        query = '''
            select * from Templates
        '''

        database.execute(query)
        templates = database.fetch_all()

        return list(map(lambda t: Template(t[1], t[2], t[3], t[0]),
                        templates)) if templates else []
예제 #15
0
def template_add():
    form = TemplateForm()
    if form.validate_on_submit():
        data = form.data

        # 保存数据
        temp = Template(
            title=data['title'],
            saveName=data['saveName'],
            toPath=data['toPath'],
            content=data['content'],
            addtime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        db.session.add(temp)
        db.session.commit()
        flash(u'提交成功', 'ok')
        # form..data = ""
    return render_template('template_add.html', title=u"增加模版", form=form)
예제 #16
0
def get_templates():  # noqa: E501
    """
  Get the templates for Sample metadata and Data files
  # noqa: E501
  :rtype: List[Template]
  """

    relevant_path = str(
        pathlib.Path(__file__).parent) + "/" + "../resources/templates/"
    included_extensions = ['yaml']
    file_names = [
        fn for fn in os.listdir(relevant_path) if any(
            fn.endswith(ext) for ext in included_extensions)
    ]
    templates = []
    for file_name in file_names:
        with open(relevant_path + os.sep + file_name) as file:
            # The FullLoader parameter handles the conversion from YAML
            # scalar values to Python the dictionary format
            yaml_file = yaml.load(file, Loader=yaml.FullLoader)
            columns = []
            for yaml_column in yaml_file['template']['columns']:
                name = yaml_column
                ontology = yaml_file['template']['columns'][yaml_column]
                type = ontology['type']
                ontology_term = None
                if 'ontology_accession' in ontology:
                    accession = ontology['ontology_accession']
                    cv = ontology['ontology']
                    ontology_term = OntologyTerm(id=accession,
                                                 name=name,
                                                 ontology=cv,
                                                 iri_id=ontology['ols_uri'])
                column = TemplateColumn(name=name,
                                        type_node=type,
                                        ontology_term=ontology_term,
                                        searchable=ontology['searchable'])
                columns.append(column)
            template = Template(yaml_file['template']['name'],
                                yaml_file['template']['type'],
                                yaml_file['template']['description'], columns)
            templates.append(template)
    return templates
예제 #17
0
def insertTemplate(_name, _value, _allocation, _manager, _service,
                   _allocation_value, _nbs, _contract, _average, _user,
                   _provider, _branch):
    name = (_allocation.get())
    value = (_value.get())
    allocation = (_allocation.get())
    manager = (_manager.get())
    service = (_service.get())
    allocation_value = (_allocation_value.get())
    nbs = (_nbs.get())
    contract = (_contract.get())
    average = (_average.get())
    user = (_user.get())
    provider = (_provider.get())
    branch = (_branch.get())
    template = Template(0, name, value, allocation, manager, service,
                        allocation_value, nbs, contract, average, user,
                        provider, branch)
    t.insertTemplate(template)
    print("Template {}, cadastrado com sucesso!".format(template.name))
예제 #18
0
def get_templates(**kwargs):
    """ Gets the list of templates that are accessible to our current user. """
    templates = Template.domain_query(kwargs.get('domain')).fetch()
    return [template.name for template in templates]
예제 #19
0
 def test__model__template__create__different_uuid(self):
     first_element = Template.create().uuid
     second_element = Template.create().uuid
     self.assertNotEqual(first_element, second_element)
class ComposerGraphicScene(QGraphicsScene):
    item_moved = pyqtSignal(float, float)

    def __init__(self, parent, *args, **kwargs):
        super(ComposerGraphicScene, self).__init__(parent, *args, **kwargs)

        self.__template = Template()
        self.__background_item = None

        self._rubber_band = None
        self._rubber_band_origin = QPoint(0, 0)

        self.__template_layer_item_map = {}
        self.__grid_items = []

    @property
    def template(self):
        return self.__template

    @template.setter
    def template(self, value):
        self.__template = value

    def dragEnterEvent(self, ev):
        if ev.mimeData().hasImage():
            ev.accept()

    def dropEvent(self, ev):

        item = None
        origin = None
        path = None

        self.clearSelection()

        if ev.mimeData().hasText():
            text = ev.mimeData().text()

            origin, path = text.split(',')
            path = Path(path)

        if ev.mimeData().hasImage():
            pixmap = ev.mimeData().imageData()

            # If origin != BACKGROUND, we scale item to fit.
            parent = self.__background_item if origin != BACKGROUND else None
            item = CustomPixmapItem(pixmap, parent=parent)

            item.setFlags(QGraphicsPixmapItem.ItemIsMovable |
                          QGraphicsPixmapItem.ItemIsSelectable |
                          QGraphicsPixmapItem.ItemSendsGeometryChanges)

            if origin == BACKGROUND:
                item.setZValue(-1)

            if origin != BACKGROUND:
                # Scale to fit the scene.
                scene_rect = self.sceneRect()
                item_rect = item.boundingRect()

                scene_width = scene_rect.width()
                scene_height = scene_rect.height()

                item_width = item_rect.width()
                item_height = item_rect.height()

                if scene_width >= scene_height:
                    factor = scene_height / (2 * item_height)
                else:
                    factor = scene_width / (2 * item_width)

                item.setScale(factor)

                dx = item.boundingRect().width() * factor / 2
                dy = item.boundingRect().height() * factor / 2

                scene_pos = ev.scenePos()

                item.setPos(QPointF(abs(scene_pos.x() - dx), abs(scene_pos.y() - dy)))
            else:
                # Modify the background aspect ratio in order to match the aspect ratio for
                # the desired size.
                desired_size_width = settings.adaptive_resize_width
                desired_size_height = settings.adaptive_resize_height

                if not (desired_size_height == 0 or desired_size_width == 0):
                    ratio = desired_size_width / desired_size_height

                    with Image(filename=str(path)) as original_background:
                        r = Rectangle(original_background.width, original_background.height)
                        r_resize = min_resize(r, ratio)
                        original_background.liquid_rescale(int(r_resize.width), int(r_resize.height))

                        root_dir = Path(settings.output_path)
                        backgrounds_dir = root_dir.joinpath(BACKGROUND)
                        backgrounds_dir.mkdir(exist_ok=True)

                        name = path.name.replace(path.suffix, f".fixed{ path.suffix}")

                        path = backgrounds_dir.joinpath(name)

                        original_background.save(filename=str(path))

            self.addItem(item)

            if origin == BACKGROUND:
                self.__background_item = item
                self.setSceneRect(item.boundingRect())

            self.parent().fitInView(self.sceneRect(), Qt.KeepAspectRatio)

            if origin == BACKGROUND:
                # We need to show the grid AFTER the background has been scaled to
                # fit the scene.
                self.show_grid()

        self.process_dropped_data(item, origin=origin, path=path)

    def dragMoveEvent(self, ev):
        ev.accept()

    def on_item_position_change(self, item, change, value):
        self.__template.update_layer(item)
        self.item_moved.emit(value.x(), value.y())

    def on_item_scale_changed(self, item: CustomPixmapItem, change, value):
        self.__template.update_layer(item)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Delete:
            items = self.selectedItems()
            for item in items:
                if self.__background_item == item:
                    self.__template.remove_background()
                    self.__background_item = None
                    self.remove_grid()
                else:
                    self.__template.remove_layer_for_item(item)
                self.removeItem(item)
        return super(ComposerGraphicScene, self).keyPressEvent(event)

    def process_dropped_data(self, item, origin: str, path: Path):
        """
        Create the new layers according the given item, this layers are mapped then to the item
        in order to update if necessary when rendering the whole svg.

        :param path: path to the real image being processed.
        :param origin: String containing the origin of the item, one of
                        "BACKGROUND", "PRESENTATION", "PRIMARY", "SECONDARY"
        :param item:  A QGraphicsItem.
        """

        layer_type_origin_map = {
            PRESENTATION: LayerType.PRESENTATION,
            PRIMARY: LayerType.PRIMARY,
            SECONDARY: LayerType.SECONDARY
        }

        bounding_rect = item.boundingRect()

        pos = Position(item.x() * SVG_SCALE_FACTOR, item.y() * SVG_SCALE_FACTOR, item.zValue())

        size = Size(bounding_rect.width() * SVG_SCALE_FACTOR, bounding_rect.height() * SVG_SCALE_FACTOR)

        if origin == BACKGROUND:
            self.__template.set_background(str(path), size=size)
        else:
            try:
                layer = self.__template.add_layer(pos=pos, size=size, _type=layer_type_origin_map[origin])
            except NoBaseSvgError as err:
                self.removeItem(item)
                error_dialog = QErrorMessage(self.parent())
                error_dialog.showMessage(str(err))
            else:
                self.__template.map_layer_with_item(layer, graphic_item=item)

    def render_template(self) -> Path:
        return self.__template.render()

    def set_output_dir(self, path: str):
        self.__template.output_dir = path

    def show_grid(self) -> None:

        w = int(self.width())
        h = int(self.height())

        w_step = int(w / 3)
        h_step = int(h / 3)

        # Add vertical lines
        for x in range(0, w, w_step):
            line = self.addLine(x, 0, x, h)
            self.__grid_items.append(line)

        # Add horizontal lines.
        for y in range(0, h, h_step):
            line = self.addLine(0, y, w, y)
            self.__grid_items.append(line)

    def remove_grid(self):
        for item in self.__grid_items:
            self.removeItem(item)

        del self.__grid_items
        self.__grid_items = []
예제 #21
0
 def Template(self):
     return Template(self)