投稿時間:2023-08-15 12:23:05 RSSフィード2023-08-15 12:00 分まとめ(25件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… YouTube Premium向け動画品質「1080p Premium」、Android版でも展開開始 https://taisy0.com/2023/08/15/175362.html ppremium 2023-08-15 02:20:01
IT 気になる、記になる… Anker、Lightning端子内蔵モバイルバッテリー「Anker Nano Power Bank(12W, Built-In Lightning Connector)」を発売 ー 10%オフセールも https://taisy0.com/2023/08/15/175358.html anker 2023-08-15 02:13:06
ROBOT ロボスタ テレビ山梨の公認VTuber 山奈しずく YouTube配信デビュー!メディアDXで地域の魅力を世界発信「ずくちゃん って呼んでほしい」 https://robotstart.info/2023/08/15/uty-vtuber-yamanashizuku-debut.html 2023-08-15 02:18:55
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] あると助かる使い捨てプラスチック製品 3位「食品トレイ」、2位「無料ポリ袋」、1位は? https://www.itmedia.co.jp/business/articles/2308/15/news062.html itmedia 2023-08-15 11:09:00
IT ITmedia 総合記事一覧 [ITmedia News] PayPal、シュルマンCEOの後任にIntuit幹部のアレックス・クリス氏を任命 https://www.itmedia.co.jp/news/articles/2308/15/news091.html intuit 2023-08-15 11:07:00
IT 情報システムリーダーのためのIT情報専門サイト IT Leaders エクサウィザーズ、生成AI製品の事業を分割、新会社「Exa Enterprise AI」を2023年10月に設立 | IT Leaders https://it.impress.co.jp/articles/-/25227 エクサウィザーズ、生成AI製品の事業を分割、新会社「ExaEnterpriseAI」を年月に設立ITLeadersエクサウィザーズ本社東京都港区は年月日、生成AIサービスの開発、販売に特化した新会社「ExaEnterpriseAI」本社東京都港区を年月日に設立すると発表した。 2023-08-15 11:52:00
AWS AWS Mobile Blog AWS SAM now supports GraphQL Applications with AWS AppSync https://aws.amazon.com/blogs/mobile/aws-sam-now-supports-graphql-applications-with-aws-appsync/ AWS SAM now supports GraphQL Applications with AWS AppSyncWe are pleased to announce that AWS Serverless Application Model AWS SAM now supports building serverless GraphQL APIs with AWS AppSync AWS SAM provides a short hand syntax for defining AWS serverless resources AWS AppSync enables developers to connect their applications to data and events with secure serverless and performant GraphQL and Pub Sub APIs GraphQL APIs … 2023-08-15 02:34:29
js JavaScriptタグが付けられた新着投稿 - Qiita ReactとNext.jsの違いについて https://qiita.com/omo_taku/items/dab874780a9aac729158 nextjs 2023-08-15 11:17:38
Linux Ubuntuタグが付けられた新着投稿 - Qiita ubuntu環境でコマンドラインから画面録画をするには`recordmydesktop`を使えば良さそうという備忘メモ https://qiita.com/seigot/items/704dea812b96a45a575f recordmydesktop 2023-08-15 11:45:36
Ruby Railsタグが付けられた新着投稿 - Qiita TechStreamのコース紹介 https://qiita.com/protechyamada/items/daa470640b0b185c79fb techs 2023-08-15 12:00:18
技術ブログ Developers.IO ずんだもんの英単語読み入力をAIで賄ってみる #ChatGPT https://dev.classmethod.jp/articles/cover-english-accent-for-zundamon-by-chatgpt/ chatgpt 2023-08-15 02:50:11
技術ブログ Developers.IO CDK(Cloud Development Kit) Workshopをやってみた。 https://dev.classmethod.jp/articles/cdkcloud-development-kit-workshop/ cdkworkshop 2023-08-15 02:23:53
海外TECH DEV Community “Talckatoo: Your Real-Time Multilingual Chat Solution Built with SocketIO, Express.js, and React!” — Part 2 https://dev.to/miminiverse/talckatoo-your-real-time-multilingual-chat-solution-built-with-socketio-expressjs-and-react-part-2-2h35 “Talckatoo Your Real Time Multilingual Chat Solution Built with SocketIO Express js and React ーPart In the previous part I provided an overview of our powerful chat application which offers real time multilingual translations In this part we will delve into the backend how we set up all the routes and also how we use socketIO to get real time functionalities Our application revolves around three essential models User Conversation and Message In essence our route structure is designed to achieve our ultimate goal of displaying messages This involves a series of HTTP requests Making a POST request to authenticate and log in the userMaking a GET request to get comprehensive information about other users Making a GET to fetch both the conversation and associated messagesLet s start with the User model Within this model each user will maintain a list of their conversations with others Additionally users will be able to set their preferred translated language during sign up thus enhancing the multilingual communication experience const UserSchema new Schema lt Iuser gt userName type String unique true required true minLength email type String required true unique true validate validator isEmail please enter a valid email address password type String minlength conversations type Schema Types ObjectId ref Conversation profileImage public id String url String language type String welcome type String Moving on to the Conversation model it serves as a container for all the messages exchanged within a particular conversation Moreover the model also associates the users who are part of that conversation This setup ensures that messages are organized and accessible within the context of their relevant discussions while maintaining a clear link to the users involved const conversationSchema new Schema lt Iconversation gt messages type Schema Types ObjectId ref Message users type Schema Types ObjectId ref User timestamps true Lastly let s look at the Message model An important aspect of this model is that it includes the sender s information This addition proves invaluable in distinguishing between the sender and recipient of each message which in turn facilitates the seamless configuration of APIs and enhances the overall communication process const messageSchema new Schema lt Imessage gt message type String minlength maxlength sender type Schema Types ObjectId ref User required true voiceNote public id String url String timestamps true Moving forward to the controllers where we ll navigate through the implementation of various routes While I ll skip detailing the signup login and user profile update routes I d like to highlight the user related routes Specifically we ll discuss the process of fetching users from our database One of the very first questions how can we display the friend lists In response we devised a strategic approach categorization of users into two distinct groups those who are logged in and have never been contacted and those with whom you ve engaged in previous conversations This segmentation enhances the user experience and helps organize interactions effectively exports getUsers catchAsync async req Request res Response next NextFunction gt const userId any req user const currentUser await User findOne id userId const populateOptions path conversations select id createdAt updatedAt const contactedUsers await User find id ne currentUser id conversations in currentUser conversations select id userName conversations profileImage language populate populateOptions contactedUsers forEach user any gt user conversations user conversations filter conversation any gt return currentUser conversations includes conversation id const modifiedUsers contactedUsers map user any gt return id user id userName user userName profileImage user profileImage conversation user conversations conversations undefined language user language modifiedUsers sort a any b any gt if a conversation updatedAt getTime b conversation updatedAt getTime return if a conversation updatedAt getTime b conversation updatedAt getTime return return const uncontactedUsers await User find id ne currentUser id conversations nin currentUser conversations select id userName profileImage language if contactedUsers length lt amp amp uncontactedUsers length lt res status json status Success message There are currently no users res status json status Success users contactedUsers modifiedUsers uncontactedUsers From this point onward we can retrieve the unique conversation IDs and seamlessly showcase each individual conversation which facilitates the comprehensive display of all messages that our logged in user has exchanged with others exports getUserConversation catchAsync async req Request res Response next NextFunction gt const conversationId req params const populateOptions path users select userName profileImage language path messages select message sender createdAt voiceNote const conversation await Conversation findOne id conversationId populate populateOptions if conversation throw new AppError This conversation does not exist res status json status Success conversation Equally crucial is the route dedicated to creating new messages a feature that defines the essence of our application Through this functionality users can receive translated versions of their messages aligned with their chosen language preference in their profiles Messages are classified into two types text messages and translated voice messages with the latter being stored using Cloudinary to store URLs for easy retrieval and playback exports createMessage catchAsync async req Request res Response next NextFunction gt const message text to from targetLanguage voiceToVoice voiceTargetLanguage req body const target targetLanguage targetLanguage en if text to from throw new AppError Invalid Input Please try again if to from throw new AppError You can t send a message to yourself const options method POST url process env TRANSLATE URL headers content type application json X RapidAPI Key process env TRANSLATE API KEY X RapidAPI Host process env API HOST data text target const response await axios request options let translate string if response data result ori en amp amp target en translate else translate n response data result text if voiceToVoice const message await Message create message text translate sender from let conversation await Conversation findOneAndUpdate users all from to push messages message id if conversation conversation await Conversation create messages message id users from to await User findOneAndUpdate id from push conversations conversation id await User findOneAndUpdate id to push conversations conversation id res status json status Success message conversation else const encodedParams new URLSearchParams encodedParams set src translate encodedParams set hl voiceTargetLanguage encodedParams set r encodedParams set c mp encodedParams set f khz bit mono encodedParams set b true const options method POST url process env URL params key process env VOICE PARAMS KEY headers content type application x www form urlencoded X RapidAPI Key process env VOICE API KEY X RapidAPI Host process env VOICE API HOST data encodedParams const response await axios request options const audioData response data const decodedData Buffer from audioData base Create a temporary file to store the audio data const tempFilePath temp audio mp fs writeFileSync tempFilePath decodedData const uploadOptions resource type video format mp folder voice notes cloudinary uploader upload large tempFilePath uploadOptions async error any result any gt Delete the temporary file fs unlinkSync tempFilePath if error console log error else const public id url result const message await Message create voiceNote public id url sender from let conversation await Conversation findOneAndUpdate users all from to push messages message id if conversation conversation await Conversation create messages message id users from to await User findOneAndUpdate id from push conversations conversation id await User findOneAndUpdate id to push conversations conversation id res status json status Success message conversation If you want to send a voice message you can use the route below exports createVoiceNote catchAsync async req Request res Response next NextFunction gt const form new multiparty Form form parse req async err any fields any files any gt const to from fields if to from throw new AppError Invalid Input Please try again if to from throw new AppError You can t send a message to yourself if files audio const data await cloudinary uploader upload files audio path resource type video folder voice notes const public id url data const message await Message create voiceNote public id url sender from let conversation await Conversation findOneAndUpdate users all from to push messages message id if conversation conversation await Conversation create messages message id users from to await User findOneAndUpdate id from push conversations conversation id await User findOneAndUpdate id to push conversations conversation id res status json message And finally here comes the best part infusing the app with real time capabilities through SocketIO Before delving into the mechanics let s unravel the rationale behind employing SocketIO and the reasons that set it apart from traditional real time communication implemented through REST APIs REST APIs operate in a stateless manner treating each GET or POST request in isolation without maintaining any continuous connection →In our context where we re striving for REAL TIME updates using REST APIs would necessitate incessant requests to the server even if there might not be new messages This approach is resource intensive and inefficient Enter SocketIO empowering us to establish a persistent connection between two users that remains active until the users opt to disconnect The server in turn automatically updates and pushes new messages to the users without necessitating a site reload or any additional actions io on connection socket Socket gt socket on addUser userId any gt onlineUsers set userId socket id io emit getUsers Array from onlineUsers socket on sendMessage data any gt const sendUserSocket onlineUsers get data to if sendUserSocket io to sendUserSocket emit getMessage data socket on disconnect gt Remove the disconnected socket from onlineUsers map for const userId socketId of onlineUsers if socketId socket id onlineUsers delete userId break io emit getUsers Array from onlineUsers Certainly let s break down the process Firstly we ll initiate the connection using the io on connection method a built in feature of SocketIO The following code snippet helps us track users who are online Whenever a user connects to our app by logging in their ID is sent from the front end to SocketIO and we manage them through a Map It s crucial to use a Map to avoid user duplication When we emit the data back to the front end we ll also need to convert it to an array as Maps and Sets need manual serialization for compatibility const onlineUsers new Map socket on addUser userId any gt onlineUsers set userId socket id io emit getUsers Array from onlineUsers The nextfour lines of code are crucial for enabling real time messaging in our application As a quick recap we have a Map named onlineUsers that keeps track of connected users Each user has a unique socket ID associated with them When a user successfully connects they receive a socket ID Here s how the messaging process works When you want to send a message to a specific user you send the recipient s ID from the front end to the backend as data With the recipient s ID you can retrieve their socket ID from the onlineUsers map Once you have the recipient s socket ID you emit the message to that socket ID which effectively sends the message to the intended recipient This process ensures that messages are sent directly to the recipient in real time Here s the basic structure of how this works socket on sendMessage data any gt const sendUserSocket onlineUsers get data to if sendUserSocket io to sendUserSocket emit getMessage data Lastly when a user disconnects from the app we can use socket on disconnect to remove them from the list of online users and emit the updated list to the frontend to reflect the current online status of users socket on disconnect gt Remove the disconnected socket from onlineUsers map for const userId socketId of onlineUsers if socketId socket id onlineUsers delete userId break io emit getUsers Array from onlineUsers You can find comprehensive information about error handling CORS configuration database integration and the array of packages employed throughout our project by exploring our repository at Stay tuned for Part on how we ve built the front end aspects of our project 2023-08-15 02:36:16
海外TECH DEV Community 9. Zinx Connection Management and Property Setting https://dev.to/aceld/9-zinx-connection-management-and-property-setting-28ha Zinx Connection Management and Property Setting lt Building Basic Services with Zinx Framework gt lt Zinx V Simple Connection Encapsulation and Binding with Business gt lt Design and Implementation of the Zinx Framework s Routing Module gt lt Zinx Global Configuration gt lt Zinx Message Encapsulation Module Design and Implementation gt lt Design and Implementation of Zinx Multi Router Mode gt lt Building Zinx s Read Write Separation Model gt lt Zinx Message Queue and Task Worker Pool Design and Implementation gt lt Zinx Connection Management and Property Setting gt In this chapter we will add connection limitations to the Zinx framework If the number of client connections exceeds a certain threshold Zinx will reject new connection requests in order to ensure timely response for existing connections Additionally we will introduce connection properties to Zinx allowing developers to associate business specific parameters with connections for easy access during business processing Connection ManagementWe need to create a connection management module for Zinx which consists of an abstract layer and an implementation layer We ll start by implementing the abstract layer in the iconnmanager go file located in the zinx ziface directory zinx ziface iconnmanager gopackage ziface Connection management abstract layer type IConnManager interface Add conn IConnection Add a connection Remove conn IConnection Remove a connection Get connID uint IConnection error Get a connection using the connection ID Len int Get the current number of connections ClearConn Remove and stop all connections The IConnManager interface defines the following methods Add Add a connection to the connection manager Remove Remove a connection from the connection manager This does not close the connection it simply removes it from the management Get Retrieve a connection object based on the connection ID Len Get the total number of connections managed by the connection manager ClearConn Remove all connections from the manager and close them Next we ll create the implementation layer for IConnManager in the connmanager go file in the zinx znet directory zinx znet connmanager gopackage znetimport errors fmt sync zinx ziface Connection manager module type ConnManager struct connections map uint ziface IConnection Map to hold connection information connLock sync RWMutex Read write lock for concurrent access to the map The ConnManager struct contains a connections map that stores all the connection information The key is the connection ID and the value is the connection itself The connLock is a read write lock used to protect concurrent access to the map The constructor for ConnManager initializes the map using the make function zinx znet connmanager go Create a connection manager func NewConnManager ConnManager return amp ConnManager connections make map uint ziface IConnection The Add method which adds a connection to the manager is implemented as follows zinx znet connmanager go Add a connectionfunc connMgr ConnManager Add conn ziface IConnection Protect shared resource map with a write lock connMgr connLock Lock defer connMgr connLock Unlock Add the connection to ConnManager connMgr connections conn GetConnID conn fmt Println Connection added to ConnManager successfully conn num connMgr Len Since Go s standard library map is not thread safe we need to use a lock to protect concurrent write operations Here we use a write lock connLock to ensure mutual exclusion when modifying the map The Remove method which removes a connection from the manager is implemented as follows zinx znet connmanager go Remove a connectionfunc connMgr ConnManager Remove conn ziface IConnection Protect shared resource map with a write lock connMgr connLock Lock defer connMgr connLock Unlock Remove the connection delete connMgr connections conn GetConnID fmt Println Connection removed ConnID conn GetConnID successfully conn num connMgr Len The Remove method simply removes the connection from the map without stopping the connection s business processing The Get and Len methods are implemented as follows zinx znet connmanager go Get a connection using the connection IDfunc connMgr ConnManager Get connID uint ziface IConnection error Protect shared resource map with a read lock connMgr connLock RLock defer connMgr connLock RUnlock if conn ok connMgr connections connID ok return conn nil else return nil errors New connection not found Get the current number of connectionsfunc connMgr ConnManager Len int return len connMgr connections The Get method uses a read lock connLock RLock to allow concurrent read access to the map ensuring data consistency If a connection with the given ID is found it is returned otherwise an error is returned The ClearConn method is implemented as follows zinx znet connmanager go Remove and stop all connectionsfunc connMgr ConnManager ClearConn Protect shared resource map with a write lock connMgr connLock Lock defer connMgr connLock Unlock Stop and remove all connections for connID conn range connMgr connections Stop the connection conn Stop Remove the connection delete connMgr connections connID fmt Println All connections cleared successfully conn num connMgr Len The ClearConn method stops each connection s business processing by calling conn Stop and then removes all connections from the map Integrating Connection Management Module into Zinx Adding ConnManager to ServerWe need to add the ConnManager to the Server struct and initialize it in the server s constructor The Server struct in the zinx znet server go file will have a new member property called ConnMgr which is of type ziface IConnManager zinx znet server go Server is a server service class implementing the IServer interfacetype Server struct Server name Name string IP version e g tcp or other IPVersion string IP address to bind the server to IP string Port to bind the server to Port int Message handler for binding MsgID and corresponding processing methods MsgHandler ziface IMsgHandle Connection manager for the server ConnMgr ziface IConnManager In the server s constructor NewServer we need to initialize the ConnMgr zinx znet server go NewServer creates a server instancefunc NewServer ziface IServer utils GlobalObject Reload s amp Server Name utils GlobalObject Name IPVersion tcp IP utils GlobalObject Host Port utils GlobalObject TcpPort MsgHandler NewMsgHandle ConnMgr NewConnManager Create a ConnManager return s The NewServer function creates a new server instance and initializes the ConnMgr property To provide access to the ConnMgr from the server we need to add a method GetConnMgr to the IServerinterface in the zinx ziface iserver go file zinx ziface iserver gotype IServer interface Start the server Start Stop the server Stop Serve the business services Serve Register a router business method for the current service used by client connection processing AddRouter msgID uint router IRouter Get the connection manager GetConnMgr IConnManager The GetConnMgr method should return the ConnMgr property of the server zinx znet server go GetConnMgr returns the connection managerfunc s Server GetConnMgr ziface IConnManager return s ConnMgr By implementing the GetConnMgr method we provide a way to access the connection manager from the server Because the connection Connection sometimes needs access to the connection manager ConnMgr in the server Server we need to establish a mutual reference relationship between the Server and Connection objects In the Connection struct we will add a member called TcpServer which represents the server that the current connection belongs to Add the TcpServer member to the Connection struct in the zinx znet connection go file as follows zinx znet connection gotype Connection struct The server to which the current connection belongs TcpServer ziface IServer Add this line to indicate the server to which the connection belongs The TCP socket of the current connection Conn net TCPConn The ID of the current connection also known as SessionID globally unique ConnID uint The closing state of the current connection isClosed bool The message handler that manages MsgID and corresponding processing methods MsgHandler ziface IMsgHandle The channel that informs that the connection has exited stopped ExitBuffChan chan bool The unbuffered channel used for message communication between the reading and writing goroutines msgChan chan byte The buffered channel used for message communication between the reading and writing goroutines msgBuffChan chan byte By adding the TcpServer member to the Connection struct we establish a reference to the server that the connection belongs to The TcpServer property is of type ziface IServer Adding Connection to the Connection ManagerWhen initializing a connection we need to add the connection to the server s connection manager In the zinx znet connection go file modify the NewConnection function to include the server object zinx znet connection go NewConnection creates a connectionfunc NewConnection server ziface IServer conn net TCPConn connID uint msgHandler ziface IMsgHandle Connection c amp Connection TcpServer server Set the server object Conn conn ConnID connID isClosed false MsgHandler msgHandler ExitBuffChan make chan bool msgChan make chan byte msgBuffChan make chan byte utils GlobalObject MaxMsgChanLen Add the newly created connection to the connection manager c TcpServer GetConnMgr Add c return c In the NewConnection function we pass the server object as a parameter and set it in the TcpServer property of the connection object Then we add the connection to the connection manager using c TcpServer GetConnMgr Add c Checking Connection Count in ServerIn the Start method of the server after a successful connection is established with a client we can check the number of connections and terminate the connection creation if it exceeds the maximum connection count Modify the Start method in the zinx znet server go file as follows zinx znet server go Start the network servicefunc s Server Start omitted code Start a goroutine to handle the server listener go func omitted code Start the server network connection business for Block and wait for client connection requests omitted code Set the maximum connection limit for the server If the limit is exceeded close the new connection if s ConnMgr Len gt utils GlobalObject MaxConn conn Close continue omitted code In the server s Start method we check the connection count using s ConnMgr Len and compare it with the maximum connection limit If the limit is reached we close the new connection conn Close and continue to the next iteration Developers can define the maximum connection count in the configuration file zinx json or in the GlobalObject global configuration using the MaxConn attribute Removing a ConnectionWhen a connection is closed it should be removed from the ConnManager In the Stop method of the Connection struct we add the removal action from the ConnManager Modify the Stop method in the zinx znet connection go file as follows zinx znet connection gofunc c Connection Stop fmt Println Conn Stop ConnID c ConnID if c isClosed true return c isClosed true c Conn Close c ExitBuffChan lt true Remove the connection from the ConnManager c TcpServer GetConnMgr Remove c close c ExitBuffChan close c msgBuffChan In the Stop method after closing the connection we remove the connection from the ConnManager using c TcpServer GetConnMgr Remove c Additionally when stopping the server in the Stop method we need to clear all connections as well zinx znet server gofunc s Server Stop fmt Println STOP Zinx server name s Name Stop or clean up other necessary connection information or other information s ConnMgr ClearConn In the Stop method we call s ConnMgr ClearConn to stop and remove all connections from the ConnManager With the above code we have successfully integrated the connection management into Zinx Buffered Message Sending Method for ConnectionPreviously a method called SendMsg was provided for the Connection struct which sends data to an unbuffered channel called msgChan However if there are a large number of client connections and the recipient is unable to process the messages promptly it may lead to temporary blocking To provide a non blocking sending experience a buffered message sending method can be added IConnection Interface Definition zinx ziface iconnection go Connection interface definitiontype IConnection interface Start the connection allowing the current connection to start working Start Stop the connection ending the current connection state Stop Get the raw TCPConn of the current connection GetTCPConnection net TCPConn Get the current connection ID GetConnID uint Get the remote client address information RemoteAddr net Addr Send Message data directly to the remote TCP client unbuffered SendMsg msgID uint data byte error Send Message data directly to the remote TCP client buffered SendBuffMsg msgID uint data byte error Add buffered message sending interface In addition to the SendMsg method we will provide a SendBuffMsg method in the IConnectioninterface The SendBuffMsg method is similar to SendMsg but uses a buffered channel for communication between two goroutines The definition of the Connection struct in the zinx znet connection go file will be modified as follows Connection Struct Definition zinx znet connection go type Connection struct The server to which the current connection belongs TcpServer ziface IServer The TCP socket of the current connection Conn net TCPConn The ID of the current connection also known as SessionID globally unique ConnID uint The closing state of the current connection isClosed bool The message handler that manages MsgID and corresponding processing methods MsgHandler ziface IMsgHandle The channel that informs that the connection has exited stopped ExitBuffChan chan bool The unbuffered channel used for message communication between the reading and writing goroutines msgChan chan byte The buffered channel used for message communication between the reading and writing goroutines msgBuffChan chan byte To implement the buffered message sending functionality a msgBuffChan of type chan byte is added to the Connection struct The msgBuffChan will be used for communication between the reading and writing goroutines Make sure to initialize the msgBuffChan member in the connection s constructor method NewConnection Constructor zinx znet connection go func NewConnection server ziface IServer conn net TCPConn connID uint msgHandler ziface IMsgHandle Connection Initialize Conn properties c amp Connection TcpServer server Conn conn ConnID connID isClosed false MsgHandler msgHandler ExitBuffChan make chan bool msgChan make chan byte msgBuffChan make chan byte utils GlobalObject MaxMsgChanLen Don t forget to initialize Add the newly created Conn to the connection manager c TcpServer GetConnMgr Add c return c The SendBuffMsg method implementation is similar to SendMsg It packs and sends the data to the client through the msgBuffChan Here s the implementation SendBuffMsg Method Implementation zinx znet connection go func c Connection SendBuffMsg msgID uint data byte error if c isClosed return errors New Connection closed when sending buffered message Pack the data and send it dp NewDataPack msg err dp Pack NewMsgPackage msgID data if err nil fmt Println Pack error msg ID msgID return errors New Pack error message Write to the client c msgBuffChan lt msg return nil The StartWriter method in the Connection struct needs to handle the msgBuffChan for data transmission Here s the implementation StartWriter Method Implementation zinx znet connection go func c Connection StartWriter fmt Println Writer Goroutine is running defer fmt Println c RemoteAddr String conn Writer exit for select case data lt c msgChan Data to be written to the client if err c Conn Write data err nil fmt Println Send Data error err Conn Writer exit return case data ok lt c msgBuffChan Handling data for buffered channel if ok Data to be written to the client if err c Conn Write data err nil fmt Println Send Buffered Data error err Conn Writer exit return else fmt Println msgBuffChan is Closed break case lt c ExitBuffChan return The StartWriter method listens to both the msgChan and msgBuffChan channels If there s data in the msgChan it writes it directly to the client If there s data in the msgBuffChan it writes it to the client after processing it accordingly Registering Connection Start Stop Custom Hook Methods for Link Initialization ShutdownDuring the lifecycle of a connection there are two moments when developers need to register callback functions to execute custom business logic These moments occur after the connection is created and before it is disconnected To meet this requirement Zinx needs to add callback functions also known as hook functions that are triggered after the connection is created and before it is disconnected The IServer interface in the zinx ziface iserver go file provides methods for registering connection hooks that can be used by developers The interface definition is as follows type IServer interface Start the server Start Stop the server Stop Start the business service Serve Register a routing business method for the current server to be used for client connection processing AddRouter msgID uint router IRouter Get the connection manager GetConnMgr IConnManager Set the hook function to be called when a connection is created for this server SetOnConnStart func IConnection Set the hook function to be called when a connection is about to be disconnected for this server SetOnConnStop func IConnection Invoke the OnConnStart hook function for the connection CallOnConnStart conn IConnection Invoke the OnConnStop hook function for the connection CallOnConnStop conn IConnection Four new hook methods are added SetOnConnStart Set the hook function to be called when a connection is created for the current server SetOnConnStop Set the hook function to be called when a connection is about to be disconnected for the current server CallOnConnStart Invoke the hook function after a connection is created CallOnConnStop Invoke the hook function before a connection is about to be disconnected The Server struct in the zinx znet server go file is updated to include two new fields for the hook functions type Server struct Server name Name string TCP version e g tcp or other IPVersion string IP address to which the server is bound IP string Port to which the server is bound Port int Message handler for the server used to bind MsgID with corresponding handling methods MsgHandler ziface IMsgHandle Connection manager for the server ConnMgr ziface IConnManager New hook function prototypes Hook function to be called when a connection is created for this server OnConnStart func conn ziface IConnection Hook function to be called when a connection is about to be disconnected for this server OnConnStop func conn ziface IConnection The Server struct now includes OnConnStart and OnConnStop fields to hold the addresses of the hook functions passed by developers The implementation of the four new hook methods is as follows Set the hook function to be called when a connection is created for the serverfunc s Server SetOnConnStart hookFunc func ziface IConnection s OnConnStart hookFunc Set the hook function to be called when a connection is about to be disconnected for the serverfunc s Server SetOnConnStop hookFunc func ziface IConnection s OnConnStop hookFunc Invoke the OnConnStart hook function for the connectionfunc s Server CallOnConnStart conn ziface IConnection if s OnConnStart nil fmt Println gt CallOnConnStart s OnConnStart conn Invoke the OnConnStop hook function for the connectionfunc s Server CallOnConnStop conn ziface IConnection if s OnConnStop nil fmt Println gt CallOnConnStop s OnConnStop conn Now let s determine the positions where these two hook methods should be called The first position is after the connection is created which is the last step in the Start method of the Connection struct Start the connection allowing it to begin workingfunc c Connection Start Start the Goroutine for reading data from the client go c StartReader Start the Goroutine for writing data back to the client go c StartWriter Call the registered hook method for connection creation according to the user s requirements c TcpServer CallOnConnStart c The second position is just before the connection is stopped which is when the Stop method of the Connection struct is called It should be called before the Close action of the socket because once the socket is closed the communication with the remote end is terminated If the hook method involves writing data back to the client it will not be able to communicate properly Therefore the hook method should be called before the Close method Here s the code Stop the connection ending the current connection statefunc c Connection Stop fmt Println Conn Stop ConnID c ConnID If the current connection is already closed if c isClosed true return c isClosed true If the user registered a callback function for this connection s closure it should be called explicitly at this moment c TcpServer CallOnConnStop c Close the socket connection c Conn Close Close the writer c ExitBuffChan lt true Remove the connection from the connection manager c TcpServer GetConnMgr Remove c Close all channels of this connection close c ExitBuffChan close c msgBuffChan Using Zinx V to Complete the ApplicationBy now all the connection management functionality has been integrated into Zinx The next step is to test whether the connection management module is functional Let s test a server that demonstrates the ability to handle connection management hook function callbacks The code is as follows Server gopackage mainimport fmt zinx ziface zinx znet Ping test custom routertype PingRouter struct znet BaseRouter Ping Handlefunc this PingRouter Handle request ziface IRequest fmt Println Call PingRouter Handle Read the data from the client first then write back ping ping ping fmt Println recv from client msgId request GetMsgID data string request GetData err request GetConnection SendBuffMsg byte ping ping ping if err nil fmt Println err type HelloZinxRouter struct znet BaseRouter HelloZinxRouter Handlefunc this HelloZinxRouter Handle request ziface IRequest fmt Println Call HelloZinxRouter Handle Read the data from the client first then write back Hello Zinx Router V fmt Println recv from client msgId request GetMsgID data string request GetData err request GetConnection SendBuffMsg byte Hello Zinx Router V if err nil fmt Println err Executed when a connection is createdfunc DoConnectionBegin conn ziface IConnection fmt Println DoConnectionBegin is Called err conn SendMsg byte DoConnection BEGIN if err nil fmt Println err Executed when a connection is lostfunc DoConnectionLost conn ziface IConnection fmt Println DoConnectionLost is Called func main Create a server handler s znet NewServer Register connection hook callback functions s SetOnConnStart DoConnectionBegin s SetOnConnStop DoConnectionLost Configure routers s AddRouter amp PingRouter s AddRouter amp HelloZinxRouter Start the server s Serve The server side business code registers two hook functions DoConnectionBegin to be executed after the connection is created and DoConnectionLost to be executed before the connection is lost DoConnectionBegin After the connection is created it sends a message with ID to the client and prints a debug message on the server side saying DoConnectionBegin is Called DoConnectionLost Before the connection is lost it prints a debug message on the server side saying DoConnectionLost is Called The code for the client Client go remains unchanged To test the server and client open different terminals and start the server and client using the following commands Start the server go run Server go Start the Client go run Client goThe server side output will be as follows go run Server goAdd api msgId Add api msgId START Server name zinx v demoApp listener at IP Port is starting Zinx Version V MaxConn MaxPacketSize start Zinx server zinx v demoApp succ now listening Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started connection add to ConnManager successfully conn num gt CallOnConnStart DoConnectionBegin is Called Writer Goroutine is running Reader Goroutine is running Add ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test MessageAdd ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test MessageAdd ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test MessageAdd ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test MessageAdd ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test Messageread msg head error read tcp gt read connection reset by peerConn Stop ConnID gt CallOnConnStop DoConnectionLost is Called connection Remove ConnID successfully conn num conn Reader exit conn Writer exit The client side output will be as follows go run Client goClient Test start gt Recv Msg ID len data DoConnection BEGIN gt Recv Msg ID len data ping ping ping gt Recv Msg ID len data ping ping ping gt Recv Msg ID len data ping ping ping gt Recv Msg ID len data ping ping ping Csignal interruptFrom the above results we can see that the client is successfully created and the callback hooks have been executed The connection has been added to the ConnManager in the server and the current connection count conn num is When we manually press CTRL C to close the client the ConnManager on the server side successfully removes the connection and the connection count conn num becomes Additionally the server side debug information for connection stop callback is printed Setting Connection Attributes in ZinxWhen dealing with connections developers often want to bind certain user data or parameters to a connection This allows them to retrieve the passed parameters from the connection during handle processing and carry out business logic accordingly In order to provide this capability Zinx needs to establish interfaces or methods for setting attributes on a current connection This section will implement the functionality to set attributes for connections Adding Connection Configuration InterfaceTo begin with in the IConnection abstract layer three related interfaces for configuring connection attributes are added The code is as follows zinx ziface iconnection go Definition of the connection interfacetype IConnection interface Start the connection and initiate its operations Start Stop the connection and terminate its current state Stop Get the underlying TCPConn from the current connection GetTCPConnection net TCPConn Get the connection s unique ID GetConnID uint Get the remote client s address information RemoteAddr net Addr Send Message data directly to the remote TCP client unbuffered SendMsg msgId uint data byte error Send Message data directly to the remote TCP client buffered SendBuffMsg msgId uint data byte error Set connection attributes SetProperty key string value interface Get connection attributes GetProperty key string interface error Remove connection attributes RemoveProperty key string In the provided code snippet IConnection has three added methods SetProperty GetProperty and RemoveProperty The key parameter in each method is of type string and the value parameter is of the versatile interface type The subsequent step involves defining the specific types of properties within the Connection Implementation of Connection Property MethodsIn the implementation layer the Connection structure is augmented with a member attribute named property This attribute will hold all user provided parameters passed through the connection and it is defined as a map string interface type The definition is as follows zinx znet connction gotype Connection struct Current Conn belongs to which Server TcpServer ziface IServer The TCP socket of the current connection Conn net TCPConn ID of the current connection also known as SessionID globally unique ConnID uint Current connection s closure state isClosed bool Message manager module for managing MsgId and corresponding message handling methods MsgHandler ziface IMsgHandle Channel to signal that the connection has exited stopped ExitBuffChan chan bool Unbuffered channel for message communication between read and write goroutines msgChan chan byte Buffered channel for message communication between read and write goroutines msgBuffChan chan byte Connection properties property map string interface Lock for protecting concurrent property modifications propertyLock sync RWMutex The property map is not concurrency safe and read and write operations on the map need to be protected with the propertyLock Additionally the constructor of Connection must initialize both property and propertyLock The code snippet for this is provided below zinx znet connction go Method to create a connectionfunc NewConntion server ziface IServer conn net TCPConn connID uint msgHandler ziface IMsgHandle Connection Initialize Conn properties c amp Connection TcpServer server Conn conn ConnID connID isClosed false MsgHandler msgHandler ExitBuffChan make chan bool msgChan make chan byte msgBuffChan make chan byte utils GlobalObject MaxMsgChanLen property make map string interface Initialize connection property map Add the newly created Conn to the connection manager c TcpServer GetConnMgr Add c return c The implementation of the three methods for handling connection properties is straightforward They respectively involve adding reading and removing entries from the map The implementations of these methods are as follows zinx znet connction go Set connection propertyfunc c Connection SetProperty key string value interface c propertyLock Lock defer c propertyLock Unlock c property key value Get connection propertyfunc c Connection GetProperty key string interface error c propertyLock RLock defer c propertyLock RUnlock if value ok c property key ok return value nil else return nil errors New no property found Remove connection propertyfunc c Connection RemoveProperty key string c propertyLock Lock defer c propertyLock Unlock delete c property key These methods manage the interaction with the property map allowing for adding retrieving and removing properties associated with a connection Connection Property Testing in Zinx VAfter encapsulating the functionality for connection properties we can use the relevant interfaces on the server side to set some properties and test whether the setting and extraction of properties are functional Below is the server side code Server gopackage mainimport fmt zinx ziface zinx znet ping test custom routertype PingRouter struct znet BaseRouter Ping Handlefunc this PingRouter Handle request ziface IRequest fmt Println Call PingRouter Handle Read client data first then reply with ping ping ping fmt Println recv from client msgId request GetMsgID data string request GetData err request GetConnection SendBuffMsg byte ping ping ping if err nil fmt Println err type HelloZinxRouter struct znet BaseRouter HelloZinxRouter Handlefunc this HelloZinxRouter Handle request ziface IRequest fmt Println Call HelloZinxRouter Handle Read client data first then reply with ping ping ping fmt Println recv from client msgId request GetMsgID data string request GetData err request GetConnection SendBuffMsg byte Hello Zinx Router V if err nil fmt Println err Executed when a connection is createdfunc DoConnectionBegin conn ziface IConnection fmt Println DoConnectionBegin is Called Set two connection properties after the connection is created fmt Println Set conn Name Home done conn SetProperty Name Aceld conn SetProperty Home err conn SendMsg byte DoConnection BEGIN if err nil fmt Println err Executed when a connection is lostfunc DoConnectionLost conn ziface IConnection Before the connection is destroyed query the Name and Home properties of the conn if name err conn GetProperty Name err nil fmt Println Conn Property Name name if home err conn GetProperty Home err nil fmt Println Conn Property Home home fmt Println DoConnectionLost is Called func main Create a server handle s znet NewServer Register connection hook callback functions s SetOnConnStart DoConnectionBegin s SetOnConnStop DoConnectionLost Configure routers s AddRouter amp PingRouter s AddRouter amp HelloZinxRouter Start the server s Serve The key focus is on the implementations of the DoConnectionBegin and DoConnectionLost functions Within these functions connection properties are set and extracted using the hook callbacks Once a connection is established the properties Name and Home are assigned to the connection using the conn SetProperty method Later these properties can be retrieved using the conn GetProperty method Open a terminal to launch the server program and observe the following results go run Server go Add api msgId Add api msgId START Server name zinx v demoApp listener at IP Port is starting Zinx Version V MaxConn MaxPacketSize start Zinx server zinx v demoApp succ now listening Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started Worker ID is started connection add to ConnManager successfully conn num gt CallOnConnStart DoConnecionBegin is Called Set conn Name Home done Writer Goroutine is running Reader Goroutine is running Add ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test MessageAdd ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test MessageAdd ConnID request msgID to workerID Call PingRouter Handlerecv from client msgId data Zinx V Client Test Messageread msg head error read tcp gt read connection reset by peerConn Stop ConnID gt CallOnConnStop Conn Property Name AceldConn Property Home https github com aceld zinxDoConneciotnLost is Called connection Remove ConnID successfully conn num conn Reader exit conn Writer exit In a new terminal start the client program and observe the following results go run Client go Client Test start gt Recv Msg ID len data DoConnection BEGIN gt Recv Msg ID len data ping ping ping gt Recv Msg ID len data ping ping ping Csignal interruptThe server output is particularly noteworthy gt CallOnConnStop Conn Property Name AceldConn Property Home DoConneciotnLost is Called SummaryIn this chapter two functionalities were introduced to enhance the capabilities of connections in Zinx The first one is the connection management module which gathers all the connections within the Zinx server providing an aggregated view and counting of the total number of connections Currently Zinx simply employs a basic incremental calculation for connection IDs Readers are encouraged to optimize this aspect by replacing ConnID with a more common distributed ID ensuring uniqueness across IDs The connection management module aids in controlling the concurrent load on the server by limiting the number of connections The second addition connection properties enriches the convenience of handling business logic within Zinx Developers can utilize the SetProperty and GetProperty methods to associate different attributes with different connections This enables the linking of various markers or attributes to different connections facilitating flexible business logic handling lt Building Basic Services with Zinx Framework gt lt Zinx V Simple Connection Encapsulation and Binding with Business gt lt Design and Implementation of the Zinx Framework s Routing Module gt lt Zinx Global Configuration gt lt Zinx Message Encapsulation Module Design and Implementation gt lt Design and Implementation of Zinx Multi Router Mode gt lt Building Zinx s Read Write Separation Model gt lt Zinx Message Queue and Task Worker Pool Design and Implementation gt lt Zinx Connection Management and Property Setting gt To be continue Author discord zinx github aceld s home 2023-08-15 02:33:25
海外TECH DEV Community Profile not creating when creating a User with Django https://dev.to/highcenburg/profile-not-creating-when-creating-a-user-with-django-27nd Profile not creating when creating a User with Django Profile not creating when creating a User with Django Aug Comments Answers I m using DRF for my project and I need help in automatically creating a Profile instance for a User model when a User is created My signals is from django db models signals import post savefrom django conf import settingsfrom django contrib auth import get user modelfrom models import ProfileUser get user model def create user profile sender instance … Open Full Question 2023-08-15 02:26:23
海外TECH DEV Community A Tale of Two Pointers: How Linked Lists Work 🖇️ https://dev.to/aztec_mirage/a-tale-of-two-pointers-how-linked-lists-work-3c6h A Tale of Two Pointers How Linked Lists Work ️ Release What is a Linked list A linked list is a data structure that consists of a collection of nodes which together represent a sequence Each node contains data and a reference or link to the next node in the sequence The first node in the sequence is called the head and the last node is called the tail Example The history of visited web pages in a web browser can be represented as a linked list Each node in the linked list represents a web page and the next pointer points to the next web page in the history Arrays and linked lists are both data structures that can be used to store data However they have different characteristics and are suited for different tasks ️ Arrays Arrays store data in contiguous memory locations This means that the elements of an array are stored next to each other in memory Accessing an element in an array is very fast because the element s address can be calculated directly from its index Arrays have a fixed size This means that the size of an array cannot be changed after it is created Arrays are good for storing data that will be accessed frequently Linked lists Linked lists store data in non contiguous memory locations This means that the elements of a linked list are not stored next to each other in memory Accessing an element in a linked list is slower than accessing an element in an array because the element s address cannot be calculated directly from its index Linked lists can grow and shrink dynamically This means that the size of a linked list can be changed at runtime Linked lists are good for storing data that will be accessed infrequently or that needs to be inserted or deleted frequently Structure of a Linked List Every element in a linked list is called a node and consists of two parts the data part and the pointer part The data part stores the value while the pointer part stores the pointer pointing to the address of the next node head gt node gt node gt node gt node gt tailIn this example head is the first node in the linked list and tail is the last node Each node contains a piece of data and a reference to the next node in the list Both of these structures arrays and linked lists are linear data structures Operations Traversal To traverse a linked list we can use a loop to iterate through each node in the list Insertion To insert a new node into a linked list we can create a new node and then set the next pointer of the new node to the next pointer of the current node Deletion To delete a node from a linked list we can first find the node to be deleted Then we can set the next pointer of the previous node to the next pointer of the node to be deleted Search To search for a node in a linked list we can use a loop to iterate through each node in the list and compare the value of the node to the value we are searching for Merging This operation merges two linked lists into one linked list Splitting This operation splits a linked list into two linked lists Circular Linked list 🛞 A circular linked list is a linked list where the last element points to the first element head hence forming a circular chain There is no node pointing to the NULL since a circle has no end In circular linked lists we have a head pointer but no starting of this list Here is an example of a circular linked list head gt node gt node gt node gt node gt headIn this example head is the first node in the circular linked list and node is the last node The next pointer of node points back to head which completes the circle Operations Traversal To traverse a circular linked list we can use a loop to iterate through the nodes in the list until we reach the beginning of the list again Insertion To traverse a circular linked list we can use a loop to iterate through the nodes in the list until we reach the beginning of the list again Deletion To delete a node from a circular linked list we can first find the node to be deleted Then we can set the next pointer of the previous node to the next pointer of the node to be deleted Search To search for a node in a circular linked list we can use a loop to iterate through the nodes in the list and compare the value of the node to the value we are searching for Merging This operation merges two circular linked lists into one circular linked list Splitting This operation splits a circular linked list into two circular linked lists Doubly Linked list ️ A doubly linked list is a data structure that consists of a collection of nodes which together represent a sequence Each node contains data and two references or links to the next and previous nodes in the sequence The first node in the sequence is called the head and the last node is called the tail Here is an example of a doubly linked list head gt node gt node gt node gt node gt tailIn this example head is the first node in the doubly linked list and tail is the last node Each node contains a piece of data and two references to the next and previous nodes in the list The two references in a doubly linked list allow for efficient traversal in both directions forward and backward This makes doubly linked lists more versatile than singly linked lists which can only be traversed in one direction The logic behind all the linked lists are same everywhere but the implementation varies depending on the programming language So to summarize we have learned about the different types of linked lists in this post Be sure to check out the code and implementation of each one in your preferred programming language to solidify your understanding amp Happy Independence Day to all my Indian comrades I hope this post has been informative and helpful If you have any questions please feel free to leave a comment below Happy Coding Thank You 2023-08-15 02:18:47
海外TECH DEV Community Preventing side effect functions in Flutter https://dev.to/brainiacneit/preventing-side-effect-functions-in-flutter-19df Preventing side effect functions in Flutter IntroductionThroughout my programming journey I ve learned that writing clean efficient and maintainable code is crucial When working with Flutter it s essential to avoid side effect functions that can cause unexpected issues and make the code harder to understand Join me as we dive into the importance of steering clear of side effects and learn how to create well crafted and reliable Flutter applications When composing a function you re aware of its inputs which are the parameters and its output which is the return value Anything that goes beyond this and influences the world outside the function is considered a side effect void hello print Hello Printing something to the console constitutes a side effect since it impacts the world beyond the function If you want to modify your function to eliminate side effects you could rewrite it like this String hello return Hello Now there s nothing within the function body that impacts the external environment You ll need to print the string to the console outside of the function Grasping Side EffectsSide effects encompass any alterations happening outside the direct scope of a function or widget Such changes can involve modifying state executing network requests carrying out I O operations accessing databases or interacting with external services Side effects can result in reduced predictability and make understanding your application s behavior challenging Consequently it s vital to use techniques that minimize side effects and ensure your app remains dependable and easy to maintain While it s acceptable and sometimes necessary for certain functions to have side effects functions without side effects are generally easier to handle and comprehend You can trust them to perform exactly as anticipated since they consistently return the same output for a given input Functions of this type are also referred to as pure functions Adopt Reactive Programming Reactive programming is an approach that emphasizes handling state changes in a clear and foreseeable way In Flutter multiple reactive programming libraries exist including Provider Riverpod Bloc and MobX These libraries let you segregate business logic from the user interface facilitating improved control over side effects By confining side effects to particular components you can make certain that alterations remain contained and predictable Opt for the Suitable State Management Method Picking the right state management strategy can substantially decrease the incidence of side effects Flutter provides a range of state management libraries each possessing unique benefits and strong points Libraries such as Provider and Riverpod promote the utilization of unchangeable data structures and impose one way data flow By following these principles you can avoid unexpected side effects and boost the predictability of your application Leverage Async Await and Futures Asynchronous tasks are frequently found in Flutter applications particularly when working with network requests file operations or animations Dart the programming language employed in Flutter offers robust asynchronous programming capabilities such as async await and Futures By using these mechanisms you can manage asynchronous operations more effectively and prevent possible side effects The async await syntax makes writing asynchronous code easier by enabling you to compose asynchronous tasks in a more synchronous manner enhancing code readability and maintainability Restrict the Usage of Global Variables Global variables can lead to side effects as they can be accessed and altered from any part of your application It s recommended to limit their use and instead confine related data and functions within particular components By narrowing the scope of variables you decrease the likelihood of unwanted side effects and render your code more modular and testable Conduct Rigorous Testing Testing is an essential part of any software development process including Flutter In depth unit and integration testing can aid in identifying and preventing side effects in your application Creating tests that encompass various situations and edge cases allows you to confirm the behavior of different components and ensure that side effects are managed properly Automated tests serve as a safety measure helping you detect regressions when making modifications and giving you confidence in your codebase s stability Steering clear of side effects is vital for developing dependable and maintainable Flutter applications By embracing a reactive programming style using suitable state management libraries taking advantage of async await and Futures minimizing global variables carrying out extensive testing applying design patterns and architectural principles and using Flutter s built in widgets and APIs you can significantly decrease the presence of side effects in your codebase Prioritizing the avoidance of side effects paves the way for more predictable high performing and error free Flutter applications ensuring a pleasant user experience and long lasting success ConclusionIn conclusion avoiding side effects is essential for building reliable and maintainable Flutter applications By incorporating best practices and techniques you can significantly reduce the occurrence of side effects in your codebase and create more predictable and performant applications Embrace reactive programming and choose the right state management libraries such as Provider or Riverpod to ensure a clean separation of concerns Leverage Dart s powerful async await and Futures constructs to handle asynchronous operations efficiently Limit the usage of global variables localizing the scope of variables to make your code more modular and testable Furthermore prioritize thorough testing including unit and integration tests to identify and prevent side effects ensuring that your components behave as expected By following these strategies and harnessing Flutter s built in widgets and APIs you ll create delightful user experiences and set your application up for long term success By consistently focusing on preventing side effects you ll produce higher quality more stable and easily maintainable codebases ultimately leading to a positive impact on both the development process and user satisfaction 2023-08-15 02:17:59
海外TECH DEV Community Create And Publish Dart Package For Flutter https://dev.to/pozadkey/create-and-publish-dart-package-for-flutter-5ff8 Create And Publish Dart Package For FlutterWhat are Dart Packages Flutter packages are collections of code that provide pre built functionalities and features to simplify app development in the Flutter framework Flutter packages are published and shared on platforms like pub dev which serves as a central repository for Flutter packages Why do we need Dart packages By leveraging Flutter packages developers can focus on building unique features and experiences while also benefiting from the collective expertise of the community This accelerates development maintains high quality and fosters an ecosystem of shared knowledge and innovation Dart Package vs Plug in PackageA Dart package generally refers to a collection of related code files and assets often distributed via the Dart package manager pub dev which helps manage dependencies and share code A plug in package typically refers to a package designed to extend the functionality of a specific software framework or platform For instance in Flutter a Dart framework a plug in package could provide access to native features or third party services Now let s get to it… Step Create a package projectWe would be creating a our project with a package name called quick button Open the command line in your terminal and type the following line flutter create template package quick buttonThis would create a folder with the entry file being lib quick button Step Initialize a Git repo for your projectWe need to initialize a Git repo on GitHub in our project and enter the following commands in the terminal git initgit add git commit m initial commit git remote add origin git push u origin masterMake sure replace the origin to your with your remote address Step Edit necessary filesAfter pushing all project files to GitHub repository we can begin with editing the files below pubspec yamlThis contains the information regarding a Flutter package as well as dependencies for that project Edit the following authorWrite the information about the creator and contributors to the package using the following pattern FirstName LastName lt gt Damilare Ajakaiye lt hello pozadkey com gt For the homepage enter the package repository s URL README mdA starter markdown file that briefly describes the package s purpose CHANGELOG mdWe list the changes in our package one after the other in the CHANGELOG md version Date explanations about changes LicenseChoose an open source license here Copy and paste the license Make changes to your name and the year Copyright year fullname Step Writing Flutter widgetNow we ll create a custom button widget We ll delete the codes inside the lib quick button file and create a widget class named QuickButton Step Create an exampleNext we ll create an example to test our package This would also help other users to learn how to use the package Go to the root directory and write the following command flutter create exampleAfter the example folder has been created head to the pubspec yaml and add the following to the package dependencies flutter sdk flutter custom alert box path We can now import our package and use it in the example project import package quick button quick button dart Write TestsTo make sure all the widgets are responding correctly you can write some tests in the test quick button test dart file Step Publishing PackageCreate documentation You have to create a documentation to explain the concepts used in the package to other developers interested in using your package To generate a documentation for your package run the command below dart doc Push all changes to GitHub Push all changes to GitHub PublishFirstly we test publish our package to make sure everything is okay before publishing the package to pub dev Run the following command below flutter pub publish ー dry run Once we confirm that there are no errors in our package we can then publish our package to pub dev using the following command flutter pub publishYou would be asked to verify your pub dev account via terminal Congratulations Your Package has been published Step Maintaining the packageBefore publishing updates to your package make sure you push all changes to Github write changes to your CHANGELOG md and change the pubspec yaml version Package source code quick buttonPublished package quick button 2023-08-15 02:12:22
金融 ニッセイ基礎研究所 QE速報:4-6月期の実質GDPは前期比1.5%(年率6.0%)の高成長-実質GDPの水準はコロナ禍前のピークを上回る https://www.nli-research.co.jp/topics_detail1/id=75834?site=nli nbsp名目GDPは前期比前期比年率と四半期連続で増加し、実質の伸びを大きく上回った。 2023-08-15 11:09:12
ニュース BBC News - Home Donald Trump election probe court files criminal charges https://www.bbc.co.uk/news/world-us-canada-66505804?at_medium=RSS&at_campaign=KARANGA grand 2023-08-15 02:42:09
ニュース BBC News - Home Japan economy gets major boost from weak currency https://www.bbc.co.uk/news/business-66506126?at_medium=RSS&at_campaign=KARANGA exporters 2023-08-15 02:07:39
ニュース Newsweek NewJeansファン、BLACKPINKリサの水着姿を「醜すぎる」と酷評...世界的に大炎上 https://www.newsweekjapan.jp/stories/culture/2023/08/newjeansblackpink.php 【画像】NewJeansファンに「醜すぎる」と酷評されたBLACKPINKリサの水着姿ネットメディアのポップ・クレイブは、X旧ツイッターでこの写真を紹介。 2023-08-15 11:30:00
IT 週刊アスキー X (旧Twitter)、ビデオ・音声通話機能を追加予告 https://weekly.ascii.jp/elem/000/004/149/4149826/ twitter 2023-08-15 11:45:00
IT 週刊アスキー 【本日】ファミマの「中華まん」がスタート! 20円引きだよ https://weekly.ascii.jp/elem/000/004/149/4149786/ 中華まん 2023-08-15 11:20:00
マーケティング AdverTimes デジタル化の次はグローバル化 講談社、組織改編の狙いとは? https://www.advertimes.com/20230815/article430118/ 開発 2023-08-15 03:00:13

コメント

このブログの人気の投稿

投稿時間: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件)