投稿時間:2023-02-25 05:24:15 RSSフィード2023-02-25 05:00 分まとめ(31件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
AWS AWS - Webinar Channel Amazon S3: Data Encryption Options https://www.youtube.com/watch?v=U1USUvvhuCY Amazon S Data Encryption OptionsAmazon S automatically encrypts all object uploads to all buckets For object uploads Amazon S supports server side encryption with three key management options SSE KMS SSE C and SSE S the base level of encryption as well as client side encryption Amazon S offers flexible security features to block unauthorized users from accessing your data Learn about how S can help you protect your data from theft errors and failures To learn more about the services featured in this talk please visit 2023-02-24 19:20:43
python Pythonタグが付けられた新着投稿 - Qiita julia+pyenv+poetry環境の構築 https://qiita.com/nyakiri_0726/items/cd3f3d23e1a46ce4223b julia 2023-02-25 04:53:09
Docker dockerタグが付けられた新着投稿 - Qiita julia+pyenv+poetry環境の構築 https://qiita.com/nyakiri_0726/items/cd3f3d23e1a46ce4223b julia 2023-02-25 04:53:09
Azure Azureタグが付けられた新着投稿 - Qiita JavaのサンプルアプリケーションをACI(Azure Container Instances)にデプロイしてみる https://qiita.com/aktsmm/items/04eca0a2296418247c9b azure 2023-02-25 04:08:48
海外TECH Ars Technica Unexpected protein interactions needed to build flowers https://arstechnica.com/?p=1919874 flowersa 2023-02-24 19:22:59
海外TECH Ars Technica An EV charger every 50 miles: Here’s the plan to keep them running https://arstechnica.com/?p=1919952 biden 2023-02-24 19:12:52
海外TECH MakeUseOf How to Participate in Xbox Research and Get Early Access to Games and Features on Xbox Series X|S https://www.makeuseof.com/how-to-participate-in-xbox-research-for-xbox-series-xs/ How to Participate in Xbox Research and Get Early Access to Games and Features on Xbox Series X SWant to try out new Xbox games and features before they re officially released Then check out Xbox Researchーhere s how you can participate 2023-02-24 19:31:16
海外TECH MakeUseOf Is the Intel Unison App Not Working on Windows 11? Here's How to Fix It https://www.makeuseof.com/intel-unison-app-not-working-windows-11/ windows 2023-02-24 19:15:16
海外TECH DEV Community What was your win this week? https://dev.to/michaeltharrington/what-was-your-win-this-week-mo6 What was your win this week What s up folks Hope everyone enjoys their weekends Looking back on this past week what was something you were proud of accomplishing All wins count ーbig or small Examples of wins include Starting a new projectFixing a tricky bugGrokking spaghetti code while eating spaghetti pasta 2023-02-24 19:44:00
海外TECH DEV Community Create Robust Access Control in Your Flask Application using Flask-login & Permify https://dev.to/bovage/create-robust-access-control-in-your-flask-application-using-flask-login-permify-2jea Create Robust Access Control in Your Flask Application using Flask login amp Permify IntroductionAccess control is a popular mechanism used to protect and restrict access to resources and data in applications networks or organizations As a result it s a really important concept in application security and privacy Having been aware of the main purpose of access control it is important to note that access control cannot be implemented without authentication and authorization In other words if resources and data need to be protected a way must be devised in order to identify who is going to access the data or resources i e Authentication Also if certain resources and data need to be accessed by a certain person a mechanism must be devised to permit certain users i e authorization There are different models of access control Role Based Access Control short for RBAC Relational Based Access Control short for ReBAC Attribute Based Access Control short for ABAC In this article we are going to focus on implementing RBAC using Flask Login amp Permify in a Blog Application By the end of this article you would have completed the following Create a Flask ServerHandle Authentication with Flask loginBuild Authorization model with PermifySet up Permify and connect it to a Flask appBuild blog endpointsAdd dummy organizations amp resources and store them in Flask appTest the endpoints with the dummy resources out Overview of the Blog ApplicationBefore we dive into building the blog application with Flask let s first analyze the blog application requirements and see how the RBAC model can be applied The Blog Application is a simple application where users can create posts The users of this blog application will be grouped into three based on common responsibilities The purpose of having three different types of users is so that the actions different users can perform can be managed appropriately i e roles As you would see in the description for the user type below Member Member of an organization which can have multiple blog posts inside it Administrator Administrator in an organization can view edit and delete the posts This is the superior user type Blog Owner The owner of the blog posts can also edit and delete the blog post The users type listed above can likened to be the roles while the permissions assigned to the roles are defined in the description of each user type In other words there are three roles in the blog application Building the Blog ApplicationNote The source code for this project is available on GitHub Prerequisites In order to follow along with building the Blog Application you need to have the following Python installed Basic Knowledge of Flask Docker installed API Design Platform Postman will be used in this guide Let s start to build the Blog Application using Flask and the authorization model using Permify Step Create the Flask serverCreate a virtual environment and install these packages Flask Flask login flask sqlalchemy python dotenv requests Create a env file and store a secret key as an environment variable Create a folder named src and then create init py and blog py files in it Copy the following codes into the init pyfrom flask import Flaskfrom flask sqlalchemy import SQLAlchemyimport osfrom dotenv import load dotenvfrom blog import blogload dotenv db SQLAlchemy def create app app Flask name app config SECRET KEY os getenv SECRET KEY app config SQLALCHEMY DATABASE URI sqlite db sqlite db init app app create database app app register blueprint blog url prefix return appdef create database app if not os path exists instance db sqlite with app app context db create all print Database created Copy the following codes into the blog py from flask import Blueprint jsonifyblog Blueprint views name blog get def status return jsonify status Up and running Create a new file named app py in the project root directory note inside src folder and copy the following codes into it from src import create appif name main app create app app run Run python app py command in the root directory to start the server and send a get request to to see the status response Now that you ve created the Flask server let s proceed to set up the authentication Step Handle Authentication with Flask LoginWe will create a simple login amp register endpoint Create a models py file in the src folder and copy the following codes into it from import dbfrom flask login import UserMixinfrom sqlalchemy sql import funcclass Organization db Model id db Column db Integer primary key True name db Column db String unique True nullable False creator id db Column db Integer db ForeignKey user id ondelete CASCADE nullable True class User db Model UserMixin id db Column db Integer primary key True email db Column db String unique True nullable False username db Column db String unique True password db Column db String organization id db Column db Integer db ForeignKey organization id ondelete CASCADE nullable True created organizations db relationship Organization backref admin primaryjoin User id Organization creator id organization db relationship Organization backref members foreign keys organization id Create auth py file in src folder and copy the following code into it from flask import Blueprint request jsonifyfrom flask login import login user login required current userfrom werkzeug security import generate password hash check password hashfrom models import User Organizationfrom sqlalchemy exc import IntegrityErrorfrom import dbfrom import permifyauth Blueprint auth name auth post login def login data request json email data get email password data get password user User query filter by email email first if user if check password hash user password password login user user remember True return jsonify status SUCCESS message User logged in successfully else return jsonify status error message Incorrect password else return jsonify status error message User does not exist auth get me def me if current user is authenticated return jsonify status SUCCESS message User logged in successfully data username current user username else return jsonify status ERROR message Not authenticated auth post register def register data request json username data get username email data get email password data get password password data get password if password password return jsonify status error message Password does not match else user User email email username username password generate password hash password sha try db session add user db session commit except IntegrityError as e print f An Error occurred e else login user user remember True return jsonify status SUCCESS message User logged in successfully Configuring Flask Login to handle AuthenticationBefore the login and register endpoint could work without throwing an error you need to configure flask login by setting the flask app s secret key and configuring the login manager Update the init py file in src folder with the code belowfrom flask login import LoginManagerdef create app some omitted code app config SECRET KEY os getenv SECRET KEY some omitted code login manager LoginManager handles session for users login manager login view auth login login manager init app app login manager user loader def load user id with app app context return User query get int id app register blueprint blog url prefix app register blueprint auth url prefix auth return app Step Build Authorization Model with PermifyWe will use Permify schema to model our authorization logic It will be used to define entities relations between them and access control decisions We will be making use of the permify playground to build the authorization model As it offers more flexibility and convenience Note Authorization model can be created outside of the permify playground As a matter of fact it can be created in any IDE or text editor such as VS Code It s important to mention that you will realize the benefit of creating the model in the playground in a bit There are only three entities in our blog application which are UserOrganizationPostThe very first step to building Permify Schema is creating Entities An entity is an object that defines your resources that hold the role in your permission system Think of entities as tables in relational databases or as collections in non relational databases Note It s advisable to name entities the same as your database table name that it corresponds to In that way you can easily model and reason your authorization as well as to eliminate the possibility of creating errors You can create entities using the entity keyword entity user entity organization relation admin user relation member user action create post admin or member action delete admin entity post relation author user relation organization organization action edit author or organization admin action delete author or organization admin You can copy the above schema snippet into your playground What does the above code snippet do We created three different entities using the entity keywordAn Entity has different attributes which are Relations and Actions We made use of the relation keyword to create relationships between the previously created entities We also made use of the action keyword to describe what relations or relation s relations can do Let s take a look at some of the actions For organization action create post admin or member indicates that only the admin or member has permission to create posts in the organization action delete admin indicates that only the admin can delete the organization For post action edit author or organization admin indicates that only the author or organization admin has permission to edit posts action delete author or organization admin indicates that only the author or organization admin can delete posts Now that we have the authorization model setup with Permify Schema let s start Permify locally and connect the flask app to it Step Set Up Permify and connect with the Flask appThere are several options to set up Permify service However in this article I ll use the docker option by running it via docker container Start Permify service by simply running the docker command below in your terminal or CLI docker run p p ghcr io permify permify serveThe above command will download the permify image if you don t have it locally i e if you haven t used permify before Once it s downloaded it will be served at the two ports specified in the command If the command runs successfully you should get a message similar to the one in the image below Note If you have docker desktop installed you can open it and find the running container and click on the Open in Browser icon button In case you don t have docker desktop you can go to localhost healthz using postman or your browser to access the permify Rest API Hurray You have successfully set up a permify service on your local computer You might be wondering about how you are going to connect the flask app with the Permify service That s very easy Your flask app will simply communicate with Permify service via the REST API provided That s what APIs are for right It s now time to make use of the authorization model we created earlier on As earlier mentioned we made use of the playground to create the model for a reason Here is why “The Permify Schema needs to be configured and sent to the Permify API in a string format Therefore the created model should be converted to a string Although it could easily be done programmatically it could be a little challenging to do it manually To help with that we have a button on the playground to copy the created model to the clipboard as a string so you get your model in string format easily Configuring Authorization Model on Permify APIClick on the Copy button on the playground to copy the authorization model Send the copied Permify Schema i e authorization model in the request body of Post request to API endpoint v tenants t schemas write Tip In order to make testing and communicating with Permify API endpoints easy and seamless you can fork the Permify API collection You get access to predefined sample body requests request methods and even data types of the body to send to the API After sending the Post request you will get a response JSON that contains schema version You can see the Permify API collection in the box labeled Note Keep the schema version returned by the API it will be used in a later section of this tutorial Add it as an environment variable to the env file created in the previous sectionWe have successfully completed the configuration of the authorization model via Permify Schema It s now time to add authorization data to see Permify in action Creating Relational TuplesRelational tuples represent authorization data They are the data used to determine whether a user is authorized on an access control check request You can create relational tuples by using v relationships write endpoint According to our authorization model defined in the earlier section after an organization is created we need to send a post request to permify write endpoint to make the user an admin of the organization i e we need to create this relational tuple organization lt id gt admin user lt id gt Let s update the create organization endpoint to include the creation of relational tuple But before we do that let s write functions that will be used to communicate with Permify API Store the schema version returned when creating the authorization in the env file created in the previous section Create a constants py file in the src folder and copy the following code into it Create a permify py file in the src folder and copy the following code into it Import the newly created permify module and call it just after saving the organization data to the DB as shown below Let s create an endpoint to allow users to join the created organization as members Note We will also add permify endpoint to this to create this relational tuple organization lt id gt member user lt id gt py auth post organizations join login requireddef join organization organ id organization Organization query get organ id if organization user id current user id user User query get user id user organization id organ id db session commit create authorization data for this in permify service so it can be used to check for permission later on snap token permify create relational tuple type organization id str organ id id organization in our db member type user id str current user id relation return jsonify status SUCCESS message f current user username now member of organization name data id organization id name organization name admin organization creator id snap token snap token else return jsonify status ERROR message f The organization does not exist data None We are done with the authentication and authorization part of the Blog Application What s left now is the resources i e Blog posts we want to restrict access to Proceed to the next section to start building the blog post functionalities Step Build Blog EndpointsWe ll create the following endpoints A POST posts API route to create postsA GET posts id API route to view a postA PUT posts id API route to edit a postA DELETE posts id API route to delete a postNote We will apply Permify check requests on each endpoint listed above to control the authorization And the resource based authorization checks in the form of Can user U perform action Y in resource Z will be used extensively Remember we have created User and Organization models but we haven t created Post model Let s do that now Add the following code to the models py file Note In order for the post table to be created we ll need to delete the previously created db sqlite file in the instance folder As done in the creating relational tuples section we ll also create relational tuples here in the create a post endpoint so our authorization data on Permify writeDB can be accurate and up to date Add the following codes to the blog py file Create decorator py file inside the src folder and copy the following codes into it Note We added the authorization check in the decorators py file so as to avoid repetition all over our blog endpoints i e adhere to the DRY principle What s happening in the above code snippet We created three decorators to ensure that a User has permission to perform a certain action on the blog resource Within each decorator we make API requests to the appropriate Permify REST API endpoints to determine whether a user s request should be granted or denied If the request should be denied we return abort which will raise an HTTP exception with the status code forbidden If the request should be allowed we grant the user access Step Add Dummy Organizations amp Resources and Store them in Flask AppNow that we have the following ready and completed Flask appPermify serviceAccess control checks added to the appropriate endpointsIt s time to access the write endpoints and create users organizations and posts to use as dummy data for testing in the next step I have created a postman collection to make things easier for you Register a user as shown below Create an organization using the newly registered user Register another user Make the second registered user a member of the organization created in no above Register a third user Create an organization using the registered user in no above Step Test the Endpoints with the Dummy Resources outLog in as the first user created in Step I e the admin of the first organization created Note You can send a GET request to the me endpoint to know the currently logged in user Try creating a post for a second organization which obviously should fail as the user isn t an admin nor a member of the organization Change the organization in no above to the first organization in which the logged in user is an admin Log in as the second user and try deleting the post created in no above This should fail because even though the second user is a member of the organization he isn t the author nor an admin of the organization ConclusionYou have just learned about how to use flask login to set up session authentication and Permify to decouple authorization modeling data and logic away from your core application If you have questions feel free to reach out 2023-02-24 19:43:31
海外TECH DEV Community Why your manager may not have an engineering background https://dev.to/linearb/why-your-manager-may-not-have-an-engineering-background-3h6k Why your manager may not have an engineering backgroundAs surprising as it is many of the best managers that leadership coach Lena Reinhard has encountered aren t engineers themselves Management isn t all about coding at it s core it s about being a leader and connecting to your employees This clip comes from our recent Interact panel about treating devs like human beings hosted by Conor Bronsdon check it out here Want to cut code review time by up to Add estimated review time to pull requests automatically gitStream is the free dev tool from LinearB that eliminates the No bottleneck in your team s workflow pull requests and code reviews After reviewing the work of dev teams LinearB s engineers and data scientists found that pickup times and code review were lasting to days longer than they should be The good news is that they found these delays could be eliminated largely by adding estimated review time to pull requests Learn more about how gitStream is making coding better HERE 2023-02-24 19:42:22
海外TECH DEV Community Using Different Color Spaces to Compare Colors https://dev.to/bytebodger/using-different-color-spaces-to-compare-colors-5agg Using Different Color Spaces to Compare Colors NOTE The live web app that encompasses this functionality can be found here All of the underlying code for that site can be found here In the previous article I took a pixelated image and matched each of the blocks to their closest colors in my inventory of paints But as we saw in the finished images the color matches were not entirely satisfying If we want to strive for better color matching the first thing to look at is the color space that we choose to use We started using a basic RGB model This is intuitive to web developers because nearly all colors that we deal with follow an RGB model But RGB is only one of many different color spaces And each different color space will produce difference results For reference here is our base image which has already been pixelated but has not been matched against the physical colors in my inventory of paints And when we did a basic RGB calculation we ended up with this conversion That s not horrible But it s not great either So let s look at using some other potential color spaces CMYKCMYK is the color space used by printers From this perspective it may seem to be a good fit for our needs because we re trying to match digital colors to those that exist in the real world e g paints First we ll need to update our getClosestColorInThePalette function The new version looks like this const getClosestColorInThePalette referenceColor rgbModel gt const key referenceColor red referenceColor green referenceColor blue if closestColors key return closestColors key let closestColor blue green name red let shortestDistance Number MAX SAFE INTEGER const algorithm local getItem algorithm palette forEach paletteColor gt if shortestDistance return let distance switch algorithm case algorithms CMYK const cyan paletteCyan magenta paletteMagenta yellow paletteYellow key paletteKey convertRgbToCmyk paletteColor const cyan referenceCyan magenta referenceMagenta yellow referenceYellow key referenceKey convertRgbToCmyk referenceColor distance Math sqrt Math pow referenceCyan paletteCyan Math pow referenceMagenta paletteMagenta Math pow referenceYellow paletteYellow Math pow referenceKey paletteKey break case algorithms RGB default distance Math sqrt Math pow paletteColor red referenceColor red Math pow paletteColor green referenceColor green Math pow paletteColor blue referenceColor blue break if distance lt shortestDistance shortestDistance distance closestColor paletteColor closestColors key paletteColor return closestColor I added case statements so that we can use different algorithms depending upon the color model we ve chosen Almost all of these calculations will use a root mean square RMS calculation RMS is the formula that you use to find the distance between two different points in three dimensional space Note that I also converted the RGB algorithm to use RMS I ve found that this alteration makes little difference in the visual output of the RGB calculation but using RMS will make it more consistent with the rest of the color space calculations Also note that we re always starting from RGB values That s what gets passed into the function So if we want to calculate differences based upon the CMYK color space we ll first need to convert our RGB value to CMYK That s why the values are first passed into convertRgbToCmyk before we run the algorithm Here s what the convertRgbToCmyk function looks like const convertRgbToCmyk rgbColor rgbModel gt const red green blue rgbColor let cyan red let magenta green let yellow blue let key Math min cyan magenta yellow const divider key key cyan cyan key divider magenta magenta key divider yellow yellow key divider key key return cyan magenta yellow key And here s what the pixelated image looks like when we do our color matching based upon CMYK Well that s a little different than the RGB calculation But I d hardly call it better So let s keep searching through different color spaces HSLIf you ve done any work in graphic tools like PaintShop you re probably familiar with HSL It represents a conical color space based on hue saturation and lightness This color space is also more intuitive for some artists So once again we ll update our getClosestColorInThePalette function The new version looks like this const getClosestColorInThePalette referenceColor rgbModel gt const key referenceColor red referenceColor green referenceColor blue if closestColors key return closestColors key let closestColor blue green name red let shortestDistance Number MAX SAFE INTEGER const algorithm local getItem algorithm palette forEach paletteColor gt if shortestDistance return let distance switch algorithm case algorithms CMYK const cyan paletteCyan magenta paletteMagenta yellow paletteYellow key paletteKey convertRgbToCmyk paletteColor const cyan referenceCyan magenta referenceMagenta yellow referenceYellow key referenceKey convertRgbToCmyk referenceColor distance Math sqrt Math pow referenceCyan paletteCyan Math pow referenceMagenta paletteMagenta Math pow referenceYellow paletteYellow Math pow referenceKey paletteKey break case algorithms HSL const hue paletteHue saturation paletteSaturation lightness paletteLightness convertRgbToHsl paletteColor const hue referenceHue saturation referenceSaturation lightness referenceLightness convertRgbToHsl referenceColor distance Math sqrt Math pow referenceHue paletteHue Math pow referenceSaturation paletteSaturation Math pow referenceLightness paletteLightness break case algorithms RGB default distance Math sqrt Math pow paletteColor red referenceColor red Math pow paletteColor green referenceColor green Math pow paletteColor blue referenceColor blue break if distance lt shortestDistance shortestDistance distance closestColor paletteColor closestColors key paletteColor return closestColor The HSL calculation is basically identical to the RGB calculation We re still taking the RMS result from the values in the palette color versus the reference color But rather than comparing red green and blue between both colors we re comparing hue saturation and lightness Just as we need to convert RGB values to CMYK to run the CMYK matching algorithm we ll need to convert RGB values to HSL to run our new HSL matching algorithm Here s what the convertRgbToHsl function looks like const convertRgbToHsl rgbcolor rgbModel gt let red green blue rgbcolor red red green green blue blue const maximum Math max red green blue const minimum Math min red green blue const basis maximum minimum let hue let saturation let lightness basis if maximum minimum hue saturation else const difference maximum minimum saturation lightness gt difference maximum minimum difference maximum minimum switch maximum case red hue green blue difference green lt blue break case green hue blue red difference break case blue default hue red green difference break hue hue return hue saturation lightness And here s what the pixelated image looks like when we do our color matching based upon HSL Honestly I prefer this transformation to the RGB or CMYK results But she still kinda looks like she s wearing a mask At this point it s time to look beyond these basic color models XYZThe XYZ color space formally known as the CIE color space is quite intriguing As the name implies it was developed back in It was the first attempt to produce a color space based on measurements of human color perception and it s the basis for almost all other color spaces That s what we re really going for here We want to take two RGB colors and determine how close they are based on human perception Again we ll update our getClosestColorInThePalette function The new version looks like this const getClosestColorInThePalette referenceColor rgbModel gt const key referenceColor red referenceColor green referenceColor blue if closestColors key return closestColors key let closestColor blue green name red let shortestDistance Number MAX SAFE INTEGER const algorithm local getItem algorithm palette forEach paletteColor gt if shortestDistance return let distance switch algorithm case algorithms CMYK const cyan paletteCyan magenta paletteMagenta yellow paletteYellow key paletteKey convertRgbToCmyk paletteColor const cyan referenceCyan magenta referenceMagenta yellow referenceYellow key referenceKey convertRgbToCmyk referenceColor distance Math sqrt Math pow referenceCyan paletteCyan Math pow referenceMagenta paletteMagenta Math pow referenceYellow paletteYellow Math pow referenceKey paletteKey break case algorithms HSL const hue paletteHue saturation paletteSaturation lightness paletteLightness convertRgbToHsl paletteColor const hue referenceHue saturation referenceSaturation lightness referenceLightness convertRgbToHsl referenceColor distance Math sqrt Math pow referenceHue paletteHue Math pow referenceSaturation paletteSaturation Math pow referenceLightness paletteLightness break case algorithms XYZ const x paletteX y paletteY z paletteZ convertRgbToXyz paletteColor const x referenceX y referenceY z referenceZ convertRgbToXyz referenceColor distance Math sqrt Math pow referenceX paletteX Math pow referenceY paletteY Math pow referenceZ paletteZ break case algorithms RGB default distance Math sqrt Math pow paletteColor red referenceColor red Math pow paletteColor green referenceColor green Math pow paletteColor blue referenceColor blue break if distance lt shortestDistance shortestDistance distance closestColor paletteColor closestColors key paletteColor return closestColor Just like before we re using a RMS calculation to determine the distance between the reference color and the palette color But this time we re comparing the values from the XYZ color space Of course that means that we need to convert the RGB values to XYZ Here s what the convertRgbToXyz function looks like const convertRgbToXyz rgbColor rgbModel gt const convert color gt color color color color gt Math pow color color color color return color let red green blue rgbColor red convert red green convert green blue convert blue const x red green blue const y red green blue const z red green blue return x y z No I certainly didn t come up with that equation on my own But that s how you convert an RGB value to XYZ And here s what the pixelated image looks like when we do our color matching based upon XYZ Wow To my eye at least this particular transformation is a lot better There s still some wonkiness there There s some odd groupings of pinks above her eyes But it seems to be a much closer match than anything we accomplished with RGB CMYK or HSL comparisons Delta E The last model we re gonna experiment with is called Delta E Delta E isn t a color space Rather it s the latest in a long line of formulas that have been developed for color matching based upon the CIELAB or L a b color space Here s a snapshot of the calculations that go into that formula Dayyumm Well let s drive into implementing this First we ll update our getClosestColorInThePalette function again const getClosestColorInThePalette referenceColor rgbModel gt const key referenceColor red referenceColor green referenceColor blue if closestColors key return closestColors key let closestColor blue green name red let shortestDistance Number MAX SAFE INTEGER const algorithm local getItem algorithm palette forEach paletteColor gt if shortestDistance return let distance switch algorithm case algorithms CMYK const cyan paletteCyan magenta paletteMagenta yellow paletteYellow key paletteKey convertRgbToCmyk paletteColor const cyan referenceCyan magenta referenceMagenta yellow referenceYellow key referenceKey convertRgbToCmyk referenceColor distance Math sqrt Math pow referenceCyan paletteCyan Math pow referenceMagenta paletteMagenta Math pow referenceYellow paletteYellow Math pow referenceKey paletteKey break case algorithms HSL const hue paletteHue saturation paletteSaturation lightness paletteLightness convertRgbToHsl paletteColor const hue referenceHue saturation referenceSaturation lightness referenceLightness convertRgbToHsl referenceColor distance Math sqrt Math pow referenceHue paletteHue Math pow referenceSaturation paletteSaturation Math pow referenceLightness paletteLightness break case algorithms XYZ const x paletteX y paletteY z paletteZ convertRgbToXyz paletteColor const x referenceX y referenceY z referenceZ convertRgbToXyz referenceColor distance Math sqrt Math pow referenceX paletteX Math pow referenceY paletteY Math pow referenceZ paletteZ break case algorithms DELTA E const paletteLabColor convertRgbToLab paletteColor const referenceLabColor convertRgbToLab referenceColor distance calculateDeltaE paletteLabColor referenceLabColor break case algorithms RGB default distance Math sqrt Math pow paletteColor red referenceColor red Math pow paletteColor green referenceColor green Math pow paletteColor blue referenceColor blue break if distance lt shortestDistance shortestDistance distance closestColor paletteColor closestColors key paletteColor return closestColor In this case we re not doing the calculation directly in this function because we re not using a simple RMS algorithm Instead we re passing the values into our new calculateDeltaE function But first we need to get L a b values from our RGB objects Here s what the convertRgbToLab function looks like const convertRgbToLab rgbColor rgbModel gt const xyzColor convertRgbToXyz rgbColor return convertXyzToLab xyzColor That s obviously pretty simple because the L a b conversion expects an XYZ color Of course we already wrote a convertRgbToXyz function Once we have the XYZ value then we call convertXyzToLab Here s what the convertXyzToLab function looks like const convertXyzToLab xyzColor xyzModel gt const adjust value gt value gt Math pow value value let x y z xyzColor x x y y z z x adjust x y adjust y z adjust z const lightness y const redGreen x y const blueYellow y z return lightness redGreen blueYellow Once we have the L a b values we can plug them into our calculateDeltaE function looks like const calculateDeltaE labColor labModel labColor labModel gt const lightness lightness redGreen redGreen blueYellow blueYellow labColor const lightness lightness redGreen redGreen blueYellow blueYellow labColor Math raddeg function rad return rad Math PI Math degrad function deg return Math PI deg const avgL lightness lightness const c Math sqrt Math pow redGreen Math pow blueYellow const c Math sqrt Math pow redGreen Math pow blueYellow const avgC c c const g Math sqrt Math pow avgC Math pow avgC Math pow const ap redGreen g const ap redGreen g const cp Math sqrt Math pow ap Math pow blueYellow const cp Math sqrt Math pow ap Math pow blueYellow const avgCp cp cp let hp Math raddeg Math atan blueYellow ap if hp lt hp hp let hp Math raddeg Math atan blueYellow ap if hp lt hp hp const avghp Math abs hp hp gt hp hp hp hp const t Math cos Math degrad avghp Math cos Math degrad avghp Math cos Math degrad avghp Math cos Math degrad avghp let deltahp hp hp if Math abs deltahp gt if hp lt hp deltahp else deltahp const deltalp lightness lightness const deltacp cp cp deltahp Math sqrt cp cp Math sin Math degrad deltahp const sl Math pow avgL Math sqrt Math pow avgL const sc avgCp const sh avgCp t const deltaro Math exp Math pow avghp const rc Math sqrt Math pow avgCp Math pow avgCp Math pow const rt rc Math sin Math degrad deltaro const kl const kc const kh return Math sqrt Math pow deltalp kl sl Math pow deltacp kc sc Math pow deltahp kh sh rt deltacp kc sc deltahp kh sh You probably don t wanna spend too much time looking at that function It ll give you a headache For now we can just be content to know that we have the logic quantified here in JavaScript And now that we can calculate Delta E values here s what the pixelated image looks like when we do our color matching based upon that algorithm To be frank I don t like this one nearly as much as the product that we received from the XYZ calculation But it s still useful as another reference point Which algorithm won Based upon the test results from this one image it may be tempting to say that the XYZ algorithm is the best But that assessment would be overly simplistic You see I ve learned after playing around with hundreds of images that each algorithm even the simplistic RGB comparison has its strengths and weaknesses For this particular image it may be true that XYZ is the winner But when you load other images you may find that you get a much more satisfying result from one of the other algorithms For this reason I didn t simply settle on a winner and then hardcode that into Paint Map Studio Instead I built an interactive form that allows you to experiment with many different settings including different algorithms as you try to find the best possible match To be honest it can sometimes be surprising to see how well a particular algorithm performs on one image and then how poorly it performs on the next So it s valuable to be able to flip between them and compare the results In the next installment We ve implemented all the algorithms that we need to find the best match So is that it Hardly Even when we look at the XYZ generated image above it may feel closer to the original image than any of the other algorithms but it still feels off There are pinks where they really shouldn t be There are dark greens halo ing her hairline In short we can still do better But if we re not gonna keep cycling through one algorithm after the next how do we improve on the color matching The answer comes from our palette of colors Even though I have more than unique paints each with their own distinct color that s still not enough colors to faithfully portray an image like this woman s face We need more colors In the next installment I ll show how to mix paints virtually so you can determine the best palette for your image 2023-02-24 19:31:05
海外TECH DEV Community Introduction and Installation https://dev.to/neeraj1997dev/introduction-and-installation-4e38 Introduction and InstallationWhat is golang Golang Go is a statically and compiled language created by google Go is mostly used to develop highly scalable and fast web apps Benefits of using go for your rest apiThere are so many programming languages to choose from when you want to make a rest api Python flask node or even java However go has some benefits which makes it a good choice whenever you are making a rest api some of the benefits of using go Quick compilation and execution speed its very easy and fast to learn go has a very simple syntax This makes it very easy to learn Lightweight goroutines that support concurrency Extensive and very well documented built in libraries Why learn Golang Now you still might be asking why should I learn Golang with all the other alternatives out there list of some of the pros of the Go programming language Simple syntax Go has concise and straightforward syntax that makes writing readable and maintainable code easy Compiled languageStatic linking The compiler supports static linking which means you can statically link your project into one massive binary and then simply deploy it to the cloud or a server Open source Go is open source so you can read the source code and contribute to the repository Installing Updating GoIf you re updating a previously installed Go version you must first delete the older one sudo rm r usr local goDownload the latest version of Go archive from and extract it sudo tar C usr local xzf go linux amd tar gzNote some people use the Go version manager GVM to install and set up Go a tool similar to NVM which I highly recommend for Node js but for Go I prefer to set up everything myself Next set the PATH environment variables by adding the following to bashrc export PATH PATH usr local go binexport GOPATH HOME goHere I use home neeraj go as my workspace which is HOME go but feel free to change it according to your preference And create your workspace mkdir p go src github com neerajGolang Study Point 2023-02-24 19:08:22
Apple AppleInsider - Frontpage News Pick up Apple's M2 Mac mini 512GB for just $699 ($100 off) https://appleinsider.com/articles/23/02/24/pick-up-apples-m2-mac-mini-512gb-for-just-699-100-off?utm_medium=rss Pick up Apple x s M Mac mini GB for just off Apple s new Mac mini M is off exclusively for AppleInsider readers driving the cost down to a record low when ordered with a GB SSD Save on the Mac mini To snap up the exclusive discount add the desktop to your cart at Apple Authorized Reseller Adorama and enter promo code APINSIDER during Step of checkout Read more 2023-02-24 19:47:00
Apple AppleInsider - Frontpage News Apple's new hire will help build video ad business for Apple TV+ https://appleinsider.com/articles/23/02/24/apples-new-hire-will-help-build-video-ad-business-for-apple-tv?utm_medium=rss Apple x s new hire will help build video ad business for Apple TV Apple has recently hired an ad executive for Apple TV as the company is considering moving into the video advertising business Apple TV might get adsA new report from The Information reveals that the company hired Lauren Fry an advertising executive for TV and digital video Her exact title is unclear but previous roles included chief revenue officer for digital video ad tech firm Simulmedia and ad sales roles at AT amp T and Comcast Read more 2023-02-24 19:52:03
Cisco Cisco Blog Driving Mainstream IoT Adoption at Scale https://feedpress.me/link/23532/15991723/driving-mainstream-iot-adoption-at-scale Driving Mainstream IoT Adoption at ScaleCisco Mobility Services offers simplified solutions offered as a Service to deliver advanced mobile IoT use cases at scale such as connected cars and connected distributed utilities demanding secure high bandwidth low latency services from the carrier edge 2023-02-24 19:07:21
海外科学 NYT > Science Alligators in New York: A Brief History https://www.nytimes.com/2023/02/24/nyregion/alligator-nyc.html alligators 2023-02-24 19:09:20
ニュース BBC News - Home Omagh police shooting: PSNI treating John Caldwell attack as terrorist-related https://www.bbc.co.uk/news/uk-northern-ireland-64751458?at_medium=RSS&at_campaign=KARANGA sports 2023-02-24 19:04:18
ニュース BBC News - Home Qatar Open: Andy Murray saves five match points to reach Doha final https://www.bbc.co.uk/sport/tennis/64764087?at_medium=RSS&at_campaign=KARANGA Qatar Open Andy Murray saves five match points to reach Doha finalAndy Murray produces yet another remarkable comeback saving five match points to beat Jiri Lehecka and reach the Qatar Open final in Doha 2023-02-24 19:27:33
ビジネス ダイヤモンド・オンライン - 新着記事 小学校受験で頻出!「平面図形」問題は“斜めの線”マスターが攻略の鍵!例題で解説 - 幼児教育&お受験のリアル https://diamond.jp/articles/-/317312 小学校受験 2023-02-25 04:55:00
ビジネス ダイヤモンド・オンライン - 新着記事 千葉の名門医療法人「3000万円恐喝事件」なぜ起きた、右翼に狙われた理由 - 倒産のニューノーマル https://diamond.jp/articles/-/318365 医療法人 2023-02-25 04:50:00
ビジネス ダイヤモンド・オンライン - 新着記事 出会い系アプリで「美人局」被害増加中、脅迫されたエリート会社員の末路 - オオカミ少年片岡の「あなたの隣に詐欺師がいます。」 https://diamond.jp/articles/-/318290 出会い系アプリで「美人局」被害増加中、脅迫されたエリート会社員の末路オオカミ少年片岡の「あなたの隣に詐欺師がいます。 2023-02-25 04:45:00
ビジネス ダイヤモンド・オンライン - 新着記事 「おかあさんといっしょ」ファン衝撃!“卒業”を巡る想定外のどんでん返し - 井の中の宴 武藤弘樹 https://diamond.jp/articles/-/318364 顛末 2023-02-25 04:40:00
ビジネス ダイヤモンド・オンライン - 新着記事 「50歳男性、余裕資金なしの初心者」に一択でおすすめしたい投資プランは? - 老後の不安がなくなる50歳からのお金の増やし方 https://diamond.jp/articles/-/317616 「歳男性、余裕資金なしの初心者」に一択でおすすめしたい投資プランは老後の不安がなくなる歳からのお金の増やし方シニア・プライベートバンカー、濵島成士郎氏の文庫新刊『老後の不安がなくなる歳からのお金の増やし方』からの一部抜粋で、老後の資産形成のため、確実にお金を増やす方法を紹介していく。 2023-02-25 04:35:00
ビジネス ダイヤモンド・オンライン - 新着記事 世界最高峰の楽団「ウィーン・フィル」、曲者を束ねる楽団長・事務局長コンビの妙 - ニュースな本 https://diamond.jp/articles/-/317951 2023-02-25 04:30:00
ビジネス ダイヤモンド・オンライン - 新着記事 その「知らんけど」、間違ってます!関西人がモヤつくホントの理由 - from AERAdot. https://diamond.jp/articles/-/318281 fromaeradot 2023-02-25 04:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 ドレスコード「ブラックタイ」はどんな服装?“黒ネクタイ”で行ったら赤っ恥 - 男のオフビジネス https://diamond.jp/articles/-/318391 第一印象 2023-02-25 04:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 埼玉で春の日帰り旅行7選、トトロの森・絶景パワスポ・市場グルメ・地酒処... - 地球の歩き方ニュース&レポート https://diamond.jp/articles/-/318245 埼玉で春の日帰り旅行選、トトロの森・絶景パワスポ・市場グルメ・地酒処地球の歩き方ニュースレポート今回紹介する記事は「埼玉・春の日帰り旅行選」です。 2023-02-25 04:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 糖尿病患者で静脈血栓塞栓症のリスクが高いのは男性と女性、どちら? - ヘルスデーニュース https://diamond.jp/articles/-/318403 静脈血栓塞栓症 2023-02-25 04:10:00
ビジネス ダイヤモンド・オンライン - 新着記事 【お金を増やす】 お金を増やしたい投資家に“超お薦め”の「3つのステップ」 - 個人投資家もマネできる 世界の富裕層がお金を増やしている方法 https://diamond.jp/articles/-/315815 米国の富裕層の間では、米国以外の海外資産を組み入れるグローバル投資の動きが、以前にも増して加速しているという。 2023-02-25 04:05:00
ビジネス 東洋経済オンライン 6月~販売、晴海フラッグ「タワー棟」"買い"なのか 2023年の「マンション市況」はどう動くのか | 街・住まい | 東洋経済オンライン https://toyokeizai.net/articles/-/654234?utm_source=rss&utm_medium=http&utm_campaign=link_back harumi 2023-02-25 04:30:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)