投稿時間:2022-02-24 04:28:30 RSSフィード2022-02-24 04:00 分まとめ(32件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
AWS AWS Machine Learning Blog How InpharmD uses Amazon Kendra and Amazon Lex to drive evidence-based patient care https://aws.amazon.com/blogs/machine-learning/how-inpharmd-uses-amazon-kendra-and-amazon-lex-to-drive-evidence-based-patient-care/ How InpharmD uses Amazon Kendra and Amazon Lex to drive evidence based patient careThe intersection of DI and AI Drug information refers to the discovery use and management of healthcare and medical information Healthcare providers have many challenges associated with drug information discovery such as intensive time involvement lack of accessibility and accuracy of reliable data The average clinical query requires a literature search that takes an average of hours In addition drug information often lies in disparate information silos behind pay walls and design walls and quickly becomes stale 2022-02-23 18:42:04
Docker dockerタグが付けられた新着投稿 - Qiita GitHub Actions workflowについてのススメ https://qiita.com/naoki_haba/items/9e46d80db06d6ff80aab GitHubActionsworkflowについてのススメ概要GitHubActionsを利用したテストワークフローの構築について社内布教用にまとめてみた経緯ucanlabさんのハンズオンに参加して個人的に導入はしているがチーム内で技術共有をしてなかったので布教用としてまとめることにしましたなお、今回のworkflowについては以下のハンズオン資料を流用させていただいています。 2022-02-24 03:57:46
海外TECH Ars Technica Today’s best deals: Eufy indoor security camera, Apple gift cards, and more https://arstechnica.com/?p=1835987 takes 2022-02-23 18:28:44
海外TECH Ars Technica An asteroid killed dinosaurs in spring—which might explain why mammals survived https://arstechnica.com/?p=1835967 extinction 2022-02-23 18:16:15
海外TECH MakeUseOf The Top 10 Meal Planning Apps for Healthy Eating https://www.makeuseof.com/top-meal-planning-apps-healthy-eating/ planning 2022-02-23 18:45:13
海外TECH MakeUseOf The 7 Best Dropbox Alternatives https://www.makeuseof.com/best-dropbox-alternatives/ dropbox 2022-02-23 18:30:13
海外TECH MakeUseOf 6 Reasons You Need to Use Microsoft Edge on Windows 11 https://www.makeuseof.com/windows-11-edge-reasons-to-use/ windows 2022-02-23 18:15:13
海外TECH DEV Community Project 1: color flipper project in Javascript explained https://dev.to/urstrulyvishwak/project-1-color-flipper-project-in-javascript-explained-3gmg Project color flipper project in Javascript explainedI want to explain each and every step in creating small project in Javascript Purely designed this project using HTML amp Javascript Ok What is color flipper first Color of the whole page changes upon clicking button also shows the color name See below Open any IDE or just a notepad in your computer Write below code and save as colorFlipper html Double click or open with Chrome browser Keep clicking on Flip Color buttonObserve that color is flipped between red and green Code lt html gt lt body id flipper gt lt p id text style font size px gt Background Color lt span id color gt red lt span gt lt p gt lt button id btn style padding px px onclick perform gt Flip color lt button gt lt script gt function perform let showingColor document getElementById color const color showingColor innerText red green red showingColor innerHTML color document getElementById flipper style backgroundColor color lt script gt lt body gt lt html gt Hope you got it Now we will see what is happening inside the code Basically you are interacting with Flip Color button That is your starting point If you see in above HTML lt button id btn style padding px px onclick perform gt Flip color lt button gt Button html element with name as Flip color has an action event onclick perform Yes here onclick event calls perform function Everything under this perform function is the core functionality which is making you to flip the color Ok Now that we have done with step click on button Let s go into perform and understand what is happening inside of it function perform let showingColor document getElementById color const color showingColor innerText red green red showingColor innerHTML color document getElementById flipper style backgroundColor color Here showingColor is variable into which we are storing element i e span inside p element showingColor innerText gives the current value of color color variable assigned with current body color So the whole condition is if color is red then assign green and vice versa now that you got which color to update using color variable Let s set text as selected color showingColor innerHTML color which sets span color with the opposite of existing color always document getElementById flipper style backgroundColor color sets background color of body with flipped color Ok now I will improve this to show random color each time when you click button I will update this article as soon as I am done Please do comment if you don t understand any part of it 2022-02-23 18:44:25
海外TECH DEV Community Setup Redux for your react application in few simple steps! https://dev.to/anshnarula5/setup-redux-for-your-react-application-in-few-simple-steps-1f1 Setup Redux for your react application in few simple steps In this article we are going to see how to integrate redux in your project by following few simple steps So lets begin Step Create a new project and add all the dependenciesnpx create react app my appAfter the installation is done you can remove all unnecessary code in App js Now we need to use following dependencies in the project npm i redux redux devtools extension redux thunk react reduxLet us see briefly what are the function of these dependencies redux Redux maintains the state of an entire application in a single immutable state tree object which can t be changed directly To read more about redux you can refer to its documentation It has one of the most easiest documentation you will find redux devtools extension This is basically an extension that you can use to visualize redux workflow in your browser To use this in your browser you need to install this extension in your browser as well linkredux thunk This is basically a middleware that allows us to use dispatch and getState methods inside store react redux React Redux is the official React binding for Redux It allows React components to read data from a Redux Store and dispatch Actions to the Store to update data Redux helps apps to scale by providing a sensible way to manage state through a unidirectional data flow model You can refer to its documentation It will surely help you to clear most of your doubts so please give it a read Step Redux folder and storeAdd a redux folder in src folder and use following structure for the folder redux ├ーactions │├ーcounterActions js │├ー ├ーreducers │├ーcounterReducer js │├ーindex js ├ー ├ーconstants jsNow let us setup store for the project Create a file named store js in src folder import createStore applyMiddleware from redux import thunk from redux thunk import composeWithDevTools from redux devtools extension import rootReducer from redux reducers const store createStore rootReducer composeWithDevTools applyMiddleware thunk export default store The empty brackets after the rootReducer denotes initial state which in our case is empty Please note We havn t yet added rootReducer so it might give you an error We will solve this in next step Now to connect redux store to react application we need to add a provider in src index js file import React from react import ReactDOM from react dom import index css import App from App import reportWebVitals from reportWebVitals import Provider from react redux import store from store ReactDOM render lt React StrictMode gt lt Provider store store gt lt App gt lt Provider gt lt React StrictMode gt document getElementById root reportWebVitals The Provider component wraps whole app s components with store Step Root ReducerNow let us add root reducer We are using a root reducer so that we can combine all the reducers inside a single function Inside redux reducers index js we write following code to combmine reducers import combineReducers from redux const rootReducer combineReducers export default rootReducer That s it Now let us see an example to get a clear understanding Counter ExampleCreate constantsHere we are going to have three constants for increasing decreasing and reset Although you can skip this step but for a large scale application this is very useful as it reduces chances of spelling mistake Inside redux constants jsexport const INCREASE INCREASE export const DECREASE DECREASE export const RESET RESET Create actions In redux actions counterActions we add following actions import DECREASE INCREASE RESET from types export const increase gt dispatch gt dispatch type INCREASE export const decrease gt dispatch gt dispatch type DECREASE export const reset gt dispatch gt dispatch type RESET Create reducers In redux actions counterReducer we add following reducer import DECREASE INCREASE RESET from types const counterReducer state action gt const type payload action switch type case INCREASE return state case DECREASE return state case RESET return default return state export default counterReducer Here we are not passing any data so payload is set empty otherwise we can pass any data in an action on dispatch Add reducer to rootReducer import combineReducers from redux import counterReducer from counterReducer const rootReducer combineReducers counter counterReducer export default rootReducer Final step dispatch action on click of buttonIn App js import useSelector from react redux import useDispatch from react redux import App css import decrease increase reset from redux actions counterActions function App const dispatch useDispatch const counter useSelector state gt state counter return lt div className App gt lt div gt lt button onClick gt dispatch increase gt Increase lt button gt lt button onClick gt dispatch reset gt Reset lt button gt lt button onClick gt dispatch decrease gt Decrease lt button gt lt div gt lt div gt counter lt div gt lt div gt export default App It works You can see all dispatch events and state of the application in the redux devtools extension For this press alt shift tab and switch to redux tab You can see the full code herePlease note You might think that using redux for such a small task is quiet an overkill but when you are creating a medium to large scale application this will surely benefit you If you want to know more about redux I will recommend you to read this articleThanks for reading this article I hope you get some basic understanding of working with redux Happy coding 2022-02-23 18:30:47
海外TECH DEV Community Custom injecting logic for NestJS with support multi providing https://dev.to/endykaufman/custom-injecting-logic-for-nestjs-with-support-multi-providing-438k Custom injecting logic for NestJS with support multi providing Installationnpm i save nestjs custom injector Links Demo application with nestjs custom injector Example generated with nest cli for Usage sections in readme UsageCreate common interface with token in animal provider interface tsexport const ANIMAL PROVIDER ANIMAL PROVIDER export interface AnimalProviderInteface type string say string Create first type of logic for cats in animal cats service tsimport Injectable from nestjs common import AnimalProviderInteface from animal provider interface Injectable export class AnimalCatsService implements AnimalProviderInteface type cat say string return meow Create second type of logic for dogs in animal dogs service tsimport Injectable from nestjs common import AnimalProviderInteface from animal provider interface Injectable export class AnimalDogsService implements AnimalProviderInteface type dog say string return woof Create controller animals controller tsimport Controller Get Query from nestjs common import CustomInject from nestjs custom injector import AnimalProviderInteface ANIMAL PROVIDER from animal provider interface Controller animals export class AnimalsController CustomInject ANIMAL PROVIDER multi true private animalProviders AnimalProviderInteface Get animal types animalTypes return this animalProviders map animalProvider gt animalProvider type Get what says animals whatSaysAnimals return this animalProviders map animal gt animal type say animal say Get who say whoSay Query voice voice string const animal this animalProviders find animal gt animal say voice if animal return error I don t know who say voice return animal type say animal say Append all logic to main app module app module tsimport Module from nestjs common import CustomInjectorModule from nestjs custom injector import AnimalCatsService from animal cats service import AnimalDogsService from animal dogs service import AnimalsController from animals controller Module imports CustomInjectorModule forRoot CustomInjectorModule forFeature providers provide ANIMAL PROVIDER useClass AnimalCatsService CustomInjectorModule forFeature providers provide ANIMAL PROVIDER useValue new AnimalDogsService controllers AnimalsController export class AppModule 2022-02-23 18:06:49
Apple AppleInsider - Frontpage News Apple releases fourth public betas for iOS 15.4, iPadOS 15.4, tvOS 15.4, watchOS 8.5, macOS 12.3 https://appleinsider.com/articles/22/02/23/apple-releases-fourth-public-betas-for-ios-154-ipados-154-tvos-154-watchos-85-macos-123?utm_medium=rss Apple releases fourth public betas for iOS iPadOS tvOS watchOS macOS Apple has released the fourth public beta of iOS iPadOS tvOS watchOS and macOS to members of its public software testing program Public betas are available to testersThe fourth public betas should be essentially the same as the third developer betas which Apple seeded on Tuesday The builds can be acquired from the Apple Beta Software Program web portal Read more 2022-02-23 18:54:15
海外TECH Engadget Target will test curbside returns and Starbucks order pickups this fall https://www.engadget.com/target-curbside-returns-starbucks-order-pickups-test-184907965.html?src=rss Target will test curbside returns and Starbucks order pickups this fallTarget claims that its free app powered Drive Up curbside pickups is one of its customers favorite services and the company plans to test more features this fall In select markets customers will be able to pick up a Starbucks order or make a return without having to enter the store The option to place a Starbucks order has been a frequent request from customers according to Target When you re on the way to a store you ll be able to order items from the Starbucks menu through the Target app A Target employee will bring your order to your car when you arrive You can set up a return through the Target app as well and complete the process in the Drive Up lane On top of those features Target plans to expand its backup item program with categories like beauty products and household essentials Customers will be able to select a wider range of secondary items in case their first choice isn t available The company claims that since it started offering backup options for grocery orders its employees have been able to substitute backup items percent of the time So even if you don t get your preferred item it s highly likely you ll get something pretty close 2022-02-23 18:49:07
海外TECH Engadget Meta wants to build a universal language translator https://www.engadget.com/meta-wants-to-build-a-universal-language-translator-182519805.html?src=rss Meta wants to build a universal language translatorDuring an Inside the Lab Building for the metaverse with AI livestream event on Wednesday Meta CEO Mark Zuckerberg didn t just expound on his company s unblinking vision for the future dubbed the Metaverse He also revealed that Meta s research division is working on a universal speech translation system that could streamline users interactions with AI within the company s digital universe nbsp nbsp nbsp quot The big goal here is to build a universal model that can incorporate knowledge across all modalities all the information that is captured through rich sensors quot Zuckerberg said quot This will enable a vast scale of predictions decisions and generation as well as whole new architectures training methods and algorithms that can learn from a vast and diverse range of different inputs quot Zuckerberg noted that Facebook has continually striven to develop technologies that enable more people worldwide to access the internet and is confident that those efforts will translate to the Metaverse as well nbsp quot This is going to be especially important when people begin teleporting across virtual worlds and experiencing things with people from different backgrounds quot he continued quot Now we have the chance to improve the internet and set a new standard where we can all communicate with one another no matter what language we speak or where we come from And if we get this right this is just one example of how AI can help bring people together on a global scale quot nbsp Meta s plan is two fold First Meta is developing No Language Left Behind a translation system capable of learning quot every language even if there isn t a lot of text available to learn from quot according to Zuckerberg quot We are creating a single model that can translate hundreds of languages with state of the art results and most of the language pairs ーeverything from Austrian to Uganda to Urdu quot Second Meta wants to create an AI Babelfish quot The goal here is instantaneous speech to speech translation across all languages even those that are mostly spoken the ability to communicate with anyone in any language quot Zuckerberg promised quot That s a superpower that people dreamed of forever and AI is going to deliver that within our lifetimes quot These are big claims from a company whose machine generated domain doesn t extend below the belt line however Facebook cum Meta has a long and broad record of AI development In the last year alone the company has announced advances in self supervised learning techniques natural language processing multimodal learning text based generation AI s understanding of social norms and even built a supercomputer to aid in its machine learning research nbsp The company still faces the major hurdle of data scarcity quot Machine translation MT systems for text translations typically rely on learning from millions of sentences of annotated data quot Facebook AI Research wrote in a Wednesday blog post quot Because of this MT systems capable of high quality translations have been developed for only the handful of languages that dominate the web quot Translating between two languages that aren t English is even more challenging according to the FAIR team Most MT systems will first convert one language to text then translate that over to the second language before converting the text back to speech This lags the translation process and creates and outsized dependence on the written word limiting the effectiveness of these systems for primarily oral languages Direct speech to speech systems like what Meta is working on would not be hindered in that way resulting in a faster more efficient translation process 2022-02-23 18:25:19
海外TECH Engadget Meta is working on an AI 'builder bot' for the metaverse https://www.engadget.com/meta-is-working-on-an-ai-builder-bot-for-the-metaverse-181034157.html?src=rss Meta is working on an AI x builder bot x for the metaverseMark Zuckerberg may still be explaining exactly what the metaverse is but the Meta CEO just showed off another technology he says will be crucial to the company s vision of creating immersive environments Meta s AI researchers are working on a voice powered bot that allows users to change their virtual surroundings with voice commands nbsp Zuckerberg demoed an early version of the concept called Builder Bot at a virtual event detailing the company s latest AI research “It enables you to describe a world and then it will generate aspects of that world for you Zuckerberg said In his demo he and another Meta employee used voice commands to create a very basic beach scene with a picnic table clouds and yes Zuckerberg s signature hydrofoil They also added some sound effects of seagulls and ocean waves FacebookFor now though the technology seems to be in a relatively early stage The environment Zuckerberg generated looked much flatter and lower res than past metaverse demos though his legless avatar was present much like other recent demos “As we advance this technology further you re going to be able to create nuanced worlds to explore and share experiences with others with just your voice he said The builder bot is part of a larger AI project called Project CAIRaoke that aims to create the kind of conversational AI necessary to create these virtual worlds Facebook isn t the first to experiment with this type of research OpenAI showed off a neural network capable of generating images from text last year But Zuckerberg said that project CAIRaoke would be central for the Meta s future “In the metaverse we re going to need AI that is built around helping people navigate virtual worlds as well as our physical world with augmented reality Zuckerberg said “When we have glasses on our faces that will be the first time that an AI system will be able to really see the world from our perspective See what we see hear what we hear and more Zuckerberg s comments come as he is trying to pivot the company from social networking to metaverse technology a move that has so far proved to be incredibly expensive But as the core Facebook service starts to lose users for the first time ever Zuckerberg has said “metaverse experiences like the company s VR Horizon Worlds will drive future growth 2022-02-23 18:10:34
Cisco Cisco Blog Digitally transform through workflow and process automation https://blogs.cisco.com/financialservices/digitally-transform-through-workflow-and-process-automation Digitally transform through workflow and process automationThe digital transformation path means replacing legacy systems and processes with more efficient methods The journey of digitizing workflow and automating processes benefits the new hybrid workforce to the betterment of sales and service 2022-02-23 18:50:40
Cisco Cisco Blog Silicon photonics explained: Cisco Optics Podcast Episode 19 notes https://blogs.cisco.com/sp/silicon-photonics-explained-cisco-optics-podcast-episode-19-notes Silicon photonics explained Cisco Optics Podcast Episode notesJoin us for Episode of the Cisco Optics Podcast where we conclude a conversation with Ron Horan who runs Product Management for the Cisco Client Optics Group 2022-02-23 18:14:58
海外科学 NYT > Science F.D.A. Grants the First Condom Approval for Anal Sex https://www.nytimes.com/2022/02/23/health/fda-condoms-anal-sex.html F D A Grants the First Condom Approval for Anal SexThough public health experts have long advised the use of condoms for anal sex to protect against H I V and other infections regulators did not have enough data to allow marketing for that use 2022-02-23 18:36:31
ニュース @日本経済新聞 電子版 世界債務、初の300兆ドル超え コロナで財政膨張 https://t.co/SO9J3UiAaJ https://twitter.com/nikkei/statuses/1496552379072004097 財政 2022-02-23 18:27:46
ニュース BBC News - Home Putin has gone ‘full tonto’ over actions in Ukraine - Ben Wallace https://www.bbc.co.uk/news/uk-politics-60496122?at_medium=RSS&at_campaign=KARANGA putin 2022-02-23 18:34:12
ニュース BBC News - Home Man arrested after hostage standoff at Amsterdam Apple store https://www.bbc.co.uk/news/world-europe-60486726?at_medium=RSS&at_campaign=KARANGA amsterdam 2022-02-23 18:24:40
ビジネス ダイヤモンド・オンライン - 新着記事 商社の業界研究、ビジネスの3大変化で人材ニーズが様変わり?【再編マップ付き】 - 親と子のための業界・企業研究 https://diamond.jp/articles/-/297156 企業研究 2022-02-24 03:55:00
ビジネス ダイヤモンド・オンライン - 新着記事 プーチン氏の演説、米主導の世界秩序を批判 - WSJ PickUp https://diamond.jp/articles/-/297089 wsjpickup 2022-02-24 03:50:00
ビジネス ダイヤモンド・オンライン - 新着記事 ウクライナ情勢緊迫で高騰の原油相場、高止まりはいつまで続くか - マーケットフォーカス https://diamond.jp/articles/-/297088 原油価格 2022-02-24 03:45:00
ビジネス ダイヤモンド・オンライン - 新着記事 出前アプリの美団急落、中国テク株に新たな曲球 - WSJ PickUp https://diamond.jp/articles/-/297090 wsjpickup 2022-02-24 03:40:00
ビジネス ダイヤモンド・オンライン - 新着記事 オープンできぬテスラの独工場、納車も先延ばし - WSJ PickUp https://diamond.jp/articles/-/297094 wsjpickup 2022-02-24 03:35:00
ビジネス ダイヤモンド・オンライン - 新着記事 「今日は残業」 深夜飯でも太らない食べ方のコツとは - やせたい人はカロリー制限をやめなさい https://diamond.jp/articles/-/296044 経験 2022-02-24 03:30:00
ビジネス ダイヤモンド・オンライン - 新着記事 「優秀さの罠」から抜け出したマネジャーが、組織の中で見つけたもの - HRオンライン https://diamond.jp/articles/-/296889 2022-02-24 03:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 定期テストで20点アップを保証する意味 「やればできる」が子どもの顔を上向かせる - 成し遂げる力 https://diamond.jp/articles/-/296832 定期テストで点アップを保証する意味「やればできる」が子どもの顔を上向かせる成し遂げる力日本最大級の個別指導塾「森塾」、第回日本サービス大賞で経済産業大臣賞を受賞した自立学習塾「RED」、教室数国内Noのプログラミングスクール「QUREOプログラミング教室」、学習塾の授業・運営を包括的にサポートする「フォレスタシリーズ」、塾講師専門の求人情報「塾講師JAPAN」…。 2022-02-24 03:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 ひろゆきが断言「やる気のない無能より、やる気のある無能のほうが危険」そのワケとは? - 1%の努力 https://diamond.jp/articles/-/296988 youtube 2022-02-24 03:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 「失敗してもいいから、とりあえずやってみよう」は、危ないワケ - 起業家の思考法 https://diamond.jp/articles/-/296959 問題解決 2022-02-24 03:10:00
ビジネス ダイヤモンド・オンライン - 新着記事 頭がいい人と悪い人「憧れのGAFAに入社したい」場合の対策の差 - 転職が僕らを助けてくれる https://diamond.jp/articles/-/290412 2022-02-24 03:05:00
GCP Cloud Blog Migrating a PHP application to use Cloud Spanner https://cloud.google.com/blog/topics/developers-practitioners/migrating-php-application-use-cloud-spanner/ Migrating a PHP application to use Cloud SpannerPHP is used in of websites making it a popular language for developers If your application runs PHP and you want to take advantage of Google Cloud Spanner for its reliability and scalability this post is for you We will highlight the common steps to migrate an existing PHP application to Spanner The example we work through modifies the e commerce platform Magento s Catalog Module to use the Spanner PHP client library But these principles can be used for any PHP application that makes use of the Spanner PHP library What we aim to accomplishUse the PHP client library to configure a connection to the Spanner database and manage a session pool Execute CRUD operations on the configured database in a reliable manner with transactions Become acquainted with some useful snippets and queries inspired by the Magento application implementation Observe how the snippets can be used in an application along with the usual CRUD operations Before we beginConsider working through the Magento Codelab that leverages the magento spanner port While the codelab describes the steps required to get the actual integration working this post goes into more detail to explain what is happening under the hood This document shows a number of examples of how to use Magento with Spanner The examples are taken from the SpannerAdapter and the AbstractDb implementation in the magento spanner port These are the main files of the Magento Spanner adapter implementation SetupAuthenticationAs the first step please follow the Authentication guide to ensure the application is authenticated before executing any of the code snippets below Creating a session pool and the connectionAfter successfully authenticating create a session pool to facilitate the connection between the application and Spanner Creating a session is an expensive operation so it is recommended to create a persistent pool of sessions that can be reused  The Spanner client library provides a handy way to alleviate this problem by having a cached session pool More information on using a cached Session Pool and best practices is available here With SysVCacheItemPool you can share the cached sessions among multiple processes The CreateSessionPool method creates and returns a session pool object Each session connects to a single database and a session can only execute one transaction at a time The variable minSessions can be used to set the minimum number of concurrent sessions that is expected The pool is initialized with minSessions when it is created Then if more than minSessions are required new sessions will be created up until maxSessions is reached To learn more about project identifiers in PHP in relation to ftok please refer to the section of the PHP documentation here Connect to the Spanner databaseThe created session pool can be used to make a connection to Spanner in the connect method as shown below The connection object can be used to perform CRUD operations on Spanner Warm up the session poolKeeping the session aliveThe maintain method refreshes sessions that would otherwise expire within the next minutes In some cases it can also refresh sessions that would otherwise expire in more than minutes in order to distribute refresh calls more evenly Only minSessions sessions are maintained Excess sessions are left to expire Note You should set maxSessions high enough to handle peak concurrency with some additional buffer to allow for growth in peak concurrency Be aware of memory usage of the process to avoid the process being killed Additionally we recommend setting minSessions equal to maxSessions to avoid the latency cost of having to create new sessions when serving requests This should minimize tail latencies Executing Transactions on Spanner After setting up the connection and creating the session pool successfully we are all set to try some Insert Read Update and Delete operations on the Spanner database The snippets below showcase executing CRUD operations using transactions where they will be committed to the database if and only if all the enclosed queries are successful InsertIn the insert method we use runTransaction to create the sequence of instructions that need to be executed We attempt to insert multiple rows using insertBatch and if all inserts are successful the transaction is committed to the database UpdateVery similar to insert updating an existing batch of data can be done using updateBatch in the update method Transactions allow you to rollback your updates in case any update of a row fails to process While updateBatch uses the mutations API updates can also be performed using DML statements with executeUpdate The same is true for inserts mentioned previously Refer to Comparing DML and Mutations for guidelines on when it s appropriate to use mutations vs DML Please keep in mind that Spanner limits the number of mutations that can be performed in a single transaction To learn more about how the number of mutations is calculated please review the documentation To find the mutation count for a transaction and learn how to prevent your transactions from hitting this limit see the commit statisticsdocumentation  DeleteThe delete method deletes the row using transactions to safeguard against partial failed queries In the above code snippet where contains the WHERE clause condition and table is the name of the table to delete from Spanner requires the presence of a WHERE clause to prevent accidental deletion of the entire table Reading from the databaseReading from the database is simpler compared to the transaction queries above as read queries do not require explicit rollback or commit calls The example fetchAll method is shown below Here sql is an SQL string that would be used to query for the results over the database Running any SQL query on the Spanner databaseQueries are made using the execute function on the Spanner connection from the class s query method  Closing the connectionThe closeConnection method releases the resources of the Spanner connection This must be done after all logical operations have been successfully completed by the application otherwise sessions will be held forever by the previous caller This will eventually exhaust the session pool preventing any further requests from being executed More Useful QueriesSo far we described examples of basic CRUD operations Here are a few more interesting operations inspired from the Magento e commerce implementation using Spanner  Convert iterator into arrayCopies the iterator object of results from a query into an array to be used by the application It s important to note that large result sets will use a significant amount of memory so best practice would be to limit results of your Spanner query Generate a UUID Spanner does not support auto increment fields and recommends using a UUID This is because incremental primary keys can create hotspots when accessing data due to the manner in which data is distributed across Spanner servers See Choosing a primary key for more details You can use the generateUUID method to generate random UUIDs Sanitize SQL querySince Spanner uses a strict type of formatting the query you can use the following sanitizeSQL method to ensure the value matches the Spanner data type This is only an example function that handles sanitizing integer data types It can be expanded in your application to handle other sanitization Add casting by type to the columns in queriesAs we just mentioned Spanner is strict on the type of the data being read and written Although Spanner performs implicit casting sometimes queries fail when the default implicit casting fails So to be safe we can explicitly specify the cast to be applied to the column using a snippet like the one below More information on the cast function can be found here Putting everything togetherTaking a few excerpts from the Magento code lab that you worked through let s discuss how we can use our learnings in practice Fetching a catalog of items from the databaseFetching all the items from the database can be as simple as Here select references to the SQL query to select from the database as described in the “Reading from the database section above Considering that Spanner enforces strict types using the addCast function we learned about the entire operation of reading from the catalog of items from the database can be framed as  Getting Wishlist or Cart itemsIn fetching the required items in the catalog for the wishlist we would need to run a SQL query for items again This can be done as follows We also learned about sanitizing the queries to adhere to Spanner s strict type requirements To do this the simple getData method should be modified as shown below The sanitizeSql function from the snippets discussed earlier takes care of the strict type formatting mandated on the queries Fetching data with conditionsYou will need to ensure your query knows the type of the field Consider the implementation below from the load function The  getLoadSelect method returns a simple MySQL query where strings and numeric values for field types are treated alike i e as strings To ensure that we are meeting Spanner s type requirements replace the function getLoadSelect with getLoadSelectForSpanner as shown here Where the implementation of getLoadSelectForSpanner is as follows Saving and updating the objects in your Items  Here we demonstrate the usage of generateUuid based on the fact that Spanner strongly recommends the use of random UUIDs instead of incremental numerals in primary keys  Consider a non Spanner implementation as below Which can be replaced by the following updateObjectInSpanner and saveNewObjectInSpanner make use of our generateUuid snippet explained earlier  To save an object To update an existing object For reference the implementation of prepareDataForSpannerUpdate in updateObjectInSpanner above is shown below Deleting an objectTo complete the D in the CRUD here is an example of safely deleting an object from Spanner in the context of Magento In the Magento example id columns are generally integers For other applications it may be useful to validate that the value matches the expected Spanner data type Wrapping it all upThe basic tools when interfacing with any database are its CRUD operations This article introduced these operations for Spanner in the context of PHP and Magento along with other nuances to keep an eye out for Please refer to the official documentation here to continue your journey with Spanner and PHP   Related ArticleDjango ORM support for Cloud Spanner is now Generally AvailableToday we re happy to announce GA support for Google Cloud Spanner in the Django ORM Read Article 2022-02-23 19:00:00

コメント

このブログの人気の投稿

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

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

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