投稿時間:2022-04-02 00:27:56 RSSフィード2022-04-02 00:00 分まとめ(35件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita BlenderでVOICEVOXの音声をPythonで追加 https://qiita.com/SaitoTsutomu/items/b2ff4b45ffe578ec23a4 BlenderでVOICEVOXの音声をPythonで追加概要CSVで用意したテキストをVOICEVOXで音声ファイルを作り、Blenderで取り込みます。 2022-04-01 23:22:21
Ruby Rubyタグが付けられた新着投稿 - Qiita rails seeds.rbファイル とは https://qiita.com/kuramoto30/items/c439038cb93234036ef9 データを件入れる場合seedsrbtimesdonUsercreatenametestnendまだテストデータは反映されていないターミナルrailsdbseedこれでテストデータが読み込まれます。 2022-04-01 23:53:44
Ruby Railsタグが付けられた新着投稿 - Qiita rails seeds.rbファイル とは https://qiita.com/kuramoto30/items/c439038cb93234036ef9 データを件入れる場合seedsrbtimesdonUsercreatenametestnendまだテストデータは反映されていないターミナルrailsdbseedこれでテストデータが読み込まれます。 2022-04-01 23:53:44
技術ブログ Developers.IO 有限の経験機会を得るために必要なこと https://dev.classmethod.jp/articles/opportunity-to-gain-experience/ 要素 2022-04-01 14:03:29
海外TECH Ars Technica Report: US Senators urge FTC to scrutinize Microsoft/Activision merger [Updated] https://arstechnica.com/?p=1844932 activision 2022-04-01 14:34:05
海外TECH Ars Technica NASA’s big rocket faces its last test before launching https://arstechnica.com/?p=1844550 pleasant 2022-04-01 14:17:02
海外TECH MakeUseOf How to Use the Flashlight on Your Apple Watch https://www.makeuseof.com/how-to-use-apple-watch-flashlight/ watch 2022-04-01 14:30:13
海外TECH MakeUseOf 6 Enlightening Online Tai Chi Classes You Need To Join Right Now https://www.makeuseof.com/top-online-tai-chi-classes/ youtube 2022-04-01 14:15:14
海外TECH DEV Community 6 Biggest Mistakes Technical Founders Make https://dev.to/kennedyrose/6-biggest-mistakes-technical-founders-make-4f0j Biggest Mistakes Technical Founders MakeUsually developers like to think of an idea and just start coding Which is exactly what I did for my first couple of products But to have the best chance of success you actually shouldn t write a line of code until you have a plan for a few very important things Ignoring Product Market Fit There s a gap in the market but is there a market in the gap is a common quote that describes this perfectly Technical founders often don t have a well rounded enough understanding of the market they re in and just think their tech skills will be enough Make sure you have an idea of the right audience for your product and make sure they are actually willing to pay for it Have plans to pivot to new audiences if it doesn t work out Not Having a Plan for MonetizationCan you even sell your product What does the overhead look like Do your tools and libraries have permissive enough license for you to use them for a commercial product Make sure you are pricing your SaaS correctly to cover everything Ideally you should be revenue positive after your first client You should also consider pre selling your product so that you re revenue positive before you even launch Not Researching CompetitionSometimes technical founders don t check competition at all When they do usually their plan is to make a simpler version of their competition s product and undercut on pricing But often undercutting the competition isn t enough Instead what can you offer that your competitor can t Do some research into your competitors and how their customers feel about their product Find what their customers need that they aren t getting and offer it in your product Not Having a Marketing StrategyHow are you actually going to bring your product to your target audience SEO on your product s website alone will not likely get you anywhere near where you want to be on the search result pages You will need to find out where your target audience is when they need you the most and find a way to be there to help them This can be done through ads social network content email campaigns or even cold calls Underestimating TimeDevelopers are notoriously bad at predicting how long it takes them to do something Which I completely understand Development on a new project often involves learning some kind of new skill library or framework And the time it takes to do that can depend on documentation and whatever other resources are available online Quality in the learning resources can vary wildly so some things that you d think would take you a few minutes wind up taking you a week I usually take the amount of time that I think a job will take and multiply it by If it seems like a lot of time then great you ll finish early and be a hero Most of the time I find the padded number winds up being accurate when you factor in bugs and other issues that pop up that you didn t initially know about But the real unsung hero here is outsourcing I know you don t want to because you can do it yourself But just because you can doesn t mean you should Outsourcing the simple stuff can let you focus on the real business problem you re trying to solve Too Much Focus on Technical FeaturesDon t fall in love with the technical aspects of your product too much Remember that all your customers care about is what s in it for them They don t care about how fast your server is they just want to know how that benefits them directly If it doesn t benefit them enough or at all maybe don t put any more time into that particular feature or don t spend any money marketing it Benefits gt Features Going FurtherIf you re a technical founder me too Make sure you subscribe to my blog if you want more tips on things to look out for while building your product 2022-04-01 14:40:51
海外TECH DEV Community Building an E-Commerce API using Nestjs, SQLite, and TypeORM https://dev.to/arctype/building-an-e-commerce-api-using-nestjs-sqlite-and-typeorm-17mp Building an E Commerce API using Nestjs SQLite and TypeORM IntroductionNestjs is a cutting edge Node js framework for developing server side applications that are efficient dependable and scalable It is simple to integrate with NoSQL and SQL databases such as MongoDB Yugabyte SQLite Postgres MySQL and others It supports popular object relational mappers such as TypeORM Sequelize and Mongoose In this tutorial we ll create an e commerce application with SQLite and TypeORM We ll also look at Arctype a powerful SQL client and database management tool Let s get started PrerequisitesThis tutorial is a hands on demonstration to get you started Ensure you ve met the following requirements You have Node gt except for v installedYou have a foundational knowledge of JavascriptArctype installed Project setupTo get started with Nestjs install the Nestjs CLI with the command below npm i g nestjs cliOnce the installation is completed create a Nestjs project with the command below nest new ecommerceChoose your npm as the package manager hit the enter button and wait for Nest to install the required packages to run this application Once the installation is completed change the directory to the project folder with the command below cd ecommerceThen open the project directory in your favorite text editor or IDE open a new terminal and run the server on development mode This will enable hot reload and allows us to see possible errors on the console with the command below npm run start dev Install DependenciesWith the server up and running open a new terminal window so you don t quit the server This will allow you to see the effect of the changes made to the codebase throughout this tutorial Now install the following dependencies PassportPassport localJwtPassport jwtSQLIteTypeORMBcryptYou can do this with the command below npm install save nestjs passport passport passport local nestjs jwt passport jwt nestjs typeorm typeorm sqlite bcryptThen install the dev dependencies with the command below npm install save dev types passport local types passport jwt types bcryptYou can grab a cup of coffee while the npm installs the packages Once the installation is completed let s get our hands dirty Create App ModulesWith all the necessary packages required to run the application let s proceed to create the application modules To build a clean and easily maintained application you ll generate separate modules for all the features implemented in this application Since this is an eCommerce application you ll have authentication cart products and orders All these will be in their own separate modules Let s start with the authentication module Create Authentication ModuleGenerate an authentication module with the command below nest g module authThe above command creates an auth folder in the project s src directory with the necessary boilerplates and registers the module in the project root module app module ts file Next create a product cart order module with the command below Create a product modulenest g module product Create cart modulenest g module cart Create cart modulenest g module orderThe above will create a product cart and order folder in the project s src folder with the basic boilerplates and registers these modules in the project s root app module Setting up TypeORM and SQLite DatabasesWith the app modules installed set up TypeORM to connect your application to SQLite Database and create your module entities To get started open the app module ts and configure your SQLite database with the code snippets below imports … TypeOrmModule forRoot type sqlite database shoppingDB entities dirname entity ts js synchronize true …In the above code snippet you connected the application to an SQLite database using the TypeORM forRoot specifying the database type database name and the location where Nestjs can find the model entities Once the server refreshes you should see a shoppingDB file created in the root directory of this project Create App Entity ModelsWith the database setup let s create the entity models for our app modules We ll start with the auth module Generate an entity file in the auth module folder with the command below nest generate class auth user entity flatThen add the code snippet below to define the user table properties with the code snippet below import Entity OneToOne JoinColumn Column CreateDateColumn UpdateDateColumn PrimaryGeneratedColumn OneToMany from typeorm import CartEntity from src cart cart entity import OrderEntity from src order order entity Entity export class Users PrimaryGeneratedColumn id number Column username string Column password string Column role string CreateDateColumn createdAt String UpdateDateColumn updtedAt String OneToMany type gt CartEntity cart gt cart id JoinColumn cart CartEntity OneToOne type gt OrderEntity order gt order id JoinColumn order OrderEntity In the code snippet you imported the decorators required to set up your database table You also imported the cartEntity and orderEntity class which you ll create shortly Using the typeorm decorator we defined the database properties of the user s model Finally we created one to one and one to many relationships between the users entity and the cartEntity and orderEntity This way you can associate a cart item with a user The same applies to the user s order Next create the product entity class with the command below nest generate class product product entity flatThe above command will generate a product entity ts file in the products module folder Now configure the product table properties with the code snippet below import Entity JoinColumn OneToMany Column CreateDateColumn UpdateDateColumn PrimaryGeneratedColumn from typeorm import CartEntity from src cart cart entity Entity export class ProductEntity PrimaryGeneratedColumn uuid id number Column name string Column price number Column quantity string CreateDateColumn createdAt String UpdateDateColumn updtedAt String OneToMany type gt CartEntity cart gt cart id JoinColumn cart CartEntity In the above code snippet we configured the properties of the product table and created a one to many relationship with the cart entity Then create the cart entity with the command below nest generate class cart cart entity flatThe above command will generate a cart entity ts file in the cart module folder Now add the code snippet below to the file you created to configure the cart table properties import Entity OneToOne ManyToOne JoinColumn Column PrimaryGeneratedColumn from typeorm import OrderEntity from src order order entity import ProductEntity from src product product entity import Users from src auth user entity Entity export class CartEntity PrimaryGeneratedColumn uuid id number Column total number Column quantity number ManyToOne type gt ProductEntity order gt order id JoinColumn item ProductEntity ManyToOne type gt Users user gt user username JoinColumn user Users In the above code snippet you configured the properties of the cart table created a many to one relationship between the cart entity and a many to one relationship with the user s entity Lastly create the order entity with the command below nest generate class order order entity flatThe above command will generate a order entity ts file in the order module folder Open the order entity ts and configure the database table with the command below import Entity OneToMany JoinColumn OneToOne Column PrimaryGeneratedColumn from typeorm import ProductEntity from src product product entity import Users from src auth user entity Entity export class OrderEntity PrimaryGeneratedColumn uuid id number OneToMany type gt ProductEntity item gt item id items ProductEntity OneToOne type gt Users user gt user username JoinColumn user Users Column subTotal number Column default false pending boolean In the above code snippet you created a one to one relationship between the users entity and a one to many relationship with the products entity At this point your database entities are set and connected Now create your business logic to store records on these entities Create App ServicesNow create the services for the modules in this application Here you ll allow the admin to add products to the product table authenticate users allow users to add the products in the store to the cart and order the product via their cart Create the Auth ServiceTo create the auth service run the command below to generate the service for the auth module nest generate service auth service auth flatThe above command will generate an auth service ts file in the src auth service folder Now open the auth service ts file and add the code snippet below import Injectable HttpException HttpStatus from nestjs common import InjectRepository from nestjs typeorm import Repository from typeorm import Users from user entity import as bcrypt from bcrypt import JwtService from nestjs jwt Injectable export class AuthService constructor InjectRepository Users private userRepository Repository lt Users gt private jwt JwtService In the above code snippet you imported InjectRepository Repository decorator JwtService and bcrypt modules Then using the InjectRepository decorator you made the User entity class available in the auth service providing the method to perform CRUD operations in your User entity Then create a signup method to allow users to register in the application with the code snippet below async signup user Users Promise lt Users gt const salt await bcrypt genSalt const hash await bcrypt hash user password salt user password hash return await this userRepository save user Now create the validateUser method to validate the users details and the login method to generate a jwt token for the authenticated user … async validateUser username string password string Promise lt any gt const foundUser await this userRepository findOne username if foundUser if await bcrypt compare password foundUser password const password result foundUser return result return null return null async login user any const payload username user username sub user id role user role return access token this jwt sign payload Now we can implement our Passport local authentication strategy Create a file called local strategy ts in the auth module folder and add the following code import Strategy from passport local import PassportStrategy from nestjs passport import Injectable UnauthorizedException from nestjs common import AuthService from service auth service Injectable export class LocalStrategy extends PassportStrategy Strategy constructor private authService AuthService super async validate username string password string Promise lt any gt const foundUser await this authService validateUser username password if foundUser throw new UnauthorizedException return foundUser In the above code snippet you ve implemented a passport local strategy There are no configuration options so our constructor simply calls super without an options object You ve also implemented the validate method Passport will call the verify function for each strategy using an appropriate strategy specific set of parameters For the local strategy Passport expects a validate method with the following signature validate username string password string any Then create a jwt auth guard ts file in the auth module folder and define a custom auth guard with the code snippet below import Injectable from nestjs common import AuthGuard from nestjs passport Injectable export class LocalAuthGuard extends AuthGuard local You ll use the AuthGuard created in the code snippet to protect your API routes from unauthorized users Now create a jwt strategy file in the auth module folder to authenticate users and generate jwt tokens for logged in users with the code snippet below import ExtractJwt Strategy from passport jwt import PassportStrategy from nestjs passport import Injectable from nestjs common import jwtConstants from constants Injectable export class JwtStrategy extends PassportStrategy Strategy constructor super jwtFromRequest ExtractJwt fromAuthHeaderAsBearerToken ignoreExpiration false secretOrKey jwtConstants secret async validate payload any return userId payload sub username payload username role payload role Then configure the jwt module in the auth module ts file in the auth module folder Before that create a constants ts file in the same auth module folder to define a jwt secret with the code snippet below export const jwtConstants secret wjeld djeuedwe uejheuii jrjjejei rjdjfjf You can generate a more secured jwt secret on production but we ll use the one for demonstration sake Now import all the required modules in your auth module ts file with the code snippet below …import JwtModule from nestjs jwt import jwtConstants from constants import JwtStrategy from jwt strategy import PassportModule from nestjs passport import LocalStrategy from local strategy import TypeOrmModule from nestjs typeorm import Users from user entity …Then in the array of imports configure jwt with the code snippet below …imports PassportModule JwtModule register secret jwtConstants secret signOptions expiresIn m …In the above code snippet we add the PassModule package to allow passport to handle the users authentication and configured jwt using the JwtModule register method We pass in the secret we created in the constants file and specify the generated token s expiration time You can reduce or increase the time depending on the use case Create the Product ServiceWith the auth service setup generate a product service with the command below nest generate service product service productNow open the product service ts file generated by the above command in the product module and add the code snippets below import Injectable UnauthorizedException from nestjs common import ProductEntity from product entity import Repository UpdateResult DeleteResult from typeorm import InjectRepository from nestjs typeorm import Users from src auth user entity Injectable export class ProductsService constructor InjectRepository ProductEntity private productRepository Repository lt ProductEntity gt async getAll Promise lt ProductEntity gt return await this productRepository find async create product ProductEntity user Users Promise lt ProductEntity gt if user role admin return await this productRepository save product throw new UnauthorizedException async getOne id number Promise lt ProductEntity gt return this productRepository findOne id async update id number product ProductEntity user Users Promise lt UpdateResult gt if user role admin return await this productRepository update id product throw new UnauthorizedException async delete id number user Users Promise lt DeleteResult gt if user role admin return await this productRepository delete id throw new UnauthorizedException In the above snippet we created our CRUD services The create update and delete methods are restricted from the users Only the admin can create a product delete or update a product Now open the product module ts file and make the product entity accessible with the code snippet below imports TypeOrmModule forFeature ProductEntity Create the Cart ServiceAt this point the admin can add products to the database and authenticated users can see all available products Now let s allow the users to add the items they like to the cart To get started generate a Cart service with the command below nest generate service cart service cart flatThen open the cart service ts file generated by the command and add the code snippet below import Injectable from nestjs common import Repository from typeorm import InjectRepository from nestjs typeorm import CartEntity from cart entity import ProductsService from src product service products service import Users from src auth user entity Injectable export class CartService constructor InjectRepository CartEntity private cartRepository Repository lt CartEntity gt InjectRepository Users private userRepository Repository lt Users gt private productsService ProductsService …You imported the modules required to create a Nest js service in the above code snippet We also imported them here since you created a relationship between the cart user and product entities Then you make a constructor method to bind these entities to the CartService class Now create a method to add an item to the cart async addToCart productId number quantity number user string Promise lt any gt const cartItems await this cartRepository find relations item user const product await this productsService getOne productId const authUser await this userRepository findOne username user Confirm the product exists if product confirm if user has item in cart const cart cartItems filter item gt item item id productId amp amp item user username user if cart length lt const newItem this cartRepository create total product price quantity quantity newItem user authUser newItem item product this cartRepository save newItem return await this cartRepository save newItem else Update the item quantity const quantity cart quantity const total cart total quantity return await this cartRepository update cart id quantity total return null In the above code snippet you created an addToCart method that takes the productId quantity and user as arguments Then check if the user has the item already in their cart If so you increment the quantity and update the total price of that item Else you add the item to the user s cart Next make the cartEntity productEntity User entity and the productService accessible in the cartService by registering them in the cart module ts file with the code snippet below …import CartEntity from cart entity import ProductsService from src product service products service import ProductEntity from src product product entity import Users from src auth user entity Module imports TypeOrmModule forFeature CartEntity ProductEntity Users providers CartService ProductsService … Lastly create a getItemsInCart method that takes a user as an argument to return all the carts belonging to a particular user async getItemsInCard user string Promise lt CartEntity gt const userCart await this cartRepository find relations item user return await userCart filter item gt item user username user Create the Order ServiceWhen users are done shopping they can order the items in their cart Generate an order service with the command below nest generate service order service order flatNow open the order service ts file generated from running the above command and add the code snippet below import OrderEntity from order entity import Repository from typeorm import InjectRepository from nestjs typeorm import CartService from src cart service cart service import Users from src auth user entity Injectable export class OrderService constructor InjectRepository OrderEntity private orderRepository Repository lt OrderEntity gt InjectRepository Users private userRepository Repository lt Users gt private cartService CartService You imported the modules required to create a Nest js service in the above code snippet We also imported them here since you created a relationship between the cart user and product entities Then you created a constructor method to bind these entities to the OrderService class Now create a method to order the items in the user s cart …async order user string Promise lt any gt find user existing orders const usersOrder await this orderRepository find relations user const userOrder usersOrder filter order gt order user username user amp amp order pending false find user s cart items const cartItems await this cartService getItemsInCard user const subTotal cartItems map item gt item total reduce acc next gt acc next get the authenticated user const authUser await this userRepository findOne username user if users has an pending order add item to the list of order const cart await cartItems map item gt item item if userOrder length const newOrder await this orderRepository create subTotal newOrder items cart newOrder user authUser return await this orderRepository save newOrder else const existingOrder userOrder map item gt item await this orderRepository update existingOrder id subTotal existingOrder subTotal cart price return message order modified …Then create another method to get a user s order from the array of orders from the database with the code snippet below …async getOrders user string Promise lt OrderEntity gt const orders await this orderRepository find relations user return orders filter order gt order user username user Lastly open the order module ts file and make the users product and cart entities accessible in the orderService with the code snippet below import TypeOrmModule from nestjs typeorm import OrderEntity from order entity import ProductEntity from src product product entity import CartService from src cart service cart service import CartEntity from src cart cart entity import Users from src auth user entity import ProductsService from src product service products service Module imports TypeOrmModule forFeature OrderEntity ProductEntity CartEntity Users controllers OrderController providers OrderService CartService ProductsService Create App ControllersWith the application services successfully created let s create the API routes for the app services Create the Auth ControllerGenerate an auth controller with the command below nest generate controller auth controller auth flatNow open the auth controller ts file generated from running the above command and configure the auth routes with the code snippet below import Controller Request Post UseGuards Body from nestjs common import AuthGuard from nestjs passport import AuthService from service auth service import Users from user entity Controller api v auth export class AuthController constructor private usersService AuthService Post signup async signup Body user Users Promise lt Users gt return this usersService signup user UseGuards AuthGuard local Post login async login Request req return this usersService login req user Create the Product ControllerWith the auth controller routes configured generate a product controller with the command below nest generate controller product controller product flatOpen the product controller ts file generated from running the above command and configure the product routes with the code snippet below import Controller Post Get Put Delete Param Request Body UseGuards from nestjs common import UpdateResult DeleteResult from typeorm import ProductsService from service products service import ProductEntity from product entity import JwtAuthGuard from src auth jwt auth guard Controller api v products export class ProductsController constructor private productsService ProductsService UseGuards JwtAuthGuard Get async GetAll Promise lt ProductEntity gt return await this productsService getAll UseGuards JwtAuthGuard Post async Create Request req Body product ProductEntity Promise lt ProductEntity gt return await this productsService create product req user UseGuards JwtAuthGuard Get id async GetOne Param id number Promise lt ProductEntity gt return await this productsService getOne id UseGuards JwtAuthGuard Put id async Update Param id number Body product ProductEntity Request req Promise lt UpdateResult gt return await this productsService update id product req user UseGuards JwtAuthGuard Delete id async Delete Param id number Request req Promise lt DeleteResult gt return await this productsService delete id req user In the above code snippet you defined the CRUD routes for the product service We used the UseGuard decorator passing your JwtAuthGaurd to protect the routes from unauthorized users Create the Cart ControllerNow generate a cart controller with the command below nest generate controller cart controller cart flatThen open the cart controller ts file generated from running the above command and configure the cart routes with the code snippet below import Controller Post Get Request Delete Body UseGuards from nestjs common import CartService from service cart service import CartEntity from cart entity import JwtAuthGuard from src auth jwt auth guard Controller api v cart export class CartController constructor private cartService CartService UseGuards JwtAuthGuard Post async AddToCart Body body Request req Promise lt void gt const productId quantity body return await this cartService addToCart productId quantity req user username UseGuards JwtAuthGuard Get async getItemsInCart Request req Promise lt CartEntity gt return await this cartService getItemsInCard req user username Create the Order ControllerWith the cart routes configured create an order controller with the command below nest generate controller order controller order flatThen open the order controlle ts file generated from running the above command and configure the cart routes with the code snippet below import Controller Post Get Request UseGuards from nestjs common import OrderService from service order service import OrderEntity from order entity import JwtAuthGuard from src auth jwt auth guard Controller api v order export class OrderController constructor private orderService OrderService UseGuards JwtAuthGuard Post async order Request req Promise lt any gt return this orderService order req user username UseGuards JwtAuthGuard Get async getOrders Request req Promise lt OrderEntity gt return await this orderService getOrders req user username At this point all your API routes have been configured Test ApplicationNow let s test them out using Postman The results of come tests are shown below Feel free to test the other routes and play around with the code here on Github Connecting Arctype to SQLite DatabaseArctype is an SQL client and database management tool that s fun to use It allows you to have a visual representation of your database tables and you can perform the CRUD operations directory in your database using Arctype Connecting Arctype to an SQLite database is a straightforward process To get started follow the steps below First launch Arctype You ll see a screen like the one below allowing you to add your credentials Click on the SQLite tab This will bring up the screen below Click on the Choose SQLite File button and navigate to your project folder Select the application database file and press the open button Press the save button and you should see your database entities as shown in the screenshot below ConclusionBy building a demo project we ve learned how to make an e commerce application using Nestjs and SQLite Database First we started with the introduction of NestJS Then we created a NestJS application connected the application to an SQLite database using TypeORM and performed CRUD operations Now that you ve gotten the knowledge you seek feel free to add extra functionality to the application 2022-04-01 14:18:26
海外TECH DEV Community DBContext, System.InvalidOperationException, and mouse clicking speed demons. https://dev.to/szcz/dbcontext-systeminvalidoperationexception-and-mouse-clicking-speed-demons-24le DBContext System InvalidOperationException and mouse clicking speed demons IntroSo you ve dipped your toes into Blazor and want to see what all the hype is about By now you re probably aware that Blazor offers incredible frontend performance and represents a huge paradigm shift for NET Long gone are the days of page reloads and boring UIs This positions Blazor uniquely among the many exceptional frameworks that are available today Consider this Blazor enables UIs that compete with some of best web frameworks and has all of the power of NET on the backend…at least to me that s really exciting I ll cover the benefits of using Blazor and compare it to some modern frameworks in an upcoming post Anyways onto what you re here for You re using a single DBContext and got a little over zealous with the ol mouse click and ran into the following error message System InvalidOperationException A second operation was started on this context instance before a previous operation completed This is usually caused by different threads concurrently using the same instance of DbContext You ve ensured that all of your methods are using async await and you ve exhausted the stack overflow suggestions of setting your services to scoped or transient The reason you re still running into this is simply because the implementation of DbContext isn t thread safe More reading here Alright just get to it This post contains a tutorial on how to convert an existing service to make use of a DBContextFactory but also a summary at the bottom that gets right to it without the fluff Pick your poison TutorialTo get started I ve created a new Blazor Server project using NET For the purposes of this tutorial I ll make use of the existing WeatherForecastService and FetchData boilerplate files I will also be using an Azure SQL Server database however this is not a requirement and should not add any additional steps for other databases Required EF packages below Include EntityFramework Version Include Microsoft EntityFrameworkCore Version Include Microsoft EntityFrameworkCore SqlServer Version Include Microsoft EntityFrameworkCore Tools Version First I ve updated my appsettings json and added the connection strings for my Azure db At this stage you should ensure that you are able to connect to your database before proceeding Next I m going to create a new file in the Data folder called ExampleContext cs This will be our DB Context Let s flip over to program cs If you re on an older version of NET this will be done in startup cs and we ll add our DBContext Additionally we will update our WeatherForecastService to a scoped service line Sidenote I made some minor changes to WeatherForecast cs We re going to add the ForecastId key and also change TemperatureF from a computed property to an int Now that we ve done that we re able to scaffold our database and create the WeatherForecast table Note If you do not have the dotnet tool installed run this command dotnet tool install global dotnet efNext we re going to create our first migration Build the solution using dotnet build Once the build succeeds run the command dotnet ef migrations add CreateWeatherForecast If you receive the following error cd into your project directory and try again No project was found Change the current working directory or use the project option Now we ll migrate our database using the dotnet ef database update command You should now be able to see the WeatherForecast table in your database Let s make some changes to the WeatherForecastService First we ll need to add an ExampleContext field We will also need to add a WeatherForecastService constructor with an ExampleContext parameter Next we ll alter the GetForecastAsync method to fetch the forecasts from the database This will be empty for now Finally we will add an InsertForecastAsync method so that we can add new forecasts to our WeatherForecast table This will also give us the opportunity to see the shortcomings of a traditional DbContext Now we ll go to our FetchData razor file First let s add a new button that we ll use to insert forecasts into our table line Next we ll switch the forecasts array into a list due to the changes we made in the WeatherForecastService line Now add the InsertForecast function so that we can add some new forecasts to the table Line For the purposes of the demo we re just going to add the new forecast directly to the forecasts list so it appears immediately in the table Launch the app and navigate to the fetch data tab fetchdata You ll see that we have an Add new forecast button at the top of the table What happens if we click it rapidly Let s look into the error a bit moreSystem InvalidOperationException A second operation was started on this context instance before a previous operation completed This is usually caused by different threads concurrently using the same instance of DbContext Well let s see what Microsoft has to say about this EF Core provides the AddDbContext extension for ASP NET Core apps that registers the context as a scoped service by default In Blazor Server apps scoped service registrations can be problematic because the instance is shared across components within the user s circuit DbContext isn t thread safe and isn t designed for concurrent use Alright so how do we fix this By using a DBContextFactory We ll be able to instantiate an instance of DbContext that will be scoped to each Task in the WeatherForecastService After each task is complete that instance of DbContext will be disposed of And its super easy First though we re just going to quickly add a delete button so we can see how effective this really is In FetchData razor add a table header line new button line and stub out the DeleteForecast method line Head back to WeatherForecastService cs and add a DeleteForecast method just under the InsertForecast method Now let s fill out our stubbed DeleteForecast method in FetchData razor Our table should now look like this If we rapidly try and delete these forecasts we ll run into the same problem Time to fix it Head back to program cs or startup cs if you re using an older version of net and just change AddDbContext to AddDbContextFactory Next head back to your WeatherForecastService cs file and we ll make some changes First we re going to need to initialize the IDbContextFactory field on line Next modify our constructor to make use of the dbContextFactory In each of our methods we re going to instantiate a new instance of DbContext that will only exist for the lifetime of our Task Next update all of the exampleContext references so that our actions use the dbContext we just instantiated That s it You re done head back to fetch data and see it in action Wow such speed much fast You re all set to create the blazingly fast blazor app of your dreams you mouse clicking speed demon SummaryYaya cool tutorial bro I m frustrated and just want this working program cs gt NET startup cs lt NET Turn your existing DbContext into a DbContextFactoryInstantiate a DbContextFactory field in each of your services line Throw it into your constructors Create a new instance of DbContext in each method This will only exist for the lifetime of your task Perform your actions with the newly created DbContext Donezo Code here This is my first time creating a tutorial so all feedback is appreciated If anything is incorrect or there is a better approach please let me know 2022-04-01 14:15:59
海外TECH DEV Community Symfony Station Communiqué - 1 April 2022. A look at Symfony, PHP, and Cybersecurity News! https://dev.to/reubenwalker64/symfony-station-communique-1-april-2022-a-look-at-symfony-php-and-cybersecurity-news-48m5 Symfony Station Communiqué    April A look at Symfony PHP and Cybersecurity News This article originally appeared on Symfony Station Welcome to this week s Symfony Station Communiqué It s your weekly review of the most essential news in the Symfony and PHP development communities Again we cover tech aspects of the war crimes going on in Ukraine and how you can help Take your time and enjoy the items most valuable to you Thanks to Javier Eguiluz and Symfony for sharing our last communiqué in their Week of Symfony Please note that links will open in a new browser window My opinions will be in bold SymfonyAs always we will start with the official news from Symfony Highlight gt This week Symfony development activity focused on fixing bugs especially on the HttpClient component and polishing the new features of the upcoming Symfony version such as the new local switcher Meanwhile SymfonyLive Paris conference is coming in just two weeks and SymfonyCon Disneyland Paris conference announced the last days of its early bird discounts A Week of Symfony March They also say See you next week at SymfonyLive Paris conferenceSymfonyCasts continues their free look at Symfony and the Easy Admin paid courses This week on SymfonyCastsPlatform sh announced We re changing the way development environment URLs are generated Featured ItemThoughtworks notes a lack of thought by some We don t see teams making that trade off analysis blindly accepting the complexity of SPAs by default even when the business needs don t justify it Indeed we ve started to notice that many newer developers aren t even aware of an alternative approach as they ve spent their entire career in a framework like React We believe that many websites will benefit from the simplicity of server side logic and we re encouraged by techniques like Hotwire that help close the gap on user experience SPA by defaultSymfony and StimulusUX people This WeekI know I ve shared many of these but this one is in Spanish Laravel vs Symfony ¿cuál elegir Les Tilleuls coop says in French we re fond of DDD tactical patterns In this structural approach we must divide and prioritize our code into three main layers Infrastructure Domain amp Application However the same idea can be expressed and defined in several areas for example if I design a forum module as well as a real time discussion module In both domains I will have a public template whose class is named Message each using its own namespace App Domain Forum Model Message and App Domain Chat Model Message How do I make resources with the same name coexist from two different domains with API Platform Bernard NG thinks it is preferable to use XML mapping when doing DDD DDD With Symfony  How to configure Doctrine XML MappingMatthius Noback had a different take back in May of DDD and your databaseMichałRomańczuk has a very detailed case study of converting a nightmare legacy project to Symfony by using the Strangler Pattern Strangler Pattern in practiceHatem Ben Yacoub has a review of a TYPO handbook The TYPO Guidebook reviewed Understand and Use TYPO CMS You can learn more about Symfony based CMSs like TYPO and Drupal here Specbee writes Data Files They re what make up your website And how you store and serve them can make all the difference for user experience Obviously cloud storage has changed the way we look at and manage data Today we re going to walk through one of the more popular options for Drupal websites S Simple Storage Service is the cloud storage service provided by AWS Amazon Web Services and it has been providing durable secure and scalable cloud storage for many industries How to store and serve files from Amazon S on your Drupal websiteLouis Nagtegaal shows us how to handle Drupal Migrations in ddev TimelessSponsored ArticleWe published our third sponsored article on Symfony Station exploring how to Implement Code Execution Monitoring for your Symfony apps via Inspector Like all our articles it is now available via audio How to Implement Code Execution Monitoring for your Symfony apps via InspectorAll sponsored articles are for products we have vetted and stand behind We either use them or would do so if they applied to the Symfony Station site PHP This weekThe PHP Foundation published their March Newsletter PHP Foundation NewsletterJonathan Bossenger writes Ever since I discovered how to configure PhpStorm with Xdebug for debugging it s been my go to solution for hunting down difficult to reproduce bugs What I didn t know until very recently was that it s also possible to debug JavaScript using the same setup which blew my mind Debugging React JavaScript and PHP at the Same Time With PhpStormBobby Jack notes Bitmasks are as old as computing itself and admittedly were more useful in the days of memory scarcity and low level programming But there s nothing to stop you using them today when appropriate PHP makes use of bitmasks in many of its built in functions How to use bitmasks in PHPAmplitudo asks Why are we using sessions in PHP Italo Baeza Cabrera writes PHPUnit is a very complete testing suite and with Mockery is even better Most of the assertions are covered data in arrays strings inside strings classes instances and so on Even so PHPUnit is not perfect and for your project you may need a custom assertion For example I just stumbled upon the need to create a simple assertion to check if a class extending other contains a given variable set of methods PHPUnit Making your own assertionThomas Dutrion says Things in computing science are sometimes complex…And I consider myself a fervent proponent of self descriptive code to limit complexity I won t get back on why you should unit test at least some of your code nor will I spend time teaching how to write unit tests in this article I will consider that all of you are ok with these concepts and implementations Examples will be based on a PHPUnit implementation Unit tests and data providers the readable wayCode and Deploy shows us how to Sanitize Input using PHPHicham Ben Kachoud has a quick look at the S in SOLID programming SRP Single Responsibility PrincipleHe also examines the L LSP Liskov Substitution PrincipleAnd regarding SOLID s D Guy Erez explains Dependency Inversion vs Dependency InjectionThis is very useful Joseph Bielawski has A short explanation of the Bus Factor and how to hold its score at safe levels What happens if your development team is hit by a bus Last WeekDimitrios Lytras says While I wasn t paying attention PHP got quite good Modern PHPBrent writes Generics in PHP I know I d want them And I know a lot of developers who agree On the other hand there is a group of PHP programmers maybe even larger that say they don t know what generics are or why they should care I m going to do a series on this blog about generics and PHP We ll start from the beginning but quickly work our way to the more complex topics We ll talk about what generics are why PHP doesn t support them and what s possible in the future Generics in PHP The basicsGolems notes What does this mean in PHP and similar questions are increasingly appearing on the Internet StackOverflow is also bombarded with questions about this variable Let s find out everything related to dynamic PHP access object property with this and break it down with examples Dynamically Access PHP Object Properties with ThisIf you ever need an extensive PHP explainer article to share Visualwebz has you covered A Bit About PHP OtherPlease visit our Support Ukraine page to learn how you can help kick Russia out of Ukraine eventually The cyber response to Russia s War CrimesThe Next Web reports For weeks Russia s military assault on Ukraine has been complemented by full fledged information warfare The Kremlin has propagandized Russian state media and is trying to control the narrative online too We ve seen a bombardment of imposter content circulating   including fake news reports and deep fake videos   while Ukrainians and the rest of the world have scrambled to find ways to tell the real story of the invasion The instant messaging app Telegram has surfaced as one of the most important channels through which to do so But what is it about Telegram that has millions flocking to it amid the chaos Why Ukrainians are turning to Telegram during the warThe New Zealand Herald reports Ukraine has claimed to have uncovered the identities of more than Russian spies in what has been described as a significant blow to President Vladimir Putin s espionage efforts Officials in the war torn country allege the unmasked individuals were carrying out criminal activity across Europe The Main Intelligence Directorate of Ukraine released a slew of personal details of hundreds of alleged agents working for the FSB Russian spies busted in huge blow to Moscow s espionage warDaniel Johnson reveals The real reason Ukraine s information war is so successfulThis was long overdue Kaspersky Named First Russian Company on Security Risk ListThe Washington Post writes As the U S funded broadcaster is forced to shut most of its Russian operations its Web traffic indicates that Russian people are eagerly consuming its stories The Kremlin tries to stifle Radio Free Europe   and its audience surgesLawfare org reports Companies like Meta Google Apple Microsoft Twitter and even TikTok increasingly recognize that they cannot afford to sit geopolitical crises out The war in Ukraine is the most dramatic instance yet of platforms geopolitical turn   their growing engagement with security and geopolitical challenges incidental to their business operations Platforms came a lot more prepared for the war in Ukraine compared to previous major geopolitical inflection points They have coordinated their actions with Western governments and other international actors leading the charge against Russia Platforms at War The Evil Empire Strikes BackRussian hackers appear to be more competent than their generals and soldiers Russian military reportedly hacked into European satellites at start of Ukraine warZDNet reports that Multiple hacking groups are using the war in Ukraine as a lure in phishing attemptsThe Intercept reports Internal chat logs leaked from the notorious Russian ransomware gang Conti reveal unfiltered conversations between ultranationalist hackers in which they repeat Russian President Vladimir Putin s conspiratorial lies about Ukraine discuss the impact of early Western sanctions against their country and make antisemitic comments aboutUkraine s Jewish president Leaked Chats Show Russian Ransomware Gang Discussing Putin s Invasion of Ukraine CybersecurityRichard Forno writes I and other researchers at the University of Maryland Baltimore County have studied the cybersecurity preparedness of the United States over local government entities As part of our analysis working with the International City County Management Association we polled local government chief security officers about their cybersecurity preparedness The results are both expected and alarming Hackers are targeting US local governments   and it s time to fight backMichael Usiagwu shares The recent increase in the severity and sophistication of cyberattacks in recent years may just signal an essential albeit overdue turning point in cybersecurity The clamor by security practitioners concerning the securing of cloud technology by use of technology like Zero Trust by enterprises and organizations has never been louder and it s not hard to see why Zero Trust   The Silver Lining to Cloud Cyber AttacksGitHub notes Securing your projects is no easy task but end to end supply chain security is more top of mind than ever We ve seen bad actors expand their focus to taking over user accounts commonly used dependencies and also build systems Defending against these attacks is hard because there s no one thing you can do to protect your project end to end To help you defend against these attacks we created new guides in our Docs that cover how to get started securing your end to end supply chain How to secure your end to end supply chain on GitHub MoreRachel Lawson rachel norfolk says on Twitter If you are mining bitcoin in Europe then you are using up energy that could otherwise be heating people s homes You are directly helping Putin s invasion of Ukraine by making it harder to apply sanctions on energy coming from Russia On a related note The Guardian reports a campaign called Change the Code Not the Climate and coordinated by Environmental Working Group is calling on bitcoin to change the way bitcoins are mined in order to tackle its outsized carbon footprint The software code that bitcoin uses   known as proof of work    requires the use of massive computer arrays to validate and secure transactions Rival cryptocurrency Etherium is shifting to another system    proof of stake    that it believes will reduce its energy use by Climate groups say a change in coding can reduce bitcoin energy consumption by Wired opines A string of sabotage incidents in open source software is reigniting discussions of how to safeguard projects that underpin digital platforms and networks around the world Many of the recent incidents have been dubbed protestware because they relate to open source developers making code changes to express support for Ukraine amidst Russia s invasion and ongoing attack of the country The Fragile Open Source Ecosystem Isn t Ready for Protestware Docker announces Extensions Docker Extensions PreviewGitHub shows us how to Save time with partial re runs in GitHub ActionsThey also announced CoPilot Labs A VS Code extension for experimental applications of Copilot GitHub Copilot LabsJonas Ulrich writes We re still wasting massive amounts of valuable development cycles in the frontend world by working in silos or by to at least some extent reinventing the wheel for every project Results suffer in the process impacting real world results for users and content creators alike How did we get here and what could a way forward look like How we ve already come a long way and why still so far even Jamstack hasn t been the sole answer either… Unlocking the frontend   a call for standardizing component APIs pt UX Tools notes The term user error implies that it s the user s fault when they do something wrong But in the vast majority of cases the fault actually rests with the designer for having created an interface that is confusing or makes it too easy for the user to make a mistake The solution to user errors is not to blame the user or try to train the mistakes out of them The solution is to redesign the product in such a way that it prevents errors from occurring in the first place How Designers Can Prevent User ErrorsLouis Lazarus says there is a whole bunch of lesser used attributes that I was sure I d forgotten about and probably a whole bunch of attributes I didn t even know existed This post is the result of my research and I hope you ll find some of these useful to you as you build HTML pages in the coming months Those HTML Attributes You Never UseThat s it for this week Thanks for making it to the end of another edition I look forward to sharing next week s Symfony and PHP news with you on Friday Please share this post   Also be sure to join our newsletter list at the bottom of our site s pages Joining gets you each week s communiquéin your inbox a day early And follow us on Twitter at symfonfystation Do you own or work for an organization that would be interested in our promotion opportunities If so please contact us We re in our infancy so it s extra economical   More importantly if you are a Ukrainian company with coding related products we can provide you with free promotion on our Support Ukraine page Or if you know of one get in touch Keep going Symfonistas Author Reuben WalkerFounderSymfony Station 2022-04-01 14:12:53
海外TECH DEV Community How Javascript Generator Functions Work https://dev.to/smpnjn/how-javascript-generators-work-3h14 How Javascript Generator Functions WorkGenerators are functions which can stop halfway through execution and then continue from where it stopped when you call them again Even though they act differently from regular functions they are still callable Let s look at how they work How Generator Functions work in JavascriptLet s look at a normal function first In this example we run a while loop up to and return its value function generator let current while current lt current current return current console log generator If we run this we will get a return value of If we were to move the return statement into the while look it would return instead In fact every time we run it it will return Use Cases for a Generator FunctionThis is great for some use cases but in others it s not so useful Imagine you didn t need to go all the way to every time some users only needed to go to In this case this function is quite inefficient since it does more than what is needed Or maybe we need to pause the while loop when a user does a certain action with this function we can t do that In both cases a function that could stop when we wanted it to is more memory efficient That s where generator functions come in Instead of writing return we can use yield to pause the iteration and return a single value It also remembers where we left off so that we can continue iterating through each item Let s convert our function to a generator function generator let current while current lt current current yield current let runGenerator generator console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false We ve introduced two new concepts to our function first we ve written function instead of function and when we ran our function we used a method called next function and yieldfunction tells Javascript that this function is a generator When we define a generator we have to use the yield keyword to return any values from it We ve used a while loop above and that ultimately defines yield statements but we can also manually type yield multiple times and each time the code will go to the next yield function generator yield yield yield let runGenerator generator console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false yield can also return objects and arrays like so function generator let current while current lt let previous current current current yield current previous let runGenerator generator console log runGenerator console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false next Any generator function you run will have a next method attached to it If you try to run the generator function and console log it without next you ll get the message generator lt suspended gt The next method returns some data on the current state of the generator in the form value value done status where value is the current value the generator is returning and status is whether or not it s completed If we had a smaller generator where we only checked for numbers below done would eventually return true function generator let current while current lt let previous current current current yield current previous let runGenerator generator console log runGenerator console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value undefined done true This lets us easily check if a generator is complete or not Changing the Yield ValueIf we pass a value to next it uses that value in the place of a yield expression For example consider the following function generator let current while current lt current yield current let runGenerator generator console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false Interestingly next only passes this value to yield after the first run So in the first run we get the value current After that yield current is replaced by so every value after is equivalent to This is quite useful for selecting specific items in an iteration Consider another example function generator yield yield yield let runGenerator generator console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value undefined done false In this example the first number runs fine as before Then after yield is replaced by our next value meaning yield yield yield becomes yield yield After that we replace it again so yield yield becomes yield Finally we replace it again yield becomes Since we have no more yields left Generators are IterableGenerators differ from normal functions and objects in that they are iterable That means they can be used with for of allowing us to iterate over them and further control when and where we stop using them For example to iterate over each item in an iterator and return only values we can do this For example function generator let current while current lt let previous current current current yield current previous for const i of generator console log i console logs Example Defining an Infinite Data StructureSince generators only run when we call them we can define a function which returns numbers up to infinity but will only generate one when it is called You can easily see how this could be useful for defining unique user IDs function generator let current while true yield current let runGenerator generator console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false console log runGenerator next Returns value done false ConclusionGenerator functions provide a great memory efficient way to iterate through items whether that be in calculation or from an API With generators you can make memory efficient functions that can be incredibly useful in complex applications I hope you ve enjoyed this article you can find more Javascript content here 2022-04-01 14:10:38
海外TECH DEV Community Dosent kniw yet https://dev.to/abbaskiko2/dosent-kniw-yet-5f54 dosent 2022-04-01 14:09:28
海外TECH DEV Community #66 Days of Data https://dev.to/mrankitgupta/66-days-of-data-44ig Days of Data Learning Python ‍D of daysofdata Today started with NumPy Broadcasting Operations Functions Mathematics Matrix amp Plotting using NumPy Matplotlib ‍Checkout My Days of Data timeline on GithubSay me Hi I ll be glad to connect on Twitter Mr AnkitGuptaGithub MrAnkitGuptaLinkedIn MrAnkitGupta 2022-04-01 14:04:51
海外TECH DEV Community C++ Kirish https://dev.to/rashid0ff/c-kirish-54hl C KirishAB amp amp falsefalsefalsetruefalsefalsefalsetruefalsetruetruetrue OR BinaryLogik true false qiymat qaytaradiKamida ta obekt true bo lsa true qaytaradi 2022-04-01 14:03:31
海外TECH DEV Community scrollTop not working if inside div class="router-container" https://dev.to/idgo/scrolltop-not-working-if-inside-div-classrouter-container-fn7 scrollTop not working if inside div class quot router container quot scrollTop not working if inside div class router container lt div class router container cdkScrollable gt lt router outlet gt lt router outlet gt lt div gt router container overflow auto background color rgb base color white New Component lt mat table table id overview trfList tbl name overview trfList tbl matSortChange sortData event dataSource dataSource matSort class table height input min spacing table flex overview table gt lt Name Column gt lt ng container matColumnDef Name gt lt mat header cell matHeaderCellDef nameSpan sortActionDescription Sort by Name id overview trfList header name btn name overview trfList header name btn gt lt span mat sort header id overview trfList header name lbl name overview trfList header name lbl gt Name lt span gt lt span nameColumnFilterOverlay click onNameFilterIconClicked event id overview trfList header name filter name overview trfList header name filter class overlay icon gt lt span ngIf displayNameFilterIcon isNameFilterOverlayPopUpOpen amp amp filterNameString class mat tbl icon icon filter matTooltipClass tooltip style matTooltipPosition above matTooltip Filter name gt lt span gt lt span ngIf filterNameString class mat tbl icon icon Filter Applied matTooltipClass tooltip style matTooltipPosition above matTooltip Filter name active gt lt span gt lt span gt lt mat header cell gt lt mat cell matCellDef let element let i index gt lt div class vertical context matTooltipClass tooltip style matTooltipPosition above id overview trfList name val i name overview trfList name val i matTooltip element Name gt element Name lt div gt lt mat cell gt lt ng container gt id overview trfList row i name overview trfList row i routerLink view row Code class selected selection isSelected row gt lt div ngIf dataSource data dataSource data length class no method overview mt id overview trfList nodata div name overview trfList nodata div gt lt p id overview trfList nodata lbl name overview trfList nodata lbl innerHtml NoData linebreak gt lt p gt lt div gt lt mat paginator page test paginator id overview trf table pagination name overview trf table pagination pageSize pageSizeOptions showFirstLastButtons true gt lt mat paginator gt ts File public test void let mm document querySelector mat sidenav content mm scrollTop Above code Not workingIf I remove lt div class router container cdkScrollable gt its working but I need this DivMy Requirement scrollTop should work with div 2022-04-01 14:03:05
海外TECH DEV Community API Pexels (API keys + color search) https://dev.to/vikelle/api-pexels-api-keys-color-search-6gn API Pexels API keys color search We are learners in dev school for a data visualization project realized in JavaScript We used the Pexels API but we encountered problems when we followed its documentation This one is rather light and did not work for us Here s how we solved our hang ups Authorization to insert the API key Pexels documentation import createClient from pexels const client createClient YOUR API KEY Our solution headers Authorization YOUR API KEY Search for a photo by color remove the in front of the hexadecimal code in lower case Marine Audrey amp Virginie 2022-04-01 14:01:56
海外TECH DEV Community Basic serverless CRUD Application with CDK for Terraform https://dev.to/pedramha/basic-serverless-crud-application-with-cdk-for-terraform-5g3d Basic serverless CRUD Application with CDK for TerraformIn this post we will build a basic serverless CRUD application on AWS using CDK for Terraform In a previous post we created a simple hello world applicaiton but in this one we persist the data using dynamo db and we add some functionality to the applicaiton Addiditionally we add some security to our API First thing s first let s initialize a CDKTF project Similar to Cloudformation CDK you can run the following command to initialize the project cdktf initThen it will ask you for the language of your choice and name and description for your project I opted for Typescript but you can use whatever language you are comfortable with The cdktf init command will create the project structure for us As you might know Terraform has a very large provider ecosystem To continue with the project you need to specify which provider you want to use To do that open the cdktf json and change the terraformProviders section to terraformProviders aws gt Of course you can use the version of your choice After that you need to run the following command to pull down the providers cdktf get OR npm run get Now we are ready to begin In the main ts file add the following imports import Construct from constructs import App AssetType TerraformAsset TerraformStack TerraformOutput from cdktf import lambdafunction s apigateway iam AwsProvider dynamodb from cdktf provider aws import path require path It is worth mentioning that unlike Cloudformation CDK you will get a compile error if you have unused imports or variables in your code Now add the following code to specify the provider new AwsProvider this aws region eu west You also need to specify where your lambda function is I created a folder called src and used TerraformAsset to import it as follows const asset new TerraformAsset this asset path path resolve dirname src type AssetType ARCHIVE Now we need to create the S Bucket and Object to upload our TerraformAsset function const assetBucket new s SBucket this assetBucket bucket a unique bucket name const lambdaArchive new s SBucketObject this lambdaArchive bucket assetBucket bucket key asset fileName source asset path sourceHash asset assetHash to inform cdktf of changes in file Now we can create our database const db new dynamodb DynamodbTable this db name my table billingMode PAY PER REQUEST hashKey id attribute name id type S Then create the IAM Policy and Role for the lambda function const lambPolicy Version Statement Sid Effect Allow Principal Service lambda amazonaws com Action sts AssumeRole const role new iam IamRole this role assumeRolePolicy JSON stringify lambPolicy name my lambda role new iam IamRolePolicyAttachment this rolePolicy policyArn arn aws iam aws policy service role AWSLambdaBasicExecutionRole role role name we can use a managed policy to access our dbnew iam IamRolePolicyAttachment this rolePolicyDB policyArn arn aws iam aws policy AmazonDynamoDBFullAccess role role name After that we can specify the configuration of our lambda function const lambdaFunc new lambdafunction LambdaFunction this lambdaFunc functionName my lambda function runtime nodejs x handler index handler role role arn sBucket assetBucket bucket sKey lambdaArchive key sourceCodeHash lambdaArchive sourceHash environment variables TABLE NAME db name PRIMARY KEY itemId I added the table name and PK as environment varaibles Then we create an API Gateway to receive HTTP Requests from the Internet We can also add the resources to our API and define HTTP Methods const restApi new apigateway ApiGatewayRestApi this restApi name my rest api description my rest api const resourceApi new apigateway ApiGatewayResource this resourceApi restApiId restApi id parentId restApi rootResourceId pathPart my resource const postApi new apigateway ApiGatewayMethod this postApi restApiId restApi id resourceId resourceApi id httpMethod POST authorization NONE const getApi new apigateway ApiGatewayMethod this getApi restApiId restApi id resourceId resourceApi id httpMethod GET authorization NONE const putApi new apigateway ApiGatewayMethod this putApi restApiId restApi id resourceId resourceApi id httpMethod PUT authorization NONE const delApi new apigateway ApiGatewayMethod this delApi restApiId restApi id resourceId resourceApi id httpMethod DELETE authorization NONE We also need to add API integrations to our methods as follows new apigateway ApiGatewayIntegration this apiIntegration restApiId restApi id resourceId resourceApi id httpMethod postApi httpMethod integrationHttpMethod POST type AWS PROXY uri lambdaFunc invokeArn new apigateway ApiGatewayIntegration this apiIntegration restApiId restApi id resourceId resourceApi id httpMethod getApi httpMethod integrationHttpMethod POST type AWS PROXY uri lambdaFunc invokeArn new apigateway ApiGatewayIntegration this apiIntegration restApiId restApi id resourceId resourceApi id httpMethod putApi httpMethod integrationHttpMethod POST type AWS PROXY uri lambdaFunc invokeArn new apigateway ApiGatewayIntegration this apiIntegration restApiId restApi id resourceId resourceApi id httpMethod delApi httpMethod integrationHttpMethod POST type AWS PROXY uri lambdaFunc invokeArn Note that integrationHttpMethod is always set to POST Finally you need to create a LambdaPermission Policy to allow the API Gateway to invoke our Lambda Function new lambdafunction LambdaPermission this apig lambda statementId AllowExecutionFromAPIGateway action lambda InvokeFunction functionName lambdaFunc functionName principal apigateway amazonaws com sourceArn restApi executionArn Now we have our API and Lambda Function Integrations We can go ahead and deploy our API into a Stage However we should secure our API because at this point it will be reachable from the Internet So we create a deployment for our API and add a stage const apiDepl new apigateway ApiGatewayDeployment this deployment restApiId restApi id dependsOn lambdaFunc const apiStage new apigateway ApiGatewayStage this stage restApiId restApi id stageName test deploymentId apiDepl id dependsOn apiDepl I also added the dependsOn property to make sure certain resources will be created before others Now we can create an API Key for our API const apiKey new apigateway ApiGatewayApiKey this apiKey name my api key description my api key enabled true After that we need to create a usage plan and attach the api key to it The Usage plan gives you a lot of control over how your API is used const usagePlan new apigateway ApiGatewayUsagePlan this usagePlan name my usage plan description my usage plan throttleSettings burstLimit rateLimit apiStages apiId restApi id stage apiStage stageName dependsOn apiKey new apigateway ApiGatewayUsagePlanKey this usagePlanKey keyId apiKey id keyType API KEY usagePlanId usagePlan id dependsOn usagePlan Note that I limited the rate and burst limit to make sure the costs will be in control If you like to see the endpoint of your API and test it curl or postman you can use the following command new TerraformOutput this apiUrl value apiStage invokeUrl description API URL Don t forget to add your lambda function in the src folder create a file called index ts and add the functionality that you want I only wanted to send a hello world response import as AWS from aws sdk import v as uuidv from uuid const db new AWS DynamoDB DocumentClient apiVersion region eu west const TABLE NAME process env TABLE NAME const PRIMARY KEY process env PRIMARY KEY export const handler async event any Promise lt any gt gt if event httpMethod POST try if event body return statusCode body invalid request you are missing the parameter body const item typeof event body object event body JSON parse event body item PRIMARY KEY uuidv const params TableName TABLE NAME Item item return await db put params promise catch error return statusCode body error else if event httpMethod GET get all items try const params TableName TABLE NAME const resp await db scan params promise return statusCode body JSON stringify resp Items catch error return statusCode body error else if event httpMethod PUT try if event body return statusCode body invalid request you are missing the parameter body const item typeof event body object event body JSON parse event body const params TableName TABLE NAME Item item return await db put params promise catch error return statusCode body error else if event httpMethod DELETE try if event pathParameters return statusCode body invalid request you are missing the parameter pathParameters const params TableName TABLE NAME Key PRIMARY KEY event pathParameters PRIMARY KEY return await db delete params promise catch error return statusCode body error I will explain this lambda function in a separate post You can create this lambda function without packaging it But I d like to package it before deploying to make sure that I have all the dependencies that I need So I create a file called package json and add the following name lambda crud dynamodb version description Lambdas to do CRUD operations on DynamoDB private true license MIT devDependencies types node types uuid dependencies aws sdk uuid Regarding deploying this code you will find your way if you have used CDK Cloudformation or Terraform HCL You can run the following commands to deploy the project npm run buildcdktf plan OR cdktf synthcdktf apply OR cdktf deployThe youtube video Github 2022-04-01 14:00:50
海外TECH Engadget JackRabbit review: If a scooter and an e-bike had a baby https://www.engadget.com/jack-rabbit-ebike-scooter-review-144537677.html?src=rss JackRabbit review If a scooter and an e bike had a babyIn a world where most e bikes are trying to blend in JackRabbit well…stands out In fact it s unique enough that you re either going to love it or at the very least be curious As a pedal free e bike it s aimed at those in the market for a scooter rather than an electrified road bike But unlike a scooter the JackRabbit can handle more than just paved sidewalk while remaining about as portable All this to say the JackRabbit bike is a curious proposition but don t let its quirky looks deceive you First let s back up a little The JackRabbit is an electronic bike but it s categorized as a scooter in some jurisdictions Thanks in part to its size at x x inches x x cm it s comically helpfully small There are no pedals chains or gears it s throttle mode only like a tiny electric motorbike At lbs Kg it s also pretty light The advertised range is miles the top speed is mph delivered by a W motor Wh battery combo and it will cost you new in a range of four spiffy colors As alluded to above comparing the JackRabbit to most other e bikes doesn t really make sense This is something you ll want to ride for short to moderate distances or for that famous last mile It can fold down to a degree you can pop out the handlebars and invert the front wheel at which point it s only slightly less portable than most scooters That said lugging it around is a little bit different it doesn t fold down as small but you can also wheel it over up things instead of just carrying it Maybe you really just wanted a bike that did all the work for you in which case that is this For example if your commute is up to five miles each way across town and you normally ride a bike the JackRabbit could be a viable alternative if you want something that can cut through traffic but won t mean showing up at the office needing a shower Oh assuming you re under that is the maximum height according to the company Or if like me you live in an apartment block and maneuvering a full size bike downstairs with a small elevator is just straight up hassle the JackRabbit is a pure delight No kidding I have to stand a regular bike on end and hope no one s waiting downstairs as I barge the door open with the front wheel With the JackRabbit I can actually just ride into and straight out of the elevator if I want James Trew EngadgetThe first time you take the JackRabbit out the center of gravity takes a little getting used to Especially once you hit higher speeds which can make the ride feel a little invigorating in the most danger fun sense of the word But it doesn t take long before you re settled in and starting to think about what street obstacles you can try to bunny hop off of over From there on out the ride is pretty smooth though there are a few things to keep in mind While the top speed is mph it s hard to get there in anything other than optimal conditions The acceleration isn t slow but once you get to around mph it tails off enough that you need a clear road ahead to hit that top speed This is still an improvement on the previous JackRabbit that seemed to take even longer to get there Inclines are also not the JackRabbit s forte If you hit a modest gradient at a good speed you shouldn t have any problems but once things get steeper and or you hit them slower you might have to help finish the job with your feet like a kid on a balance bike It s not the most gracious thing but you shouldn t have to get off and push unless you live somewhere like San Francisco That said this latest JackRabbit does a much better job of the model before it so that s something Some other quirks of the JackRabbit s size include your feet occasionally rubbing against the wheels tight turns definitely require a little more forethought and I do wonder the addition of footrest pegs on the front wheel too might give an alternative riding style almost putting you in a slight “chopper seating position But as much as the unusual dimensions of the JackRabbit present some minor challenges they are also what makes it so much fun to ride There s something about its slightly “dirt bike aesthetic that makes you want to deviate from the well paved sidewalk and into more adventurous terrain I live near a very long park that has everything from railway sleepers to block paved cycle paths to small dirt tracks and gravel the JackRabbit loves ate them all up I also discovered that it can fit in the back of my small hatchback without any folding it sits perfectly with one wheel behind each seat making it easily transportable too You can fold it down somewhat if you need to The handlebars pop out easily and there s a clip to hold them while the front wheel folds inwards It shrinks the profile down enough if you either want to take up less space on the metro or simply stow it somewhere when not in use It actually didn t take long before I found myself just taking this thing out for fun rather than as a means of getting somewhere Although it had already usurped my scooter and regular size e bike as a means of transportation I was now just using it for the fun of the ride too And then that s when it happened James Trew EngadgetThree LEDs to indicate battery power is not enough I found this out about a mile away from home where with one shiny LED remaining on the handlebar mounted throttle the JackRabbit suddenly lost most of its power I pressed my thumb down in vain only to remain at a crawl I had been having so much fun I had drained the battery and the three LED power indicator clearly isn t detailed enough to let you know you re really in the danger zone Luckily where I live is very flat and I was able to push my way home without too much trouble It turns out you can pump like a skateboard with one foot if you really don t want to get off and walk this thing home Worst of all I had mentally calculated that I was well within the claimed mile range and tracing the route out on Google Maps suggests it was a shade over six miles I subsequently discovered that each LED appears to remain on as you accelerate until it s about to drop down to the next one At which point the LED remains lit unil you apply the throttle and it dims This is a way of letting you know you re at the lower end of that section of the battery indicator So it s slightly more informative than just three LEDs but it s still not a great indicator of remaining time or range I spoke with JackRabbit about this and we did some back and forth which included checking the battery with a voltmeter to make sure it wasn t faulty The company s own testing is like most of these things done without going full speed and with a payload a bit lighter than me it seems So my full throttle approach and extra weight seem to be enough to drag down the range somewhat For me it s less about the actual range although that s a factor but more about having detailed information Most scooters will give you either a numerical percentage of battery remaining or a higher resolution graphical indicator So for me it s more about not having the information I needed to know I was about to empty the proverbial tank James Trew EngadgetThankfully the batteries are removable and they are portable enough that you could definitely slip a spare into a backpack But at each that s a reasonable spend just to relieve some anxiety It s also slightly frustrating that if you have the previous JackRabbit the battery from that won t work on the latest model despite being nearly identical If there was another small addition that might help here it would be regenerative braking Right now the JackRabbit doesn t have it but with just one rear brake to speak of it seems something that might be easy to implement and enable a modest saving of power especially as most inner city commutes require a fair amount of stop starting anyway The above might sound like there are still quite a few areas for improvement but the JackRabbit remains about the most enjoyable electric ride I ve tried in a long while It s form factor is going to sing to some users while being a little impractical for others But that s true of scooters bikes and any other form of transportation The JackRabbit just presents another option I would also strongly consider how many inclines are on your route For the most part cities with moderate inclines they shouldn t present a challenge but hillier locations won t be as much fun But if you don t want need a full size bike and you find scooters uncomfortable or impractical this is a refreshing alternative Throw in the fact that you can also cover terrain that scooters can t or fit places where most bikes won t and the JackRabbit really does make a good if specific case for itself The fact that it s wildly fun is just an added bonus 2022-04-01 14:45:37
海外TECH Engadget Washington is first state to guarantee pay and benefits for Uber and Lyft drivers https://www.engadget.com/washington-state-uber-lift-pay-guarantee-141640438.html?src=rss Washington is first state to guarantee pay and benefits for Uber and Lyft driversWashington State legislation guaranteeing pay and benefits for ride hail workers has become a practical reality Reutersreports Governor Jay Inslee has signed into law a measure setting minimum pay guarantees of per mile and cents per minute with trips costing at least each Drivers at Uber Lyft and other companies will also have benefits like paid sick leave access to workers compensation and family medical leave They can also appeal if they believe they ve been unfairly terminated The law has garnered support from both labor organizers and companies The Washington Drivers Union billed it as an quot unprecedented victory quot that would reverse years of shrinking pay and improve the overall quality of life Uber said in a statement that the law quot decisively quot gave drivers the mix of independence and safeguards they were asking for while Lyft said this was a quot win quot that emerged when unions politicians and companies quot worked together quot There are concerns the law strips power away however It declares that drivers for ride hailing apps aren t employees potentially limiting access to further benefits and more consistent hours The law also bars cities and counties from applying additional regulations beyond those in effect Seattle will still offer higher pay per mile cents per minute and at least per trip but companies like Uber and Lyft have effectively limited the scope of regulations they might face This is still the first state level law to set pay standards for gig based rides though Until now only New York City and Seattle had established minimums in the country This could make ride hail work viable for considerably more people and might prompt other states to enact their own guarantees 2022-04-01 14:16:40
海外科学 NYT > Science Cannabis for Better Sex? Here’s What the Science Says. https://www.nytimes.com/2022/04/01/well/live/marijuana-sex.html difference 2022-04-01 14:53:08
海外科学 NYT > Science As Gas Prices Soar, Biden’s Climate Ambitions Sputter https://www.nytimes.com/2022/04/01/climate/biden-climate-change.html As Gas Prices Soar Biden s Climate Ambitions SputterRising costs at the pump war in Ukraine an emboldened fossil fuel industry and stalled legislation have imperiled President Biden s climate agenda 2022-04-01 14:35:07
金融 金融庁ホームページ 「中小企業の事業再生等に関するガイドライン」Q&Aについて公表しました。 https://www.fsa.go.jp/news/r3/ginkou/20220401.html qampa 2022-04-01 15:30:00
金融 金融庁ホームページ つみたてNISA取扱金融機関一覧について更新しました。 https://www.fsa.go.jp/policy/nisa2/about/tsumitate/target/index.html 対象商品 2022-04-01 15:00:00
ニュース BBC News - Home Energy price: Bill shock for millions as rises hit https://www.bbc.co.uk/news/business-60943192?at_medium=RSS&at_campaign=KARANGA bills 2022-04-01 14:51:13
ニュース BBC News - Home P&O Ferries faces criminal probe over sackings https://www.bbc.co.uk/news/business-60953832?at_medium=RSS&at_campaign=KARANGA recent 2022-04-01 14:11:31
ニュース BBC News - Home Just Stop Oil protests: Terminal operations suspended and arrests made https://www.bbc.co.uk/news/uk-england-60951403?at_medium=RSS&at_campaign=KARANGA england 2022-04-01 14:40:40
ニュース BBC News - Home Child Q: Met Police changes strip-search policy in two London boroughs https://www.bbc.co.uk/news/uk-england-london-60956799?at_medium=RSS&at_campaign=KARANGA london 2022-04-01 14:52:47
ニュース BBC News - Home World Cup 2022: How has Qatar treated stadium workers? https://www.bbc.co.uk/news/world-60867042?at_medium=RSS&at_campaign=KARANGA facilities 2022-04-01 14:23:22
ニュース BBC News - Home Laura Kenny & Katie Archibald lead Great Britain at Track Nations Cup https://www.bbc.co.uk/sport/cycling/60957151?at_medium=RSS&at_campaign=KARANGA glasgow 2022-04-01 14:09:40
北海道 北海道新聞 アベノマスク5億円かけ配布 5月末までに希望者へ 厚労省 https://www.hokkaido-np.co.jp/article/664414/ 新型コロナウイルス 2022-04-01 23:33:57
北海道 北海道新聞 NY株、反発 https://www.hokkaido-np.co.jp/article/664517/ 工業 2022-04-01 23:31:00
北海道 北海道新聞 シカ肉ゴロゴロ入ったカレー缶詰 足寄の野生肉専門店、陸別の旅館と商品化 https://www.hokkaido-np.co.jp/article/664459/ 陸別 2022-04-01 23:18:03
北海道 北海道新聞 避難民30人、政府専用機同乗へ ポーランド派遣の林外相帰国で https://www.hokkaido-np.co.jp/article/664510/ 政府専用機 2022-04-01 23:12:00

コメント

このブログの人気の投稿

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

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

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)