Ejemplo n.º 1
0
def test_resize_antialiasing():
    """
    Test that the Resize processor antialiases.

    The Resize processor is used by all of the Resize* variants, so this should
    cover all of resize processors. Basically, this is to test that it converts
    to RGBA mode before resizing.

    Related: jdriscoll/django-imagekit#192

    """
    # Create a palette image and draw a circle into it.
    img = Image.new('P', (500, 500), 1)
    img.putpalette([
        0,
        0,
        0,
        255,
        255,
        255,
        0,
        0,
        255,
    ])
    d = ImageDraw.ImageDraw(img)
    d.ellipse((100, 100, 400, 400), fill=2)

    # Resize the image using the Resize processor
    img = Resize(100, 100).process(img)

    # Count the number of colors
    color_count = len(list(filter(None, img.histogram())))

    assert_true(color_count > 2)
Ejemplo n.º 2
0
def test_resize_antialiasing():
    """
    Test that the Resize processor antialiases.

    The Resize processor is used by all of the Resize* variants, so this should
    cover all of resize processors. Basically, this is to test that it converts
    to RGBA mode before resizing.

    Related: jdriscoll/django-imagekit#192

    """
    # Create a palette image and draw a circle into it.
    img = Image.new('P', (500, 500), 1)
    img.putpalette([
        0,   0,   0,
        255, 255, 255,
        0,   0,   255,
    ])
    d = ImageDraw.ImageDraw(img)
    d.ellipse((100, 100, 400, 400), fill=2)

    # Resize the image using the Resize processor
    img = Resize(100, 100).process(img)

    # Count the number of colors
    color_count = len(list(filter(None, img.histogram())))

    assert_true(color_count > 2)
Ejemplo n.º 3
0
	def process(self, img):
		original_width, original_height = img.size
		ratio = min(float(self.width) / original_width,
					float(self.height) / original_height)
		new_width, new_height = (int(round(original_width * ratio)),
					int(round(original_height * ratio)))
		img = Resize(new_width, new_height, upscale=self.upscale).process(img)
		return img
Ejemplo n.º 4
0
class Contract(models.Model):  # Known contract addresses by the service
    objects = ContractManager.from_queryset(ContractQuerySet)()
    address = EthereumAddressV2Field(primary_key=True)
    name = models.CharField(max_length=200, blank=True, default="")
    display_name = models.CharField(max_length=200, blank=True, default="")
    logo = ProcessedImageField(
        blank=True,
        default="",
        upload_to=get_contract_logo_path,
        storage=get_file_storage,
        format="PNG",
        processors=[Resize(256, 256, upscale=False)],
    )
    contract_abi = models.ForeignKey(
        ContractAbi,
        on_delete=models.SET_NULL,
        null=True,
        default=None,
        blank=True,
        related_name="contracts",
    )
    # Trusted for doing delegate calls, as it's very dangerous doing delegate calls to other contracts
    trusted_for_delegate_call = models.BooleanField(default=False)

    def __str__(self):
        has_abi = self.contract_abi_id is not None
        logo = " with logo" if self.logo else " without logo"
        return f"Contract {self.address} - {self.name} - with abi {has_abi}{logo}"

    def sync_abi_from_api(self,
                          network: Optional[EthereumNetwork] = None) -> bool:
        """
        Sync ABI from Sourcify, then from Etherscan and blockscout if available
        :param network: Can be provided to save requests to the node
        :return: True if updated, False otherwise
        """
        ethereum_client = EthereumClientProvider()
        network = network or ethereum_client.get_network()
        sourcify = Sourcify(network)

        try:
            etherscan_client = EtherscanClient(
                network, api_key=settings.ETHERSCAN_API_KEY)
        except EtherscanClientConfigurationProblem:
            logger.info(
                "Etherscan client is not available for current network %s",
                network)
            etherscan_client = None

        try:
            blockscout_client = BlockscoutClient(network)
        except BlockScoutConfigurationProblem:
            logger.info(
                "Blockscout client is not available for current network %s",
                network)
            blockscout_client = None

        contract_abi: Optional[ContractAbi] = None
        for client in (sourcify, etherscan_client, blockscout_client):
            if not client:
                continue
            try:
                contract_metadata = client.get_contract_metadata(self.address)
                if contract_metadata:
                    name = contract_metadata.name or ""
                    contract_abi, _ = ContractAbi.objects.get_or_create(
                        abi=contract_metadata.abi,
                        defaults={"description": name})
                    if name:
                        if not contract_abi.description:
                            contract_abi.description = name
                            contract_abi.save(update_fields=["description"])
                        if not self.name:
                            self.name = name
                    self.contract_abi = contract_abi
                    self.save(update_fields=["name", "contract_abi"])
                    break
            except IOError:
                pass

        return bool(contract_abi)
