IT |
気になる、記になる… |
トリニティの全商品が「楽天お買い物マラソン」でポイント10倍に(7月26日まで) |
https://taisy0.com/2023/07/19/174278.html
|
premium |
2023-07-19 12:59:08 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] povo2.0、海外ローミングに対応へ 提供は160カ国以上 Wi-Fiなしでも現地でトッピングが買える |
https://www.itmedia.co.jp/news/articles/2307/19/news190.html
|
itmedianewspovo |
2023-07-19 21:40:00 |
AWS |
lambdaタグが付けられた新着投稿 - Qiita |
API Gatewayのリクエストバリデーション機能でLambdaのリソース消費を抑制する |
https://qiita.com/sho_fcafe/items/e8f1ccdeac795ddd9dde
|
apigateway |
2023-07-19 21:37:14 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
playwrightデバッグのコツ |
https://qiita.com/k8uwall/items/adbed30ecb4f257ff9cd
|
codegen |
2023-07-19 21:37:39 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Pythonの venv 仮想環境内で環境変数を恒常的に設定する方法 |
https://qiita.com/ryotab22/items/3057062cdedeaa48dd1b
|
exportapikey |
2023-07-19 21:36:41 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
ターミナルでドーナッツを回そう! |
https://qiita.com/kurumaebi65/items/7e31b762fb529ad98739
|
donutmathhowdonutcworks |
2023-07-19 21:25:26 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
【Ruby】combinationメソッドで重複のない組み合わせを作る |
https://qiita.com/ym0628/items/4de2c01dae757c872383
|
combi |
2023-07-19 21:12:45 |
Linux |
Ubuntuタグが付けられた新着投稿 - Qiita |
Ubuntuでキーマップを変更する |
https://qiita.com/HBenpitsu/items/4f5fabe9f73e0ab34174
|
ubunt |
2023-07-19 21:32:32 |
Azure |
Azureタグが付けられた新着投稿 - Qiita |
Bing Chat Enterprise がプレビューになったので有効化した |
https://qiita.com/Olivia_0707/items/4b5aa26443e1341ac8dc
|
bingchatenterprise |
2023-07-19 21:04:35 |
技術ブログ |
Developers.IO |
「唯一生き残るのは、変化できる者である! 生物進化の原理に基づいた最適化手法の 遺伝的アルゴリズムのご紹介」というタイトルで DevelopersIO 2023 に登壇しました! #devio2023 |
https://dev.classmethod.jp/articles/devio2023-genetic-algorithm/
|
developersio |
2023-07-19 12:24:46 |
技術ブログ |
Developers.IO |
話題のLlama 2という大規模言語モデルをAmazon SageMaker JumpStartで動かしてみた |
https://dev.classmethod.jp/articles/sagemaker-jumpstart-llama2/
|
sagemakerjumpstart |
2023-07-19 12:08:16 |
海外TECH |
DEV Community |
Memoization using React.useMemo() |
https://dev.to/hardiksharma/memoization-using-reactusememo-142h
|
Memoization using React useMemo First we need to understand what memoization is Memoization is an optimization technique in which we accelerate our programs by caching the results of heavy function calls for the same inputs In simple terms for example we have an input say and we pass it through our function which takes a lot of time to execute Now if we need to calculate the result for input again then we need to perform the function again and it will again take that much time But not if we used memoization in the first go if we memoize the output for of that function then we just need to get that value from our memoized values and don t need to execute that function again for which in term will save us the time it takes for execution and will make our program much more optimized In this post we will understand how to use useMemo React hook useMemo useMemo is a React Hook that lets you cache the result of a calculation between re renders It accepts arguments a function that computes a result and the depedencies array const memoizedValue useMemo calculateValue dependencies During initial rendering useMemo calculateValue dependencies invokes calculateValue memoizes the calculation result and returns it to the component If the dependencies don t change during the next renderings then useMemo doesn t invoke calculateValue but returns the memoized value But if the dependencies change during re rendering then useMemo invokes calculateValue memoizes the new value and returns it const memoizedResult useMemo gt return heavyFunction A B A B In this case we have two dependencies A and B so for the first render it will let the heavyFunction run to get the output but in the re renders if the dependencies don t change then it ll not execute the function and will return the memoized value ExampleLet s take example of a classic recursion problem of calculating a factorial In factorial we often have the same input and without memoization the function always keeps on going to calculate the result but if we memoize the output for a value and return that then we will save a lot of recursion cycles and will just return the memoized value at that point only function fact n if n lt return return n fact n So this is a simple implementation of factorial of a number n using recursion Now if we have a whole component for this import useState useMemo from react export function CalculateFactorial const number setNumber useState const factorial useMemo gt fact number number const onChange event gt setNumber Number event target value return lt div gt Factorial of lt input type number value number onChange onChange gt is factorial lt div gt function fact n console log factorial called if n lt return return n fact n Every time you change the value of the number factorial called is logged to console That s expected However if we Re render without changing the number factorial called isn t logged to console because useMemo gt fact number number returns the memoized factorial calculation And hence saving us from calling the function again and recalculating useMemo is a Hook so you can only call it at the top level of your component or your own Hooks You can t call it inside loops or conditions I hope now you understand how useMemo works in React Thanks for reading |
2023-07-19 12:39:10 |
海外TECH |
DEV Community |
Running Slack App on Cloudflare Workers |
https://dev.to/seratch/running-slack-app-on-cloudflare-workers-3hhn
|
Running Slack App on Cloudflare WorkersRecently as a weekend hobby project I created a Slack app development framework for Cloudflare Workers and Vercel Edge Functions In this article I will explain the basics of Slack app development and how to use the following libraries If you are already familiar with Slack app development and want to try it out right away it might be faster to read the documentation by following the links from the README Slack App development basicsLet me explain a little about the basics of Slack app A Slack app is a mechanism for adding features such as bots that can converse in a Slack workspace workflows that respond to events that occur within Slack e g someone joining a channel slash commands shortcuts etc There are two ways to communicate between this Slack app and Slack s API server Request URL Set up a public endpoint in advance on the app configuration page at receive event data from Slack and respond with HTTP responses or Web API calls Socket Mode Receive event data from Slack via a WebSocket connection and respond with WebSocket messages or Web API calls The latter Socket Mode is useful for local development or when it is not possible to expose a public URL In this article I will guide you on how to develop a Slack app by setting the URL issued when deployed to Cloudflare Workers as the Request URL Digression New platform feature for Workflow BuilderBy the way since the beginning of this year a new app development mechanism for extending the Workflow Builder called the next generation automation platform has been added to the Slack platform In the Workflow Builder there is one starting point called a trigger and small processes called steps are connected in series to form a workflow The next generation platform allows you to create your own steps While it has become easier to automate within Slack there are things that cannot be done with existing app development For example as of you cannot add slash commands to the entire workspace or set a home tab for users Also note that this next generation platform feature is only available in paid Slack workspaces and usage charges apply for workflow executions that exceed the free tier For more details please read the series of articles I wrote a few months ago Wanna go without any libraries You might think if all I need to do with Cloudflare Workers fetch function is receiving request data at most calling Slack s Web API or other services and returning an HTTP response why not just implement it without bothering to use a library Of course you could implement all the things all yourself However considering the following points it s hard to deny that implementing everything yourself every time can be quite a hassle Request verificationThe Request URL of a Slack app is a URL that is publicly available on the internet and the source IP address of Slack s requests is not always guaranteed to be the same Therefore there is a risk that a malicious third party could mimic the payload sent from Slack and make requests As a countermeasure against this every HTTP request from Slack includes headers called x slack signature and x slack request timestamp It is recommended that the Slack app side verifies the x slack signature string using the Signing Secret shared only with Slack and also checks that the x slack request timestamp is not an old date and time For more details please read the official documentation To implement this as code that runs on Cloudflare Workers you first need to read the request body as plain text and then implement the specified verification logic Here is an example of such an implementation export default async fetch request Request env Env ctx ExecutionContext Promise lt Response gt Request text on Cloudflare Workers prints warning const blobRequestBody await request blob const rawBody string await blobRequestBody text if await verifySlackRequest env SLACK SIGNING SECRET request headers rawBody Valid request pattern else Invalid signature or timestamp return new Response invalid signature status async function verifySlackRequest signingSecret string requsetHeaders Headers requestBody string const timestampHeader requsetHeaders get x slack request timestamp if timestampHeader return false const fiveMinutesAgoSeconds Math floor Date now if Number parseInt timestampHeader lt fiveMinutesAgoSeconds return false const signatureHeader requsetHeaders get x slack signature if signatureHeader return false const textEncoder new TextEncoder return await crypto subtle verify HMAC await crypto subtle importKey raw textEncoder encode signingSecret name HMAC hash SHA false verify fromHexStringToBytes signatureHeader substring textEncoder encode v timestampHeader requestBody function fromHexStringToBytes hexString string const bytes new UintArray hexString length for let idx idx lt hexString length idx bytes idx parseInt hexString substring idx idx return bytes buffer Various formats of payloadsDue to historical reasons the format of the request body sent from Slack varies depending on the feature For the Events API it s Content Type application json but for other features it s application x www form urlencoded and the format of the contents differs between slash commands and other features To accommodate all patterns you need to implement something like this Various data patternsSlack s developer platform supports a wide variety of events And for each event there are quite a few edge cases and diverse data patterns when you delve into the details For example even channel messages which are the most basic data can be just text or can include rich text and interactive components using blocks from Block Kit When files emails etc are attached they are also added as attachments Also this is a point for improvement in Slack s developer support but there is a lack of comprehensive documentation on payloads So sorry For this reason using a library like the one I developed this time and receiving support from TypeScript types this area can be much easier Why don t you use Bolt Many of you may be aware of Bolt for JavaScript an npm package that serves as a framework for developing Slack apps It s an official full stack Slack app development framework developed by the Slack Developer Relations team of which I am a member to free Slack app developers from the hassles I mentioned above However unfortunately Bolt for JS depends on axios and other Node js APIs and cannot be used directly with Cloudflare Workers Although its name is for JavaScript it s more of a framework for Node js Also while Bolt for JS is designed to be extended with an interface called Receiver this aspect does not mesh well with the specification of processing requests as Cloudflare Workers fetch function This also becomes a constraint when you want to run it as part of a web application using modern frameworks like Next js or Nest js Since I often get questions about this I explored possible ways on the weekends and eventually created a library to circumvent the constraints of the Receiver At the moment there are no plans to transfer this Bolt HTTP Runner into the st party SDKs However I intend to continue maintaining it as much as I can as an individual so if you really want to try running it on Next js or something similar please use or fork this library I digressed a bit As you can see it s surprisingly difficult or was to properly create a Slack app on Cloudflare Workers For example this app that implements integration with ChatGPT is doing all the things I mentioned above on its own When I was playing with Cloudflare Workers on the weekend I thought I want to make it easier to create Slack apps and found the time to create the slack cloudflare workers and slack edge libraries Initially I put all the implementation into slack cloudflare workers but along the way I realized that most of it could also be used with Vercel Edge Functions and presumably other similar runtimes so I extracted that part as slack edge and left only the OAuth flow related implementation such as managing installation information using KV in slack cloudflare workers And while this library was originally a hobby project aimed solely at running on edge functions as I progressed with the implementation I was able to complete it as something that solved the challenges that Bolt for JS had been facing for a long time Streamlined Slack Web API clientImproved portability Eliminated all dependencies on axios and other rd party modules as well as Node js implemented to depend only on the Fetch APIImplemented more precise TypeScript typing for API response data especially the types of Block Kit components are much easier to use Support for Web APIs that are only available on the Next Generation PlatformSimplified code by completely removing support for deprecated APIsNative support for async code execution to avoid second timeoutsEquipped with a feature equivalent to Bolt for Python s Lazy Listeners as standard using the Fetch event s waitUntil commandResolved issues with TypeScript support in Bolt for JSChanged the behavior and payload type of app message listener to be more intuitiveBy removing support for deprecated features such as old style dialogs and button click events in attachments the type of app action listener arguments is more clearly definedDesigned to enable developers to more easily avoid the error saying you ve called ack method several times when matching multiple listenersMore strictly defined the types of returned values from listenersAdded features missing in Bolt for JSAdded middleware mechanism that runs before the authorize functionAdded support for Sign in with Slack OpenID Connect featureAdded Socket Mode for local development without other dependency libraries this is still experimental Added supports for emerging JavaScript TypeScript runtimes such as Deno and BunFor those who are not familiar with Slack app development it may seem like a lot of things that aren t quite understandable but the point is It s not just that it works on Cloudflare Workers it s also improved in many ways over Bolt for JS If you re going to create a Slack app with TypeScript in I think it s not an exaggeration to say that this is the easiest library to use As I mentioned earlier it s designed to work with Deno and Bun as well so you can use it even if you want to run your Deno Bun app on a container service e g ks Amazon ECS not just on edge functions Ideally I d like to incorporate the insights gained from this development into Bolt for JS but most of them would result in breaking changes and as the DevRel team most of the members are focusing on the next generation platform so the improvements I could add to the st party ones are still very limited I hope to be able to do it little by little Getting StaredThe introduction might be quite long Now let s finally create a Slack app Most of the things are already written in the library s README but I ll go over them with more details Install the wragnler CLI and create a projectInstall wrangler the CLI for developing Cloudflare Workers apps and create a project npm install g wrangler latestnpx wrangler generate my slack appProceed with the default specification set to Yes The console should output something like this npx wrangler generate my slack app ️wrangler Using npm as package manager WARNING The init command is no longer supported Please use npm create cloudflare my slack app instead The init command will be removed in a future version Created my slack app wrangler tomlWould you like to use git to manage this Worker …yesInitialized git repository at my slack appNo package json found Would you like to create one …yesCreated my slack app package jsonWould you like to use TypeScript …yesCreated my slack app tsconfig jsonWould you like to create a Worker at my slack app src index ts ›Fetch handlerCreated my slack app src index tsWould you like us to write your first test with Vitest …yesCreated my slack app src index test tsnpm WARN deprecated rollup plugin inject This package has been deprecated and is no longer maintained Please use rollup plugin inject npm WARN deprecated sourcemap codec Please use jridgewell sourcemap codec insteadadded packages and audited packages in s packages are looking for funding run npm fund for detailsfound vulnerabilitiesInstalled cloudflare workers types typescript and vitest into devDependenciesTo start developing your Worker run cd my slack app amp amp npm start To start testing your Worker run npm test To publish your Worker to the Internet run npm run deploy Then we ll add the library I developed slack cloudflare workers cd my slack appnpm i slack cloudflare workers latestIt s still the default sample code but if you run npm start you should see the following console output npm start gt my slack app start gt wrangler dev ️wrangler wrangler dev now uses local mode by default powered by Miniflare and workerd To run an edge preview session for your Worker use wrangler dev remote⎔Starting local server mf wrn The latest compatibility date supported by the installed Cloudflare Workers Runtime is but you ve requested Falling back to mf inf Ready on ╭ー╮│ b open a browser d open Devtools l turn off local mode c clear console x to exit │╰ー╯If you access from your browser you should see Hello World there Slack app settingsAccess in your web browser If you re not already logged into the Slack workspace you re planning to use for development in that browser log in first There s a button in the upper right corner that says Create New App Click on it select From an app manifest and create an app using the YAML configuration information after the video below just set it as is for now we ll change it later display information name cf worker test appfeatures bot user display name cf worker test app always online true shortcuts name Hey Cloudflare Wokers type global callback id hey cf workers description Say hi to CF Workers slash commands command hey cf workers url description Say hi to CF Workers usage hint Say hi to CF Workersoauth config scopes bot app mentions read chat write chat write public commandssettings event subscriptions request url bot events app mention interactivity is enabled true request url message menu options url Once the app settings are created you should see a button that says Install to Workspace Click on it and complete the installation to your Slack workspace Set env variablesCreate a file named dev vars in the top directory of the project and set it with the following content your App ID general Settings gt Basic Information gt App Credentials gt Signing SecretSLACK SIGNING SECRET your App ID install on team Settings gt Install App gt Bot User OAuth TokenSLACK BOT TOKEN xoxb SLACK LOGGING LEVEL DEBUGAs written in the comments SLACK SIGNING SECRET is in Settings gt Basic Information gt App Credentials gt Signing Secret on the app management screenSLACK BOT TOKEN is in Settings gt Install App gt Bot User OAuth Token on the app management screenPlease set these to the correct values and restart the npm start command We will check if they are set correctly in the next step Now the minimum preparation is complete Next we will check the communication with Slack Connecting to SlackBefore we start writing code let s check if the app we re about to develop can communicate correctly with Slack Edit src index tsWe ll flesh out the logic later but for now please paste the following minimum code into src index ts It will no longer be consistent with src index test ts but let s hold off maintaining the tests for now sorry this article does not cover how to write tests import SlackApp SlackEdgeAppEnv from slack cloudflare workers export default async fetch request Request env SlackEdgeAppEnv ctx ExecutionContext Promise lt Response gt const app new SlackApp env return await app run request ctx Configure Cloudflare TunnelAs mentioned at the beginning the Request URL needs to be a URL that is publicly available on the internet The App Manifest YAML settings we set earlier had a placeholder of We will change this to the correct value Please install the command following the steps below to use Cloudflare Tunnel For instructions other than macOS please follow the official guide brew install cloudflare cloudflare cloudflaredcloudflared tunnel url http localhost If it starts up correctly the console should output something like the following cloudflared tunnel url http localhost T Z INF Thank you for trying Cloudflare Tunnel Doing so without a Cloudflare account is a quick way to experiment and try it out However be aware that these account less Tunnels have no uptime guarantee If you intend to use Tunnels in production you should use a pre created named tunnel by following T Z INF Requesting new quick Tunnel on trycloudflare com T Z INF T Z INF Your quick Tunnel has been created Visit it at it may take some time to be reachable T Z INF T Z INF T Z INF Cannot determine default configuration path No file config yml config yaml in cloudflared cloudflare warp cloudflare warp etc cloudflared usr local etc cloudflared T Z INF Version T Z INF GOOS darwin GOVersion go GoArch amd T Z INF Settings map ha connections protocol quic url http localhost T Z INF cloudflared will not automatically update when run from the shell To enable auto updates run cloudflared as a service T Z INF Generated Connector ID b d ef ac cda T Z INF Initial protocol quic T Z INF ICMP proxy will use as source for IPv T Z INF ICMP proxy will use fe f fa f in zone en as source for IPv T Z INF Created ICMP proxy listening on T Z INF Created ICMP proxy listening on fe f fa f en T Z INF Starting metrics server on metrics T Z INF Registered tunnel connection connIndex connection f f f ddeaa event ip location NRT protocol quicIn this case is the available public URL Please enter this URL into Request URL under Features gt Event Subscriptions on the app configuration page If dev vars is set correctly it should display Verified as shown below Don t forget to press the Save Changes button at the bottom right to save the settings Please set this same URL on the following screens Features gt Interactivity amp Shortcuts gt Request URLFeatures gt Interactivity amp Shortcuts gt Select Menus gt Options Load URLFeatures gt Slash Commands gt Click the pencil icon for hey cf workers gt Request URLPlease be careful not to forget to press the save button on each screen Add functionalites to the appWe have the minimum preparations in place but this app has no implementation yet Try running the added slash command hey cf workers You should get an error with the dispatch failed code If you look at the console where you started the app with npm start you should see output like the following Received request body token zzz team id TEMJU team domain seratch channel id CHEDUWV channel name dev user id UEMK user name seratch command hey cf workers text api app id AHMVTXA is enterprise install false response url trigger id xxx No listener found mf inf POST Not Found ms ╭ー╮│ b open a browser d open Devtools l turn off local mode c clear console x to exit │╰ー╯The very simple code to respond to hey cf workers can be as follows const app new SlackApp env app command hey cf workers ack function must complete within seconds async req gt This text can be sent as an ephemeral message return What s up lazy function can do whatever you want to do asynchronously async req gt await req context respond text Hey This is an async response return await app run request ctx If everything is working correctly you should not get an error this time and you should see two ephemeral messages displayed You might be wondering Why are we passing two functions to app command here This mechanism of executing two functions ack lazy was originally something I devised for Function as a Service environments like AWS Lambda Slack s event delivery requires rd party apps to respond within seconds but in AWS Lambda once a function triggered by an HTTP request returns an HTTP response the runtime can be terminated so you can t perform time consuming asynchronous processing after returning a response As a solution for it Bolt for Python s Lazy Listeners were designed to handle asynchronous processing in a separate AWS Lambda execution with the same input However with Cloudflare Workers there is already a mechanism called the Fetch event s waitUntil command so there s no need for such a workaround and the same thing can be achieved with a simple implementation THIS IS AMAZING By the way when it s clear that the lazy processing is not needed you can omit the second function However if you go with this implementation make sure that all processing finishes within seconds If that s always true move the time consuming processing to the second asynchronous execution function app command hey cf workers async gt return What s up Slash commands and Block Kit interationsLet s improve the above slash command example further by adding a message with a Block Kit button and also add a process for when the button is pressed Post a message with a button in response to a slash command invocationapp command hey cf workers async gt return response type ephemeral text Click this blocks type section block id button text type mrkdwn text Click this accessory type button action id button action app action will match this string text type plain text text Button value hidden value app action button action async gt just acknowledge the request async context payload gt if context respond context respond sends a message using response url await context respond text You ve clicked it else await context client views open trigger id payload trigger id view type modal callback id test modal title type plain text text Button click close type plain text text Close blocks type section text type plain text text You ve clicked it This code overwrites the original message where the button was placed If you set the response type to in channel you can post it as a message that can be seen by other people in the channel The context respond is a utility that uses response url to send a message There is also an example of opening a modal that just conveys the same text in the else clause of the above code so please try that as well if you like Shortcuts and modal data submissionsNext I will introduce an example where a modal opens when a global shortcut is executed and input validation is performed when data is sent An example of a search function using external data is also included From a global shortcut execution to modal data submissionapp shortcut hey cf workers async gt just acknowledge the request async context body gt await context client views open trigger id body trigger id view type modal callback id test modal app view will match this string title type plain text text Test modal submit type plain text text Submit close type plain text text Cancel blocks type input block id memo label type plain text text Memo element type plain text input multiline true action id input type input block id category label type plain text text Category element type external select action id category search app options will match this string min query length Respond to a keyword search using the external select block element This listener must complete to return search results within seconds Therefore having lazy listeners is not supportedapp options category search async payload gt console log Query payload value In a real app perhaps you will filter the options by the keyword return options text type plain text text Work value work text type plain text text Family value family text type plain text text Running value running text type plain text text Random thoughts value random thought Handle modal data submissionsapp view test modal async payload gt Do all the things within seconds here const stateValues payload view state values console log JSON stringify stateValues null const memo payload view state values memo input value if memo length lt validation errors return response action errors errors memo The memo must be longer than characters Update the modal view as completed return response action update view type modal callback id test modal title type plain text text Test modal close type plain text text Close blocks type section text type plain text text Thank you If you just want to close the modal no need to return anything here async req gt you can do async jobs here Event delivery when someone mentions your app s botLasty here is an example of the Events API It s the app mention event which notifies when the bot user of the app is mentioned In the Events API there are no requirements that must be responded to synchronously within seconds so you can pass only the lazy function app event app mention async context gt await context say text Hey lt context userId gt is there anything I can help you with If you want to create an app that responds to other events you can specify the events from this list in the app configuration pages and reinstall it in the workspace to be able to receive them The payload argument of the listener function is resolved to the data type of the specified event payload If there are any deficiencies or errors please report them to this issue tracker and I will correct them I appreciate your help Deploy to CloudflareThat s it for the implementation of the features Now let s deploy this app to the Cloudflare Workers environment and see it in action wrangler deployIf the deployment is successful the console will output something like this wrangler deploy ️wrangler Total Upload KiB gzip KiBUploaded my slack app sec Published my slack app sec Current Deployment ID fde edde b bc acdbfcdbdIf you want to switch the app you just tested locally to production as is it s a bit of a hassle but you need to switch all four of the following settings that were previously set with the trycloudflare com URL to Features gt Event Subscriptions gt Request URLFeatures gt Interactivity amp Shortcuts gt Request URLFeatures gt Interactivity amp Shortcuts gt Select Menus gt Options Load URLFeatures gt Slash Commands gt Click the pencil icon for hey cf workers gt Request URLIf you plan to create a production app with a new separate configuration it would be easier to replace the part of the App Manifest YAML configuration file with the issued production URL and then create the app As the last step tell the Signing Secret and Bot User OAuth Token set in dev vars to the production secrets For this step as well if you are creating a new production app separately the values will be different so please obtain them from the Slack app management screen after installing them in your workspace and specify those values wrangler secret put SLACK SIGNING SECRETwrangler secret put SLACK BOT TOKENThe console outputs will look like this wrangler secret put SLACK SIGNING SECRET ️wrangler Enter a secret value … Creating the secret for the Worker my slack app Success Uploaded secret SLACK SIGNING SECRET wrangler secret put SLACK BOT TOKEN ️wrangler Enter a secret value … Creating the secret for the Worker my slack app Success Uploaded secret SLACK BOT TOKENOnce all the settings are complete please check to see if it works the same way when switched Perhaps the app running in the production environment can respond much more quickly More advanced topicsLet me briefly touch on some more advanced topics I may publish more blog posts for these topics in the near future Enable the OAuth flowThe steps above are for creating the simplest type of app one that only operates in a single workspace This article has gotten a bit long so I ll explain the details in another article but if you want the same app to work in other workspaces you can provide your own OAuth flow for installation so far we ve been installing using the installation flow provided by the Slack app management screen right This is about switching to your own and by properly managing the installation information for multiple workspaces you can distribute your app to other workspaces Also by implementing the OAuth flow you can not only get bot permissions like this article does but also receive permissions to view or operate some information from each user in the workspace allowing you to change statuses post messages access search results etc on behalf of the user if you install from the management screen without implementing the OAuth flow you can only issue your own user token The slack cloudflare workers library already provides a feature to implement Slack s OAuth flow using Cloudflare s KV For more details please refer to this document and the code examples Sign in with SlackThe library also supports the feature of logging into external sites with a Slack account compatible with OpenID Connect There is currently no documentation for this feature so I plan to first enhance the documentation and then introduce how to implement it in some form Run your app outside of edge functionsI mentioned this briefly in the middle of this article but this slack edge library is also compatible with Deno and Bun Also as of the time of this article s posting it s still in the experimental stage but it does support socket mode to some extent If you like this library and want to use it not only for edge functions but also for developing apps that run on container services running it on Deno Bun might be a good idea There are some sample codes here so please refer to them Wrap up Will anyone read this to the end This article has become quite long Thank you so much for reading this far Cloudflare Workers are truly convenient Especially the Fetch event s waitUntil command is absolutely fantastic I almost thought it was a feature designed specifically for Slack apps joking Also the development experience is very smooth and I think it can be used for various purposes not limited to Slack apps As for slack edge and slack cloudflare workers they are completely my personal hobby projects So I m not sure how much time I can devote to them but I hope to continue improving them at my own pace Currently they only support KV so I want to add support for other data stores as well Please feel free to give me any questions or feedback Also if you create something interesting using these I d love to hear about it That s all for now |
2023-07-19 12:16:25 |
海外TECH |
DEV Community |
Mastering Laravel: Top 10 Training Tasks to Showcase Your Skills |
https://dev.to/faridteymouri/mastering-laravel-top-10-training-tasks-to-showcase-your-skills-4l03
|
Mastering Laravel Top Training Tasks to Showcase Your SkillsLaravel the popular PHP framework empowers developers to build elegant and robust web applications As a Laravel enthusiast proving your proficiency requires more than theoretical knowledge Demonstrating your skills through practical projects is vital to stand out among peers and potential employers In this article we present ten challenging training tasks that cover various aspects of Laravel from user authentication to real time chat applications Completing these tasks will not only enhance your skills but also serve as an impressive portfolio to showcase your expertise User Authentication SystemA strong foundation in user authentication is crucial for any web application Create a secure and user friendly authentication system with features like user registration login password reset and email verification Emphasize security measures and best practices to protect user credentials CRUD ApplicationImplement a full fledged CRUD Create Read Update Delete application for managing a specific domain This project will demonstrate your ability to design efficient database schemas and build interactive user interfaces for seamless data management File Upload and ManagementDevelop a file upload and management system that allows users to upload files categorize them and perform CRUD operations on files Emphasize proper validation secure file storage and efficient file retrieval Real Time Chat ApplicationBuild a real time chat application using Laravel Broadcasting and Pusher Allow users to send and receive messages instantly showcasing your understanding of event broadcasting and handling real time updates API DevelopmentCreate a robust RESTful API for a specific domain such as a blog e commerce platform or social media app Implement JWT authentication and provide well documented endpoints for various actions like creating updating and deleting resources Task Scheduler and Cron JobsLeverage Laravel s task scheduler and cron jobs to automate repetitive tasks such as sending periodic emails or processing data at scheduled intervals Showcase your proficiency in managing recurring tasks efficiently Role Based Access Control RBAC Implement role based access control to manage user permissions effectively Create a system where administrators managers and regular users have different levels of access to various functionalities Search FunctionalityDevelop a powerful search functionality using Laravel Scout and Algolia or Elasticsearch Allow users to search for resources efficiently and demonstrate your ability to build robust search systems Integration with Third Party APIsIntegrate your application with popular third party APIs such as Google Maps Twitter or payment gateways like Stripe Showcase your expertise in working with external services and handling API responses effectively Localization and Multilingual SupportEnhance your application by adding localization and multilingual support Enable users to switch between different languages and provide translations for various content ConclusionMastering Laravel requires hands on experience and practical application of concepts By completing these ten training tasks you will showcase your ability to design and build real world web applications using Laravel s full potential Focus on adhering to Laravel s best practices maintaining clean and organized code and providing comprehensive documentation for each task A diverse portfolio of projects will undoubtedly impress potential employers and clients certifying you as a skilled and competent Laravel developer Happy coding and best of luck in showcasing your Laravel mastery |
2023-07-19 12:16:20 |
海外TECH |
DEV Community |
I am working on the latest software technology |
https://dev.to/shreyvijayvargiya/i-am-working-on-the-latest-software-technology-m6d
|
I am working on the latest software technologyReact Native Open AI Blockchain the latest tech stack Under the HoodThis is quite an interesting thing months ago I emailed the founder for the work related opportunity I ve found my current company on a product hunt and directly emailed the founder asking for the workLuckily the company is looking for a mobile app developer and they are working on blockchain and AI the most latest technology in today s world I ve already mentioned this story in my LinkedIn post regarding how one cold email helps me to land a remote job easily Latest Tech StackThis is cool shit I met the entire dev team and nobody knows how to develop a mobile app So I am alone to decide what to choose and what to reject Our objective was to develop a non custodial wallet mobile app for our users So it will be a web blockchain mobile app and have AI integrated tools developed using Open AI Now for mobile apps I choose react nativefor blockchain I go for Moralis Web js and ethers js amp for Open AI we have APIs for the same React Native Blockchain Open AI APIs is very rare you will find this combination ChallengesThis is another set of questions Since it s new so third party package support will be in question and in development or under progress Sometimes finding solutions and debugging is the task it takes hours to actually find and solve the issue Redux new toolkit with react native gt version was the taskIntegrating web js in react native is not that straightforwardI am using M so the M chip with an Android emulator and simulator is the painMost of the time is consumed in installing and integrating or creating a development setup SolutionSince I ve mentioned the challenges so let me give a solution also The easiest way is to start with ƒorking the already existing repository We are also developing a wallet and uniswap has this react native open source GitHub repository on which their IOS and Android apps are built Uniswap WalletAnother way is using Chat GPT to install all these packages and create your own custom setup I ve started everything from scratch and if you want to get started in web and react native here is the starter repository Starter Web react native repositoryFeel free to ask any questions or guidance I ll be happy to help Plan of ActionSince I am still developing the application so can t be sure what should be the best plan of action Here is my approachStart with repository setup by installing packages emulators or simulatorsRepository architecture along with finalising of the technology stack such as Redux toolkit Icons library UI library version control analytics testing librariesStart with designs and create all the design components and develop all screensAPI integration and state management in entire applicationWrite test cases for security reasons and detect APIs failuresAdd analytics and event tracking methods along with Over the Air update integrationRelease the APK AAB to the play store and app store respectively Keep developingShreyiHateReading |
2023-07-19 12:14:29 |
海外TECH |
DEV Community |
What is Event Bubbling? event bubbling in JS |
https://dev.to/diwakarkashyap/what-is-event-bubbling-event-bubbling-in-js-4kn7
|
What is Event Bubbling event bubbling in JSEvent bubbling in JavaScript refers to the way events are handled and propagated through the different elements of a webpage When an event occurs on an element such as a button click the event doesn t just trigger on that specific element Instead it also triggers on its parent elements all the way up to the topmost element usually the document Imagine a scenario where you have a button inside a div and that div is inside another div If you click the button the click event will not only be detected by the button itself but also by its parent div and the outer div This bubbling behavior allows you to capture events at different levels of the DOM hierarchy For example you can have a single event listener attached to the outer div and it will be triggered for events that occur on the button the inner div or the outer div itself Event bubbling can be useful because it simplifies event handling Instead of attaching event listeners to each individual element you can attach a single listener to a parent element and let the event bubble up to it This reduces the amount of code you need to write and makes it easier to manage events However in some cases you may want to stop the event from bubbling further up the DOM hierarchy You can use the event stopPropagation method inside an event handler to prevent the event from triggering on parent elements This can be handy when you want to isolate the event handling to a specific element and prevent any further handling by its ancestors In summary event bubbling in JavaScript refers to the propagation of events from a child element to its parent elements It simplifies event handling by allowing you to capture events at higher levels in the DOM hierarchy Thank you for reading this blog follow me on Twitter I regularly share blogs and post on Javascript React Web development and opensource contributionTwitter Github |
2023-07-19 12:02:48 |
Apple |
AppleInsider - Frontpage News |
Unity launches game creator program for Vision Pro developers |
https://appleinsider.com/articles/23/07/19/unity-launches-game-creator-program-for-vision-pro-developers?utm_medium=rss
|
Unity launches game creator program for Vision Pro developersGame engine maker Unity has launched a developer program to help its users build experiences to run on the forthcoming Apple Vision Pro Unity is a subscription platform for developers to create games though it has also heavily relied on advertising which saw it releasing an App Tracking Transparency workaround that ultimately didn t work Now the company says it has been working with Apple to create a new beta program for enabling Unity developers to create apps for Vision Pro We re thrilled to be working with Apple Ralph Hauwert SVP GM Unity Runtime Editor and Ecosystems said in a statement so our ecosystem of millions of game and app developers can bring their Unity apps to this exciting new platform Read more |
2023-07-19 12:59:46 |
Apple |
AppleInsider - Frontpage News |
How to use improved dictation features in macOS Sonoma |
https://appleinsider.com/inside/macos-sonoma/tips/how-to-use-improved-dictation-features-in-macos-sonoma?utm_medium=rss
|
How to use improved dictation features in macOS SonomaApple has not made giant changes to dictation in macOS Sonoma but yet again the small improvements it has introduced will significantly help users Here s what s new in Dictation and how to make the most of it Apple includes its improvements to dictation as one of the key benefits of upgrading to macOS Sonoma but it s one that you can easily miss That s because on the surface dictation appears to be exactly the same as before It s identical in how you turn on the feature right down to the one toggle you need to click in System Settings But what happens now when you click Dictation to on is subtly different Read more |
2023-07-19 12:31:27 |
海外TECH |
Engadget |
The best student discounts we found for 2023 |
https://www.engadget.com/best-student-discounts-140038070.html?src=rss
|
The best student discounts we found for Your college years can be some of the best of your life but we know it can be tough to enjoy them when you re scrounging every dollar for textbooks food and if you re lucky the occasional outing with friends Money is tight when you re a student and that financial stress can be compounded by the reality of having to stay on top of your studies If there s a silver lining it s student discounts Many companies offer their products and apps for less to those struggling through lectures writing term papers and studying for finals We ve compiled a list of the best deals you can get on useful services along with some things you ll enjoy in your down time Just keep in mind that most of these offers require you to prove your status as a student either by signing up with your edu email address or providing some form of student identification ShoppingAmazonAmazon Prime StudentIf you re not piggybacking off of your parents Amazon Prime account you can have the subscription for less while you re in school College students can get Prime Student for free for six months then it costs only per month after that That comes out to about per year and the membership includes the same perks as regular Prime does including free two day shipping free same day delivery in select areas and access to the entire Prime Video library Shop Amazon Prime StudentBest BuyWhile it doesn t offer a specific student discount Best Buy has a student deal hub page where you can find gadgets on sale You ll find discounts on a bunch of gear that students would need including laptops headphones monitors software and more Best Buy also has a tool that will help students find the right computer for their needs that only requires them to answer a few questions before providing them a number of options Shop Best Buy Student DealsAppleApple offers some deals to students and educators in the form of knocking down the prices of its most popular laptops and tablets There isn t a flat percentage rate across all products the discounts vary by device For example right now students can get a MacBook Air M starting at which is less than the normal starting price and the iPad Pros start at which represents a discount These are decent savings if you must have a brand new Apple product but those with tighter budgets should also consider Apple s refurb program Also for students can get up to a gift card and percent off AppleCare when they purchase a qualifying Mac or iPad and they ll get one month free of Apple Music and Apple TV as well Shop Apple s back to school promosSamsungMuch like Apple Samsung doesn t offer a blanket discount across all of its products for students But you can save depending on what you re looking to buy For example you can save hundreds on the latest Galaxy S and foldable smartphones up to on Samsung Galaxy Book laptops and an extra percent off Samsung wireless earbuds Shop Samsung s back to school promosMicrosoftMicrosoft also provides students and educators with up to and additional percent off its gadgets including most of its Surface family And the online store doesn t only sell Microsoft made devices You can also find Windows PCs from Lenovo HP Acer and others there at discounted prices Shop Microsoft s back to school promosStreamingEngadgetSpotifySpotify Premium s student plan gives you full ad free access to the music streaming service plus a subscription to the ad supported Hulu plan for only per month This is a great discount considering you d pay roughly per month if you were to buy each service separately Buy Spotify Premium StudentPandoraPandora also offers students its Premium membership for per month Pandora s offering doesn t include any additional services but you do get an ad free experience personalized music unlimited skips and unlimited offline play Plus you ll get days of free use before your payments kick in Buy Pandora Premium StudentApple MusicApple also slashes percent off its Apple Music subscription for students bringing it down to per month The offer is available for up to months so you can enjoy the rate for the entirety of your college experience What s more the company bundles Apple TV in this student offer so you can watch Apple originals like Ted Lasso and Severance Buy Apple Music Student membershipParamount Paramount s student discount knocks percent off the Essentials monthly plan so you ll end up paying around per month for access to the service s content with limited commercials With this subscription you can watch shows like Star Trek Strange New Worlds South Park RuPaul s Drag Race and more but just keep in mind that this particular plan doesn t include access to your local CBS station Buy Paramount StudentTidalTidal provides student discounts on all of its services ーeligible high school and college students can get up to percent off its subscription plans Tidal is still often overshadowed by Spotify and Apple Music but these discounts are a good way to give it a try without spending too much money Buy Tidal StudentHuluCollege students can sign up for Hulu s ad supported plan for only per month That s less than the normal price and a great deal considering all of the content that Hulu has to offer think The Handmaid s Tale Grey s Anatomy Rick amp Morty and more Yes you have to deal with commercials but it s a small price to pay to binge watch shows like Brooklyn Nine Nine which can provide a much needed laugh when you re drowning in coursework Buy Hulu ad supported for studentsHeadspaceBeing a student is stressful even in the best of times but now it s even more difficult to concentrate and find peace Headspace is just one of many meditation and mindfulness apps available that can help with that but it stands apart with an excellent student discount for the entire year or less than a normal annual membership In addition to a large library of meditation lessons and routines to follow Headspace recently added SleepCasts a collection of soothing voices reading bedtime stories to help you fall asleep as well as “mindful workout routines Buy Headspace Student planToolsEngadgetAdobe Creative CloudYou re probably using Adobe products if you re studying anything related to digital art or design Adobe Creative Cloud is the industry standard in this space but the entire suite of programs is quite expensive at per month Thankfully Adobe has education pricing for students that drops the entire creative suite to per month for the first year That includes the big programs like Photoshop CC and Illustrator CC along with Lightroom CC Premiere Pro CC Adobe XD and more After your first year the monthly cost increases to per month While not ideal it s still more affordable for students than it is for industry professionals If you re not tied to Adobe programs you might also consider Affinity Photo Designer and Publisher apps from Serif each for the Mac or Windows versions which compete with Photoshop Illustrator and InDesign respectively Buy Adobe CC for studentsAbleton LiveRegardless of whether you re studying music production students can get percent off Ableton Live Standard or Suite for as long as they are enrolled full time That brings Live Standard down to and Suite down to ーgreat discounts on some of the best music software available right now Buy Ableton LiveMicrosoft Many students have to use Microsoft tools on the regular If your college or university doesn t provide you with an account you can still get Microsoft for free by taking advantage of the company s student and educator discount This gives you access to Word Excel PowerPoint OneNote and even Microsoft Teams free of charge which is a solid deal considering an annual subscription costs Get Microsoft UlyssesSpending all day and night writing papers is even more frustrating when you don t have all your writing organized in one place Ulysses is a popular writing app for mac iOS that can be used for note taking as well as thesis writing with features like auto save and auto backup word count writing goals markup plain text support and DropBox integration Normally Ulysses costs per year but students can get it for only every six months or per year There isn t a direct alternative for Windows users but you do have options including Scrivener IA Writer and FocusWriter Buy UlyssesEvernoteEvernote can be an indispensable tool if you like to keep all of your thoughts in one place ーeverything from class notes to web clippings to to do lists Students can get percent off Professional which is the way to go because it syncs your notes across unlimited devices gives you offline access lets you annotate PDFs and search saved documents Buy Evernote ProfessionalGithub Student Developer PackAspiring developers can sign up for Github s Student Developer Pack which includes discounts and resources that developers can use to learn create projects and more Github partnered with a bunch of companies including Educative Canva Namecheap Bootstrap Studio and others to offer students access to many of the services they ll need as the expand their skills Get Github Student Developer PackSquarespace Student planWhether you re itching to get a jump start on your portfolio or just want an online space to show off your work Squarespace is a good option as it gives students a percent discount on any of its annual plans for the first year Squarespace is one of many website builders out there but it s particularly popular with creative professionals Its customizable templates make it easy to build a website and make it look exactly how you want it Plus you can upgrade down the line to add things like website analytics custom JavaScript and CSS and e commerce Buy SquarespaceSurfsharkOne of our favorite VPNs Surfshark offers percent off for students plus two months free when you sign up for a two year plan You can connect an unlimited number of devices to one Surfshark account which will be good for students who want access across their phone laptop smart TV and other gadgets It also has more than servers that you can access across countries giving you plenty of connection options Subscribe to Surfshark VPNNordVPNNordVPN s student discount gives you two years of the service for less than Like most of the top picks in our VPN guide NordVPN offers access to thousands of servers in a number of countries and you can connect from almost any device you could imagine It also has a kill switch feature that will prevent you from making unprotected connections should the VPN accidentally drop Subscribe to NordVPNDashlaneDashlane offers one year of its Premium plan for free to all students with a valid university email address It s one of our top picks in our best password managers guide thanks to its easy to use apps and its focus on secure sharing The latter could be particularly useful for students if they have friends and roommates with which they need to share account credentials Subscribe to DashlaneNordPassAnother one of our favorite password managers NordPass offers students a two year Premium plan for just over plus an extra month for free Its wide platform compatibility makes it a great pick if you re always logging in from different devices You can stay logged in on up to six devices simultaneously and it has browser extensions for Chrome Firefox Edge and Opera Subscribe to NordPassNewsEngadgetYou shouldn t rely on Twitter to be your sole source of news With foreign wars new viruses Supreme Court decisions and upcoming elections making headlines daily it s important to get your news from reliable sources Yes it s daunting to get into the news on a regular basis but it s crucial to know what s going on in the country and the world as a whole Here are some reputable news organizations that offer student discounts on their monthly or annual subscription plans The Atlantic Starts at per year for digital only access The New York Times every four weeks for a base subscription The Washington Post every four weeks for digital only access The Wall Street Journal Starting at every four weeks for the WSJ Digital pack This article originally appeared on Engadget at |
2023-07-19 12:55:05 |
海外TECH |
Engadget |
Netflix axes its $10 ‘Basic’ plan in the US and UK |
https://www.engadget.com/netflix-axes-its-10-basic-plan-in-the-us-and-uk-123350885.html?src=rss
|
Netflix axes its Basic plan in the US and UKNetflix has removed its Basic tier option ーthe service s most affordable one that doesn t come with ads ーin the US and the UK The company has updated its Plans and Pricing page to say that new and rejoining members in the US and the UK will no longer be able to sign up for the Basic tier Meanwhile those already on the plan can keep their membership as is until they cancel or change their subscription The streaming giant initially axed the tier in Canada where users are typically the first to experience changes to the service It was also one of the countries where Netflix started its password sharing crackdown which the company eventually implemented across the globe nbsp As Cord Busters notes Netflix has been steering its audiences towards the Standard Ad Supported plan for a while now and has previously made the Basic plan virtually invisible during sign up Now the Basic plan truly no longer exists in some regions Without it users in the US and UK will have to pay at least and £ a month respectively if they don t want their streaming experience to be interrupted by ads The Standard plan supports streaming on two devices at a time and can stream content in Full HD It also allows users to download content for offline viewing on two devices and gives them the ability to add an extra member who doesn t live with them for an additional fee nbsp Still the Basic option worked just fine for those who don t mind HD streaming on a single device only want to download content on one phone or tablet and don t need to add an extra person to their account If they don t want to pay over more for a Standard plan they now have to make do with the Standard Ad Supported tier that costs a month in the US and £ in the UK It supports Full HD streams and viewing on two devices at a time like the no ads Standard plan but it doesn t have offline viewing and the option to add a member Subscribers can expect to see an average of minutes of ads an hour at around to seconds each which of course they cannot skip nbsp This article originally appeared on Engadget at |
2023-07-19 12:33:50 |
海外ニュース |
Japan Times latest articles |
F. Marinos thump Celtic, overcome Daizen Maeda’s homecoming hat trick |
https://www.japantimes.co.jp/sports/2023/07/19/soccer/j-league/fmarinos-celtic-friendly-maeda-miyaichi/
|
nissan |
2023-07-19 21:18:11 |
ニュース |
BBC News - Home |
Rishi Sunak apologises to UK’s LGBT veterans for military gay ban |
https://www.bbc.co.uk/news/uk-66242611?at_medium=RSS&at_campaign=KARANGA
|
people |
2023-07-19 12:14:16 |
ニュース |
BBC News - Home |
Travis King: US soldier in N Korea had been held after fighting in Seoul |
https://www.bbc.co.uk/news/world-asia-66219603?at_medium=RSS&at_campaign=KARANGA
|
police |
2023-07-19 12:50:51 |
ニュース |
BBC News - Home |
Afghanistan: Women protest against beauty salon closures |
https://www.bbc.co.uk/news/world-66244408?at_medium=RSS&at_campaign=KARANGA
|
kabul |
2023-07-19 12:16:23 |
コメント
コメントを投稿