Ejemplo n.º 5
0
class Token(models.Model):
    objects = TokenManager.from_queryset(TokenQuerySet)()
    pool_tokens = PoolTokenManager()
    address = EthereumAddressV2Field(primary_key=True)
    name = models.CharField(max_length=60)
    symbol = models.CharField(max_length=60)
    decimals = models.PositiveSmallIntegerField(
        db_index=True,
        null=True,
        blank=True,
        help_text=
        "Number of decimals. For ERC721 tokens decimals must be `None`",
    )
    logo = ProcessedImageField(
        blank=True,
        default="",
        upload_to=get_token_logo_path,
        storage=get_file_storage,
        format="PNG",
        processors=[Resize(256, 256, upscale=False)],
    )
    events_bugged = models.BooleanField(
        default=False,
        help_text=
        "Set `True` if token does not send `Transfer` event sometimes (e.g. WETH on minting)",
    )
    spam = models.BooleanField(
        default=False, help_text="Spam and trusted cannot be both True")
    trusted = models.BooleanField(
        default=False, help_text="Spam and trusted cannot be both True")
    copy_price = EthereumAddressV2Field(
        null=True,
        blank=True,
        help_text="If provided, copy the price from the token")

    class Meta:
        indexes = [
            models.Index(name="token_trusted_idx",
                         fields=["trusted"],
                         condition=Q(trusted=True)),
            models.Index(
                name="token_events_bugged_idx",
                fields=["events_bugged"],
                condition=Q(events_bugged=True),
            ),
        ]

    def __str__(self):
        spam_text = "SPAM " if self.spam else ""
        if self.decimals is None:
            return f"{spam_text}ERC721 - {self.name} - {self.address}"
        else:
            return f"{spam_text}ERC20 - {self.name} - {self.address}"

    def clean(self):
        if self.trusted and self.spam:
            raise ValidationError("Spam and trusted cannot be both `True`")

    def is_erc20(self):
        return self.decimals is not None

    def is_erc721(self):
        return not self.is_erc20()

    def set_trusted(self) -> None:
        self.trusted = True
        return self.save(update_fields=["trusted"])

    def set_spam(self) -> None:
        self.spam = True
        return self.save(update_fields=["spam"])

    def get_full_logo_uri(self) -> str:
        if self.logo:
            return self.logo.url
        elif settings.AWS_S3_PUBLIC_URL:
            return urljoin(
                settings.AWS_S3_PUBLIC_URL,
                get_token_logo_path(
                    self, self.address + settings.TOKENS_LOGO_EXTENSION),
            )
        else:
            # Old behaviour
            return urljoin(
                settings.TOKENS_LOGO_BASE_URI,
                get_token_logo_path(
                    self, self.address + settings.TOKENS_LOGO_EXTENSION),
            )

    def get_price_address(self) -> ChecksumAddress:
        """
        :return: Address to use to retrieve the token price
        """
        return self.copy_price or self.address
Ejemplo n.º 6
0
    def get(self, request, req_img_path):
        #TODO: catch type conversion errors
        print "Debug log: image render view"
        # store request data 
        req_img_w = int(request.GET.get('w', '-1'))
        req_img_h = int(request.GET.get('h', '-1'))
        req_img_priority = request.GET.get('priority', 'w')
        req_img_border_pc = request.GET.get('pad', None)
        print "Debug log: image size requested : %sx%s, Image Priority : %s,\
                Image border Color %s, req_img_path : %s" % \
                (req_img_w, req_img_h, req_img_priority, req_img_border_pc, req_img_path)

        #req_directory = os.path.join(settings.BASE_DIR, "static", "images")
        #req_img_name = os.path.basename(req_img_path)
        req_directory = os.path.join(settings.MEDIA_ROOT, os.path.dirname(req_img_path))
        req_img_name = os.path.basename(req_img_path)
        
        # create img path dict
        img_path_dict = create_img_paths(req_directory, req_img_name)
 
        #choose image file path
        resp_img_path = get_image_path(img_path_dict, req_img_priority)

        #pixel calculation
        img_path_dict['c_img'] = os.path.join(req_directory, 'resized', \
                   os.path.splitext(req_img_name)[0]+'_%sx%s' % (req_img_w, req_img_h)+ os.path.splitext(req_img_name)[1])
        if os.path.exists(img_path_dict['c_img']):
            resp_img_path = img_path_dict['c_img']
            resize_flag = False
        else:
            #resizing required
            im = Image.open(resp_img_path)
            w,h = im.size
            resize_flag, new_w, new_h = pixel_calculation(req_img_w, req_img_h, w, h, img_path_dict['c_img'])

        print "Debug Log : Response Image path: %s" % resp_img_path
        if resize_flag:
            print "Debug Log : Resizing required, new_w X new_h %sx%s" % (new_w, new_h)
            img = Image.open(resp_img_path)
            processor = Resize(new_w, new_h)
            m_img = processor.process(img)
            #update path to render
            resp_img_path = img_path_dict['c_img']

            if not os.path.exists(os.path.join(req_directory, "resized")):
                os.makedirs(os.path.join(req_directory, "resized"))
            if req_img_border_pc is not None:
                border_w = (req_img_w - new_w)/2
                border_h = (req_img_h - new_h)/2
                print "Debug Log: border_w X border_h %sx%s" % (border_w, border_h)
                ImageOps.expand(m_img, border=(border_w, border_h), fill=req_img_border_pc).save(resp_img_path, quality=95)
            else:
                m_img.save(resp_img_path, quality=95)

        relative_path = os.path.relpath(resp_img_path, settings.MEDIA_ROOT)
        #context_dict = {'relative_path':relative_path}
        #return render_to_response('images/image_render.html', context_dict, RequestContext(request))
        print "Debug Log: relative path: %s" % relative_path
        img = Image.open(resp_img_path)
        response = HttpResponse(content_type="image/jpeg")
        img.save(response, "jpeg")
        return response
Ejemplo n.º 7
0
class Tool(models.Model):
    class Meta:
        app_label = 'app'

    def toolPictureName(instance, filename):
        ext = filename.split('.')[-1]
        return 'toolpics/{}.{}'.format(instance.name, ext)

    name = models.CharField(max_length=25)
    picture = ProcessedImageField(processors=[Resize(500, 500)],
                                  format='JPEG',
                                  upload_to=toolPictureName)
    description = models.TextField(max_length=500)
    status = models.CharField(max_length=1, choices=app.constants.TOOL_STATUS)
    category = models.CharField(max_length=2,
                                choices=app.constants.TOOL_CATEGORY)
    location = models.CharField(max_length=1,
                                choices=app.constants.TOOL_LOCATION,
                                blank=False,
                                default='H')
    models.CharField()
    shed = models.ForeignKey(Shed, null=True, on_delete=models.SET_NULL)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    pickupArrangement = models.TextField(max_length=500)

    def __str__(self):
        return self.name

    def get_all_reservations(self):
        reservations = self.reservation_set.all()
        return reservations

    # returns a query of reservations on the tool based on the reservation_status arg (A, O, AC, R, C, etc.)
    def get_reservations(self, reservation_status):
        reservations = self.reservation_set.filter(status=reservation_status)
        return reservations

    # Checks if tool has unresolved future reservations that prevent it from moving
    # Returns true if no unresolved future reservations on it, false otherwise
    def is_ready_to_move(self):
        if self.location == "S":
            return False

        # Keeps a count of all reservations that might be interfering with moving a tool.
        blockingReservations = 0

        # Checks tool for any active reservations
        activeReservations = self.get_reservations('AC')
        blockingReservations = blockingReservations + len(activeReservations)

        # Checks tool for approved future reservations
        approvedReservations = self.get_reservations('A')
        blockingReservations = blockingReservations + len(approvedReservations)

        # Add additional reservations that might block tool from moving here
        user = self.owner
        ownReservations = app.models.Reservation.objects.filter(user=user)
        ownReservations = ownReservations.filter(status="AC").filter(
            status="A")
        blockingReservations = blockingReservations + len(ownReservations)

        # Check the sum of the lengths of the reservation lists described above.
        # If sum is zero (no blocking reservations), return ready_to_move = True. Else, return ready_to_move = False
        if blockingReservations == 0:
            return True
        else:
            return False

    def get_next_available_date(self):
        reservations = self.reservation_set.exclude(status='C').exclude(status='CL').exclude(status='O'). \
            exclude(status='P').exclude(status='R')
        blackoutdates = self.blackoutdate_set.all()
        availableDate = datetime.date.today()
        addOneDay = datetime.timedelta(days=1)
        setOfDates = set()

        for res in reservations:
            setOfDates = setOfDates.union(res.get_dates_covered())

        for bd in blackoutdates:
            setOfDates = setOfDates.union(bd.get_dates_covered())

        unavailableDates = sorted(setOfDates)

        for date in unavailableDates:
            while availableDate == date:
                availableDate = date + addOneDay

        return availableDate

    def get_days_until_available(self):
        today = datetime.date.today()
        delta = (self.get_next_available_date() - today).days
        return delta

    def get_status_label_owner(self):
        label = "Active"
        if self.status == "D":
            label = "Deactivated"
        else:
            reservations = self.get_all_reservations()
            for reservation in reservations:
                if reservation.status == "RI":
                    label = "Return Initiated"
                elif reservation.status == "O":
                    label = "Overdue"
                elif reservation.status == "AC":
                    label = "Lent Out"
        return label

    def get_label_type_owner(self):
        type = "label-success"
        if self.get_status_label_owner() == "Deactivated":
            type = "label-danger"
        if self.get_status_label_owner() == "Return Initiated":
            type = "label-warning"
        if self.get_status_label_owner() == "Overdue":
            type = "label-danger"
        if self.get_status_label_owner() == "Lent Out":
            type = "label-warning"
        return type

    def get_status_label_borrower(self):
        label = "Available"
        daysOnRes = self.get_days_until_available()
        if daysOnRes > 0:
            label = self.get_next_available_date()
        return label

    def get_label_type_borrower(self):
        type = "label-warning"
        if self.get_status_label_borrower() == "Available":
            type = "label-success"
        return type

    def get_init_return_reservation(self):
        reservations = self.get_reservations('RI')
        if len(reservations) > 0:
            return reservations[0]
        return reservations

    @property
    def address(self):
        if self.location == 'S':
            return self.shed.address
        return self.owner.address